'use client' import CartSummary from '@/components/CartSummary' import Layout from '@/hoc/Layout' import { NextPage } from 'next' // import CartItem from '../components/CartItem' import TitleBack from '../components/TitleBack' import ShippingMethodSelector from '../components/ShippingMethodSelector' import { Location } from 'iconsax-react' import { useGetCart, useSaveShipmentCart, useShippingCost } from '../hooks/useCartData' // import { CartItemType } from '../types/Types' import { useGetProfile } from '@/app/profile/hooks/useProfileData' import Link from 'next/link' import { useState, useEffect } from 'react' import { toast } from '@/components/Toast' import { extractErrorMessage } from '@/helpers/errorUtils' const CartShipping: NextPage = () => { const { data: cartData, isLoading: cartLoading, error: cartError } = useGetCart() const { data: shippingData, isLoading: shippingLoading, error: shippingError } = useShippingCost() const { data: profileData, isLoading: profileLoading, error: profileError } = useGetProfile() const { mutate: saveShipmentCart } = useSaveShipmentCart() // State برای ذخیره انتخاب‌های روش ارسال const [selectedShipments, setSelectedShipments] = useState>({}) const [isSavingShipment, setIsSavingShipment] = useState(false) // بارگذاری انتخاب‌های قبلی از localStorage useEffect(() => { const savedShipments = localStorage.getItem('selectedShipments') if (savedShipments) { setSelectedShipments(JSON.parse(savedShipments)) } }, []) // ذخیره انتخاب‌ها در localStorage useEffect(() => { if (Object.keys(selectedShipments).length > 0) { localStorage.setItem('selectedShipments', JSON.stringify(selectedShipments)) } }, [selectedShipments]) // پاک کردن انتخاب‌های نامعتبر وقتی shippingData تغییر می‌کند useEffect(() => { if (shippingData?.results?.shipping) { const validShopIds = new Set(shippingData.results.shipping.map(shop => shop.shopId)) const filteredShipments = Object.fromEntries( Object.entries(selectedShipments).filter(([shopId]) => validShopIds.has(shopId)) ) if (Object.keys(filteredShipments).length !== Object.keys(selectedShipments).length) { setSelectedShipments(filteredShipments) } } }, [shippingData, selectedShipments]) // هندلر انتخاب روش ارسال const handleShipmentSelect = (shopId: string, shipperId: number) => { setSelectedShipments(prev => ({ ...prev, [shopId]: shipperId })) } // چک کردن اینکه آیا همه فروشگاه‌ها روش ارسال انتخاب کرده‌اند const allShipmentsSelected = shippingData?.results?.shipping?.every(shop => selectedShipments[shop.shopId] !== undefined ) || false // هندلر پاک کردن همه انتخاب‌ها const handleClearSelections = () => { setSelectedShipments({}) localStorage.removeItem('selectedShipments') } // هندلر ذخیره انتخاب‌های ارسال و انتقال به صفحه پرداخت const handleProceedToPayment = async () => { if (!allShipmentsSelected) return setIsSavingShipment(true) // فیلتر کردن selectedShipments تا فقط shop هایی که در shippingData وجود دارند const validShopIds = new Set(shippingData?.results?.shipping?.map(shop => shop.shopId) || []) // تبدیل selectedShipments به فرمت مورد نیاز API const shipmentsInfo = Object.entries(selectedShipments) .filter(([shopId]) => validShopIds.has(shopId)) .map(([shopId, shipperId]) => ({ shopId, shipmentId: shipperId })) // ذخیره انتخاب‌ها در API await new Promise((resolve, reject) => { saveShipmentCart({ shipmentsInfo }, { onSuccess: () => { resolve() window.location.href = '/cart/payment' }, onError: (error) => { setIsSavingShipment(false) toast(extractErrorMessage(error)) reject(error) } }) }) } if (cartLoading || shippingLoading || profileLoading) { return (
در حال بارگذاری...
) } if (cartError || shippingError || profileError) { return (
خطا در بارگذاری اطلاعات
) } const cart = cartData?.results?.cart const items = cart?.items || [] const profile = profileData?.results?.info if (!items.length) { return (
سبد خرید شما خالی است
) } // محاسبه هزینه ارسال بر اساس انتخاب‌های کاربر const totalShippingCost = shippingData?.results?.shipping?.reduce((total, shop) => { const selectedShipperId = selectedShipments[shop.shopId] const selectedShipper = shop.shippers?.find(shipper => shipper.shipperId === selectedShipperId) return total + (selectedShipper?.totalShippingCost || shop.shippers?.[0]?.totalShippingCost || 0) }, 0) || 0 // محاسبه قیمت نهایی const finalTotal = (cart?.payable_price || 0) + totalShippingCost return (
آدرس تحویل سفارش
{profile?.userAddress && (
{profile.userAddress.address} {profile.userAddress.city && `، ${profile.userAddress.city.name}`} {profile.userAddress.province && `، ${profile.userAddress.province.name}`}
)}
ویرایش
{/*
{items.map((item: CartItemType, index: number) => { if (!item || !item.product || !item.variant) { return null } return ( ) })}
*/}
{!allShipmentsSelected && (
لطفا برای همه فروشگاه‌ها روش ارسال انتخاب کنید
)}
) } export default function CartShippingWithLayout() { return ( ) }