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

const InfiniteUlStyle: CSSProperties = {
  marginTop: '84px',
  height: '82vh',
  width: '100%',
  padding: '0',
  overflowY: 'auto',
  overflowX: 'hidden',
}
const tabs = [
  {
    index: 0,
    key: '全部',
    title: '全部'
  },
  {
    index: 1,
    key: '待付款',
    title: '待付款'
  },
  {
    index: 2,
    key: '待发货',
    title: '待发货'
  },
  {
    index: 3,
    key: '已收货',
    title: '已收货'
  },
  {
    index: 4,
    key: '已完成',
    title: '已完成'
  }
]

function OrderList(props: any) {
  const [list, setList] = useState<ShopOrder[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [tapIndex, setTapIndex] = useState<string | number>('0')

  console.log(props.statusBarHeight, 'ppp')

  const getOrderStatusParams = (index: string | number) => {
    let params: { payStatus?: number; deliveryStatus?: number; orderStatus?: number } = {};
    switch (index) {
      case '1': // 待付款
        params.payStatus = 0;
        break;
      case '2': // 待发货
        params.payStatus = 1;
        params.deliveryStatus = 10;
        break;
      case '3': // 已收货
        params.deliveryStatus = 30;
        break;
      case '4': // 已完成
        params.orderStatus = 1;
        break;
      case '0': // 全部
      default:
        break;
    }
    return params;
  };

  const reload = async (resetPage = false) => {
    const currentPage = resetPage ? 1 : page;
    const params = getOrderStatusParams(tapIndex);
    pageShopOrder({ page: currentPage, ...params }).then(res => {
      let newList: ShopOrder[] | undefined = [];
      if (res?.list && res?.list.length > 0) {
        newList = resetPage ? res.list : list?.concat(res.list);
        setHasMore(true);
      } else {
        newList = res?.list;
        setHasMore(false);
      }
      setList(newList || []);
      setPage(currentPage);
    });
  };

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

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

  return (
    <>
      <Tabs
        align={'left'}
        className={'fixed left-0'}
        style={{ top: '84px'}}
        tabStyle={{ backgroundColor: 'transparent'}}
        value={tapIndex}
        onChange={(paneKey) => {
          setTapIndex(paneKey)
        }}
      >
        {
          tabs?.map((item, index) => {
            return <TabPane key={index} title={item.title}></TabPane>
          })
        }
      </Tabs>
      <div style={InfiniteUlStyle} id="scroll">
        <InfiniteLoading
          target="scroll"
          hasMore={hasMore}
          onLoadMore={reloadMore}
          onScroll={() => {

          }}
          onScrollToUpper={() => {

          }}
          loadingText={
            <>
              加载中
            </>
          }
          loadMoreText={
            <>
              没有更多了
            </>
          }
        >
          {list?.map(item => {
            return (
              <Cell style={{padding: '16px'}} onClick={() => Taro.navigateTo({url: `/shop/orderDetail/index?orderId=${item.orderId}`})}>
                <Space direction={'vertical'} className={'w-full flex flex-col'}>
                  <div className={'order-no flex justify-between'}>
                    <span className={'text-gray-700 font-bold text-sm'}
                          onClick={(e) => {e.stopPropagation(); copyText(`${item.orderNo}`)}}>{item.orderNo}</span>
                    <span className={'text-orange-500'}>待付款</span> {/* 这里可以根据item.orderStatus显示不同的状态 */}
                  </div>
                  <div
                    className={'create-time text-gray-400 text-xs'}>{dayjs(item.createTime).format('YYYY年MM月DD日 HH:mm:ss')}</div>
                  <div className={'goods-info'}>
                    <div className={'flex items-center'}>
                      <div className={'flex items-center'}>
                        <Avatar
                          src='34'
                          size={'45'}
                          shape={'square'}
                        />
                        <div className={'ml-2'}>{item.realName}</div>
                      </div>
                      <div className={'text-gray-400 text-xs'}>{item.totalNum}件商品</div>
                    </div>
                  </div>
                  <div className={' w-full text-right'}>实付金额：￥{item.payPrice}</div>
                  <Space className={'btn flex justify-end'}>
                    <Button size={'small'}>发货</Button>
                  </Space>
                </Space>
              </Cell>
            )
          })}
        </InfiniteLoading>
      </div>
    </>
  )
}

export default OrderList
