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 {listShopOrderGoods} from "@/api/shop/shopOrderGoods";
import {ShopOrderGoods} from "@/api/shop/shopOrderGoods/model";
import dayjs from "dayjs";
import './index.scss'

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

  const getOrderStatusText = (order: ShopOrder) => {
    // 优先检查订单状态
    if (order.orderStatus === 2) return '已取消';
    if (order.orderStatus === 3) return '取消中';
    if (order.orderStatus === 4) return '退款申请中';
    if (order.orderStatus === 5) return '退款被拒绝';
    if (order.orderStatus === 6) return '退款成功';
    if (order.orderStatus === 7) return '客户端申请退款';

    // 检查支付状态 (payStatus为boolean类型)
    if (!order.payStatus) return '待付款';

    // 已付款后检查发货状态
    if (order.deliveryStatus === 10) return '待发货';
    if (order.deliveryStatus === 20) return '待收货';
    if (order.deliveryStatus === 30) return '已收货';

    // 最后检查订单完成状态
    if (order.orderStatus === 1) return '已完成';
    if (order.orderStatus === 0) return '未使用';

    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 listShopOrderGoods({ orderId: Number(orderId) });
        if (goodsRes && goodsRes.length > 0) {
          setOrderGoodsList(goodsRes);
        }
      }).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)} />
      </CellGroup>

      <CellGroup title="商品信息">
        {orderGoodsList.map((item, index) => (
          <Cell key={index}>
            <div className={'flex items-center'}>
              <Image src={item.image || '/default-goods.png'} width="80" height="80" lazyLoad={false} />
              <div className={'ml-2'}>
                <div className={'text-sm font-bold'}>{item.goodsName}</div>
                {item.spec && <div className={'text-gray-500 text-xs'}>规格：{item.spec}</div>}
                <div className={'text-gray-500 text-xs'}>数量：{item.totalNum}</div>
                <div className={'text-red-500 text-lg'}>￥{item.price}</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 && <Button size="small" onClick={() => console.log('取消订单')}>取消订单</Button>}
          {!order.payStatus && <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;
