import {Avatar, Cell, Space, Tabs, Button, TabPane, Image} from '@nutui/nutui-react-taro'
import {useEffect, useState, CSSProperties} from "react";
import {View} from '@tarojs/components'
import Taro from '@tarojs/taro';
import {InfiniteLoading} from '@nutui/nutui-react-taro'
import dayjs from "dayjs";
import {pageShopOrder, removeShopOrder, updateShopOrder} from "@/api/shop/shopOrder";
import {ShopOrder, ShopOrderParam} from "@/api/shop/shopOrder/model";
import {listShopOrderGoods} from "@/api/shop/shopOrderGoods";
import {ShopOrderGoods} from "@/api/shop/shopOrderGoods/model";
import {copyText} from "@/utils/common";

const getInfiniteUlStyle = (showSearch: boolean = false): CSSProperties => ({
  marginTop: showSearch ? '65px' : '44px', // 如果显示搜索框，增加更多的上边距
  height: showSearch ? '75vh' : '82vh', // 相应调整高度
  width: '100%',
  padding: '0',
  overflowY: 'auto',
  overflowX: 'hidden',
  boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)',
})

// 统一的订单状态标签配置，与后端 statusFilter 保持一致
const tabs = [
  {
    index: 0,
    key: '全部',
    title: '全部',
    description: '所有订单',
    statusFilter: undefined // 不传statusFilter，显示所有订单
  },
  {
    index: 1,
    key: '待付款',
    title: '待付款',
    description: '等待付款的订单',
    statusFilter: 0 // 对应后端：pay_status = false
  },
  {
    index: 2,
    key: '待发货',
    title: '待发货',
    description: '已付款待发货的订单',
    statusFilter: 1 // 对应后端：pay_status = true AND delivery_status = 10
  },
  {
    index: 3,
    key: '待收货',
    title: '待收货',
    description: '已发货待收货的订单',
    statusFilter: 3 // 对应后端：pay_status = true AND delivery_status = 20
  },
  {
    index: 4,
    key: '已完成',
    title: '已完成',
    description: '已完成的订单',
    statusFilter: 5 // 对应后端：order_status = 1
  },
  {
    index: 5,
    key: '已取消',
    title: '已取消',
    description: '已取消/退款的订单',
    statusFilter: 6 // 对应后端：order_status = 6 (已退款)
  }
]

// 扩展订单接口，包含商品信息
interface OrderWithGoods extends ShopOrder {
  orderGoods?: ShopOrderGoods[];
}

interface OrderListProps {
  data: ShopOrder[];
  onReload?: () => void;
  searchParams?: ShopOrderParam;
  showSearch?: boolean;
}

