import {useEffect, useState} from "react";
import {Cell, CellGroup, Image, Space, Button} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {ShopOrder} from "@/api/shop/shopOrder/model";
import {getShopOrder} from "@/api/shop/shopOrder";
import {listOrderGoods} from "@/api/system/orderGoods";
import {OrderGoods} from "@/api/system/orderGoods/model";
import {getShopGoods} from "@/api/shop/shopGoods";
import dayjs from "dayjs";
import './index.scss'

interface OrderGoodsDetail extends OrderGoods {
  goodsName?: string;
  goodsImage?: string;
}

const OrderDetail = () => {
  const [order, setOrder] = useState<ShopOrder | null>(null);
  const [orderGoodsList, setOrderGoodsList] = useState<OrderGoodsDetail[]>([]);
  const router = Taro.getCurrentInstance().router;
  const orderId = router?.params?.orderId;

  const getOrderStatusText = (orderStatus?: number, payStatus?: number) => {
    if (payStatus === 0) return '待付款';
    switch (orderStatus) {
      case 0: return '未使用';
      case 1: return '已完成';
      case 2: return '已取消';
      case 3: return '取消中';
      case 4: return '退款申请中';
      case 5: return '退款被拒绝';
      case 6: return '退款成功';
      case 7: return '客户端申请退款';
      default: return '未知状态';
    }
  };

  const getPayTypeText = (payType?: number) => {
    switch (payType) {
      case 0: return '余额支付';
      case 1: return '微信支付';
      case 102: return '微信Native';
      case 2: return '会员卡支付';
      case 3: return '支付宝';
      case 4: return '现金';
      case 5: return 'POS机';
      default: return '未知支付方式';
    }
  };

  useEffect(() => {
    if (orderId) {
      console.log('shop-goods',orderId)
      getShopOrder(Number(orderId)).then(async (res) => {
        setOrder(res);

        // 获取订单商品列表
        const goodsRes = await listOrderGoods({ orderId: Number(orderId) });
        if (goodsRes && goodsRes.length > 0) {
          const goodsDetailsPromises = goodsRes.map(async (item) => {
            console.log(item,'item.>>>')
            const shopGoods = await getShopGoods(Number(item.goodsId));
            return {
              ...item,
              goodsName: shopGoods?.name,
              goodsImage: shopGoods?.image,
            };
          });
          const detailedGoodsList = await Promise.all(goodsDetailsPromises);
          setOrderGoodsList(detailedGoodsList);
        }
      }).catch(error => {
        console.error("Failed to fetch order detail:", error);
      });
    }
  }, [orderId]);

  if (!order) {
    return <div>加载中...</div>;
  }

  return (
    <div className={'order-detail-page'}>
      <CellGroup title="订单信息">
        <Cell title="订单编号" description={order.orderNo} />
        <Cell title="下单时间" description={dayjs(order.createTime).format('YYYY-MM-DD HH:mm:ss')} />
        <Cell title="订单状态" description={getOrderStatusText(order.orderStatus, order.payStatus)} />
      </CellGroup>

      <CellGroup title="商品信息">
        {orderGoodsList.map((item, index) => (
          <Cell key={index}>
            <div className={'flex items-center'}>
              <Image src={item.goodsImage} width="80" height="80" />
              <div className={'ml-2'}>
                <div className={'text-sm font-bold'}>{item.goodsName}</div>
                <div className={'text-gray-500 text-xs'}>数量：{item.totalNum}</div>
                <div className={'text-red-500 text-lg'}>￥{item.payPrice}</div>
              </div>
            </div>
          </Cell>
        ))}
      </CellGroup>

      <CellGroup title="收货信息">
        <Cell title="收货人" description={order.realName} />
        <Cell title="手机号" description={order.phone} />
        <Cell title="收货地址" description={order.address} />
      </CellGroup>

      <CellGroup title="支付信息">
        <Cell title="支付方式" description={getPayTypeText(order.payType)} />
        <Cell title="实付金额" description={`￥${order.payPrice}`} />
      </CellGroup>

      <div className={'fixed-bottom'}>
        <Space>
          {order.payStatus === 0 && <Button size="small" onClick={() => console.log('取消订单')}>取消订单</Button>}
          {order.payStatus === 0 && <Button size="small" type="primary" onClick={() => console.log('立即支付')}>立即支付</Button>}
          {order.orderStatus === 1 && <Button size="small" onClick={() => console.log('申请退款')}>申请退款</Button>}
          {order.deliveryStatus === 20 && <Button size="small" type="primary" onClick={() => console.log('确认收货')}>确认收货</Button>}
        </Space>
      </div>
    </div>
  );
};

export default OrderDetail;
