import { View, ScrollView, Text } from '@tarojs/components' import { useQuery, useMutation } from '@tanstack/react-query' import { useState, useEffect } from 'react' import Taro from '@tarojs/taro' import { deliveryAddressClient, orderClient } from '@/api' import { InferResponseType, InferRequestType } from 'hono' import { Navbar } from '@/components/ui/navbar' import { Card } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { useAuth } from '@/utils/auth' import { useCart } from '@/utils/cart' import { Image } from '@/components/ui/image' type AddressResponse = InferResponseType type Address = AddressResponse['data'][0] type CreateOrderRequest = InferRequestType['json'] interface CheckoutItem { id: number name: string price: number image: string quantity: number } export default function OrderSubmitPage() { const { user } = useAuth() const { clearCart } = useCart() const [selectedAddress, setSelectedAddress] = useState
(null) const [orderItems, setOrderItems] = useState([]) const [totalAmount, setTotalAmount] = useState(0) // 获取地址列表 const { data: addresses } = useQuery({ queryKey: ['delivery-addresses', user?.id], queryFn: async () => { const response = await deliveryAddressClient.$get({ query: { page: 1, pageSize: 100, filters: JSON.stringify({ userId: user?.id }) } }) if (response.status !== 200) { throw new Error('获取地址失败') } return response.json() }, enabled: !!user?.id, }) // 创建订单 const createOrderMutation = useMutation({ mutationFn: async () => { if (!selectedAddress || orderItems.length === 0) { throw new Error('请完善订单信息') } const goodsDetail = JSON.stringify( orderItems.map(item => ({ goodsId: item.id, name: item.name, price: item.price, num: item.quantity })) ) const orderData: CreateOrderRequest = { orderNo: `ORD${Date.now()}`, userId: user!.id, amount: totalAmount, payAmount: totalAmount, goodsDetail, addressId: selectedAddress.id, recevierName: selectedAddress.name, receiverMobile: selectedAddress.phone, address: `${selectedAddress.province?.name || ''}${selectedAddress.city?.name || ''}${selectedAddress.district?.name || ''}${selectedAddress.town?.name || ''}${selectedAddress.address}`, orderType: 1, payType: 0, payState: 0, state: 0 } const response = await orderClient.$post({ json: orderData }) if (response.status !== 201) { throw new Error('创建订单失败') } return response.json() }, onSuccess: (data) => { // 清空购物车 clearCart() Taro.showToast({ title: '订单创建成功', icon: 'success' }) // 跳转到订单详情页 Taro.redirectTo({ url: `/pages/order-detail/index?id=${data.id}` }) }, onError: (error) => { Taro.showToast({ title: error.message || '创建订单失败', icon: 'none' }) } }) // 页面加载时获取订单数据 useEffect(() => { // 从购物车获取数据 const checkoutData = Taro.getStorageSync('checkoutItems') const cartData = Taro.getStorageSync('mini_cart') if (checkoutData && checkoutData.items) { setOrderItems(checkoutData.items) setTotalAmount(checkoutData.totalAmount) } else if (cartData && cartData.items) { // 使用购物车数据 const items = cartData.items const total = items.reduce((sum: number, item: CheckoutItem) => sum + (item.price * item.quantity), 0) setOrderItems(items) setTotalAmount(total) } // 设置默认地址 if (addresses?.data) { const defaultAddress = addresses.data.find(addr => addr.isDefault === 1) setSelectedAddress(defaultAddress || addresses.data[0] || null) } }, [addresses]) // 选择地址 const handleSelectAddress = () => { Taro.navigateTo({ url: '/pages/address-manage/index' }) } // 提交订单 const handleSubmitOrder = () => { if (!selectedAddress) { Taro.showToast({ title: '请选择收货地址', icon: 'none' }) return } createOrderMutation.mutate() } return ( Taro.navigateBack()} /> {/* 收货地址 */} 收货地址 {selectedAddress ? ( {selectedAddress.name} {selectedAddress.phone} {selectedAddress.isDefault === 1 && ( 默认 )} {selectedAddress.province?.name || ''} {selectedAddress.city?.name || ''} {selectedAddress.district?.name || ''} {selectedAddress.town?.name || ''} {selectedAddress.address} ) : ( )} {/* 商品列表 */} 商品信息 {orderItems.map((item) => ( {item.name} ¥{item.price.toFixed(2)} × {item.quantity} ¥{(item.price * item.quantity).toFixed(2)} ))} {/* 订单金额 */} 订单金额 商品金额 ¥{totalAmount.toFixed(2)} 运费 ¥0.00 实付款 ¥{totalAmount.toFixed(2)} {/* 支付方式 */} 支付方式 微信支付 {/* 底部提交栏 */} 合计: ¥{totalAmount.toFixed(2)} ) }