'use client'; /* eslint-disable */ import LogosProduct from '@/assets/product.png'; import { BASE_URL } from '@/shared/config/api/URLs'; import { useCartId } from '@/shared/hooks/cartId'; import formatDate from '@/shared/lib/formatDate'; import formatPrice from '@/shared/lib/formatPrice'; import { cn } from '@/shared/lib/utils'; import { Button } from '@/shared/ui/button'; import { Calendar } from '@/shared/ui/calendar'; import { Form, FormControl, FormField, FormItem, FormMessage, } from '@/shared/ui/form'; import { Input } from '@/shared/ui/input'; import { Label } from '@/shared/ui/label'; import { Popover, PopoverContent, PopoverTrigger } from '@/shared/ui/popover'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/shared/ui/select'; import { Textarea } from '@/shared/ui/textarea'; import { userStore } from '@/widgets/welcome/lib/hook'; import { zodResolver } from '@hookform/resolvers/zod'; import { Map, Placemark, Polygon, YMaps, ZoomControl, } from '@pbe/react-yandex-maps'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { AxiosError } from 'axios'; import { format } from 'date-fns'; import { uz } from 'date-fns/locale'; import { Calendar as CalIcon, CheckCircle2, Clock, Loader2, LocateFixed, MapPin, } from 'lucide-react'; import { useTranslations } from 'next-intl'; import Image from 'next/image'; import { useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import z from 'zod'; import { cart_api, OrderCreateBody } from '../lib/api'; import { orderForm } from '../lib/form'; interface CoordsData { lat: number; lon: number; polygon: [number, number][][]; } // Yetkazib berish vaqt oraliqlar const deliveryTimeSlots = [ { id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' }, { id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' }, { id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' }, { id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' }, { id: 5, label: '17:00 - 19:00', start: '17:00', end: '19:00' }, { id: 6, label: '19:00 - 21:00', start: '19:00', end: '21:00' }, ]; const OrderPage = () => { const t = useTranslations(); const { user } = userStore(); const form = useForm>({ resolver: zodResolver(orderForm), defaultValues: { comment: '', lat: '41.311081', long: '69.240562', }, }); const [cart, setCart] = useState(null); const { cart_id } = useCartId(); const [orderSuccess, setOrderSuccess] = useState(false); const queryClinet = useQueryClient(); const { data } = useQuery({ queryKey: ['clear_cart', cart], queryFn: () => cart_api.clear_cart(cart!), enabled: !!cart, }); console.log(data); const { mutate, isPending } = useMutation({ mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body), onSuccess: (res) => { const message = JSON.parse(res.data.response); if (message.successes.length > 0) { setOrderSuccess(true); setCart(cart_id); queryClinet.refetchQueries({ queryKey: ['cart_items'] }); } else { toast.error(t('Xatolik yuz berdi'), { richColors: true, position: 'top-center', }); } }, onError: (error: AxiosError) => { ( error.response?.data as { items: { non_field_errors: string[] }[] } ).items ?.flatMap((i) => i.non_field_errors || []) .forEach((msg: string) => toast.error(msg, { richColors: true, position: 'top-center' }), ); }, }); const { data: cartItems } = useQuery({ queryKey: ['cart_items', cart_id], queryFn: () => cart_api.get_cart_items(cart_id!), enabled: !!cart_id, select: (data) => data.data.cart_item, }); // Yetkazib berish vaqti uchun state const [deliveryDate, setDeliveryDate] = useState(); const [selectedTimeSlot, setSelectedTimeSlot] = useState(''); const subtotal = cartItems?.reduce((sum, item) => { if (item.product.prices.length === 0) return sum; // narx yo'q bo'lsa qo'shmaymiz // Eng yuqori narxni olish const maxPrice = Math.max( ...item.product.prices.map((p) => Number(p.price)), ); return sum + maxPrice * item.quantity; }, 0) || 0; // cartItems bo'sh bo'lsa 0 qaytaradi const [coords, setCoords] = useState({ latitude: 41.311081, longitude: 69.240562, zoom: 12, }); const [polygonCoords, setPolygonCoords] = useState< [number, number][][] | null >(null); const getCoords = async (name: string): Promise => { const res = await fetch( `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(name)}&format=json&polygon_geojson=1&limit=1`, ); const data = await res.json(); if (data.length > 0 && data[0].geojson) { const lat = parseFloat(data[0].lat); const lon = parseFloat(data[0].lon); let polygon: [number, number][][] = []; if (data[0].geojson.type === 'Polygon') { polygon = data[0].geojson.coordinates.map((ring: [number, number][]) => ring.map((coord: [number, number]) => [coord[1], coord[0]]), ); } else if (data[0].geojson.type === 'MultiPolygon') { polygon = data[0].geojson.coordinates.map( (poly: [number, number][][]) => poly[0].map((coord: [number, number]) => [coord[1], coord[0]]), ); } return { lat, lon, polygon }; } return null; }; const handleMapClick = ( e: ymaps.IEvent, ) => { const [lat, lon] = e.get('coords'); setCoords({ latitude: lat, longitude: lon, zoom: 18 }); form.setValue('lat', lat.toString(), { shouldDirty: true }); form.setValue('long', lon.toString(), { shouldDirty: true }); }; const handleShowMyLocation = () => { if (!navigator.geolocation) { alert("Sizning brauzeringiz geolokatsiyani qo'llab-quvvatlamaydi"); return; } navigator.geolocation.getCurrentPosition( (position) => { const lat = position.coords.latitude; const lon = position.coords.longitude; setCoords({ latitude: lat, longitude: lon, zoom: 14 }); form.setValue('lat', lat.toString()); form.setValue('long', lon.toString()); }, (error) => { alert('Joylashuv aniqlanmadi: ' + error.message); }, ); }; const cityValue = form.watch('city'); useEffect(() => { if (!cityValue || cityValue.length < 3) return; const timeout = setTimeout(async () => { const result = await getCoords(cityValue); if (!result) return; setCoords({ latitude: result.lat, longitude: result.lon, zoom: 12, }); setPolygonCoords(result.polygon); form.setValue('lat', result.lat.toString(), { shouldDirty: true }); form.setValue('long', result.lon.toString(), { shouldDirty: true }); }, 700); return () => clearTimeout(timeout); }, [cityValue]); function onSubmit(value: z.infer) { if (!cartItems || cartItems.length === 0) { toast.error(t("Savatcha bo'sh"), { richColors: true, position: 'top-center', }); return; } // Yetkazib berish vaqtini tekshirish if (!deliveryDate) { toast.error(t('Yetkazib berish sanasini tanlang'), { richColors: true, position: 'top-center', }); return; } if (!selectedTimeSlot) { toast.error(t('Yetkazib berish vaqtini tanlang'), { richColors: true, position: 'top-center', }); return; } const order_products = cartItems .filter( (item) => item.product.prices && item.product.prices.length > 0 && item.product.prices[0].price_type?.code && item.product.prices[0].price, ) .map((item) => ({ inventory_kind: 'G', product_code: item.product.code, on_balance: 'Y', order_quant: item.quantity, price_type_code: item.product.prices![0].price_type.code, product_price: item.product.prices![0].price, warehouse_code: 'wh1', })); if (user) { mutate({ order: [ { filial_code: process.env.NEXT_FILIAL_CODE!, delivery_date: formatDate.format(deliveryDate, 'DD.MM.YYYY'), room_code: process.env.NEXT_ROOM_CODE!, deal_time: formatDate.format(deliveryDate, 'DD.MM.YYYY'), robot_code: process.env.NEXT_ROBOT_CODE!, status: 'B#N', sales_manager_code: process.env.NEXT_SALES_MANAGER_CODE!, person_code: user?.username, currency_code: '860', owner_person_code: user?.username, note: value.comment, order_products: order_products, }, ], }); } else { toast.error(t('Xatolik yuz berdi'), { richColors: true, position: 'top-center', }); } } if (orderSuccess) { return (

{t('Buyurtma qabul qilindi!')}

{t('Buyurtmangiz muvaffaqiyatli qabul qilindi')}

); } return (

{t('Buyurtmani rasmiylashtirish')}

{t("Ma'lumotlaringizni to'ldiring")}

{/* Contact Information */}
(