function OrderList(props: OrderListProps) {
  const [list, setList] = useState<OrderWithGoods[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [tapIndex, setTapIndex] = useState<string | number>(0)
  const [loading, setLoading] = useState(false)

  // 获取订单状态文本
  const getOrderStatusText = (order: ShopOrder) => {
    console.log(order,'order')

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

    // 检查支付状态 (payStatus为boolean类型，false/0表示未付款，true/1表示已付款)
    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 getOrderStatusColor = (order: ShopOrder) => {
    // 优先检查订单状态
    if (order.orderStatus === 2) return 'text-gray-500'; // 已取消
    if (order.orderStatus === 4) return 'text-orange-500'; // 退款申请中
    if (order.orderStatus === 5) return 'text-red-500'; // 退款被拒绝
    if (order.orderStatus === 6) return 'text-green-500'; // 退款成功
    if (order.orderStatus === 7) return 'text-orange-500'; // 客户端申请退款

    // 检查支付状态
    if (!order.payStatus) return 'text-orange-500'; // 等待买家付款

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

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

    return 'text-gray-600'; // 默认颜色
  };

  // 使用后端统一的 statusFilter 进行筛选
  const getOrderStatusParams = (index: string | number) => {
    let params: ShopOrderParam = {};
    // 添加用户ID过滤
    params.userId = Taro.getStorageSync('UserId');

    // 获取当前tab的statusFilter配置
    const currentTab = tabs.find(tab => tab.index === Number(index));
    if (currentTab && currentTab.statusFilter !== undefined) {
      params.statusFilter = currentTab.statusFilter;
    }

    console.log(`Tab ${index} (${currentTab?.title}) 筛选参数:`, params);
    return params;
  };

  const reload = async (resetPage = false) => {
    setLoading(true);
    const currentPage = resetPage ? 1 : page;
    const statusParams = getOrderStatusParams(tapIndex);
    const searchConditions = {
      page: currentPage,
      ...statusParams,
      ...props.searchParams
    };
    console.log('订单筛选条件:', {
      tapIndex,
      statusParams,
      searchConditions
    });

    try {
      const res = await pageShopOrder(searchConditions);
      let newList: OrderWithGoods[] = [];

      if (res?.list && res?.list.length > 0) {
        // 为每个订单获取商品信息
        const ordersWithGoods = await Promise.all(
          res.list.map(async (order) => {
            try {
              const orderGoods = await listShopOrderGoods({ orderId: order.orderId });
              return {
                ...order,
                orderGoods: orderGoods || []
              };
            } catch (error) {
              console.error('获取订单商品失败:', error);
              return {
                ...order,
                orderGoods: []
              };
            }
          })
        );

        // 合并数据
        newList = resetPage ? ordersWithGoods : list?.concat(ordersWithGoods);
        setHasMore(true);
      } else {
        newList = [];
        setHasMore(false);
      }

      setList(newList || []);
      setPage(currentPage);
      setLoading(false);
    } catch (error) {
      console.error('加载订单失败:', error);
      setLoading(false);
    }
  };

  const reloadMore = async () => {
    setPage(page + 1);
    reload();
  };

  // 格式化日期为后端期望的格式
  const formatDateForBackend = (date: Date) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  };

  // 确认收货
  const confirmReceive = async (order: ShopOrder) => {
    try {
      await updateShopOrder({
        ...order,
        deliveryStatus: 30, // 已收货
        orderStatus: 1 // 已完成
      });
      Taro.showToast({
        title: '确认收货成功',
      });
      reload(true); // 重新加载列表
      props.onReload?.(); // 通知父组件刷新
    } catch (error) {
      Taro.showToast({
        title: '确认收货失败',
      });
    }
  };

  // 取消订单
  const cancelOrder = async (order: ShopOrder) => {
    try {
      await removeShopOrder(order.orderId);
      Taro.showToast({
        title: '订单已删除',
      });
      reload(true); // 重新加载列表
      props.onReload?.(); // 通知父组件刷新
    } catch (error) {
      console.error('取消订单失败:', error);
      Taro.showToast({
        title: '取消订单失败',
      });
    }
  };

  useEffect(() => {
    reload(true); // 首次加载或tab切换时重置页码
  }, [tapIndex]); // 监听tapIndex变化

  useEffect(() => {
    reload(true); // 搜索参数变化时重置页码
  }, [props.searchParams]); // 监听搜索参数变化

  return (
    <>
      <Tabs
        align={'left'}
        className={'fixed left-0'}
        style={{
          top: '44px',
          zIndex: 998,
          borderBottom: '1px solid #e5e5e5'
        }}
        tabStyle={{
          backgroundColor: '#ffffff',
          boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
        }}
        value={tapIndex}
        onChange={(paneKey) => {
          console.log('Tab切换到:', paneKey, '对应状态:', tabs[paneKey]?.title);
          setTapIndex(paneKey)
        }}
      >
        {
          tabs?.map((item, index) => {
            return (
              <TabPane
                key={index}
                title={loading && tapIndex === index ? `${item.title}...` : item.title}
              ></TabPane>
            )
          })
        }
      </Tabs>
      <div style={getInfiniteUlStyle(props.showSearch)} id="scroll">
        <InfiniteLoading
          target="scroll"
          hasMore={hasMore}
          onLoadMore={reloadMore}
          onScroll={() => {

          }}
          onScrollToUpper={() => {

          }}
          loadingText={
            <>
              加载中
            </>
          }
          loadMoreText={
            <>
              没有更多了
            </>
          }
        >
          {list?.map((item, index) => {
            return (
              <Cell key={index} style={{padding: '16px'}} onClick={() => Taro.navigateTo({url: `/shop/orderDetail/index?orderId=${item.orderId}`})}>
                <Space direction={'vertical'} className={'w-full flex flex-col'}>
                  <View className={'order-no flex justify-between'}>
                    <View className={'text-gray-600 font-bold text-sm'}
                          onClick={(e) => {e.stopPropagation(); copyText(`${item.orderNo}`)}}>{item.orderNo}</View>
                    <View className={`${getOrderStatusColor(item)} font-medium`}>{getOrderStatusText(item)}</View>
                  </View>
                  <div
                    className={'create-time text-gray-400 text-xs'}>{dayjs(item.createTime).format('YYYY年MM月DD日 HH:mm:ss')}</div>

                  {/* 商品信息 */}
                  <div className={'goods-info'}>
                    {item.orderGoods && item.orderGoods.length > 0 ? (
                      item.orderGoods.map((goods, goodsIndex) => (
                        <div key={goodsIndex} className={'flex items-center mb-2'}>
                          <Image
                            src={goods.image || '/default-goods.png'}
                            width="50"
                            height="50"
                            lazyLoad={false}
                            className={'rounded'}
                          />
                          <div className={'ml-2 flex-1'}>
                            <div className={'text-sm font-bold'}>{goods.goodsName}</div>
                            {goods.spec && <div className={'text-gray-500 text-xs'}>规格：{goods.spec}</div>}
                            <div className={'text-gray-500 text-xs'}>数量：{goods.totalNum}</div>
                          </div>
                          <div className={'text-sm'}>￥{goods.price}</div>
                        </div>
                      ))
                    ) : (
                      <div className={'flex items-center'}>
                        <Avatar
                          src='/default-goods.png'
                          size={'50'}
                          shape={'square'}
                        />
                        <div className={'ml-2'}>
                          <div className={'text-sm'}>{item.title || '订单商品'}</div>
                          <div className={'text-gray-400 text-xs'}>{item.totalNum}件商品</div>
                        </div>
                      </div>
                    )}
                  </div>

                  <div className={'w-full text-right'}>实付金额：￥{item.payPrice}</div>

                  {/* 操作按钮 */}
                  <Space className={'btn flex justify-end'}>
                    {/* 待付款状态：显示取消订单和立即支付 */}
                    {(!item.payStatus) && item.orderStatus !== 2 && (
                      <Space>
                        <Button size={'small'} onClick={(e) => {e.stopPropagation(); cancelOrder(item)}}>取消订单</Button>
                        <Button size={'small'} type="primary" onClick={(e) => {e.stopPropagation(); console.log('立即支付')}}>立即支付</Button>
                      </Space>
                    )}
                    {/* 待收货状态：显示确认收货 */}
                    {item.deliveryStatus === 20 && (
                      <Button size={'small'} type="primary" onClick={(e) => {e.stopPropagation(); confirmReceive(item)}}>确认收货</Button>
                    )}
                    {/* 已完成状态：显示申请退款 */}
                    {item.orderStatus === 1 && (
                      <Button size={'small'} onClick={(e) => {e.stopPropagation(); console.log('申请退款')}}>申请退款</Button>
                    )}
                    {/* 退款相关状态的按钮可以在这里添加 */}
                  </Space>
                </Space>
              </Cell>
            )
          })}
        </InfiniteLoading>
      </div>
    </>
  )
}

export default OrderList
