import React, { useEffect, useState } from 'react';
import { Button, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useRouter } from 'next/router';
import { useDispatch, useSelector } from 'react-redux';
import { InterDataType, InterListType, PaginationProps } from '@/api/interface';
import {
  MallOrderListType,
  UavOrderStatusListType,
} from '@/api/interface/order';
import { OrderAPI } from '@/api/modules/order';
import TableItem from '@/components/orderTableItem';
import { RootState } from '@/store';
import { setGlobalData } from '@/store/module/globalData';
import { SystemState } from '@/store/module/system';

// 列表类型
type ListType = InterListType<MallOrderListType>;
// 状态列表
type StatusType = InterDataType<UavOrderStatusListType>;

const MallOrderListTable: React.FC = () => {
  // store
  const dispatch = useDispatch();
  // system
  const system = useSelector((state: RootState) => state.system) as SystemState;
  // 路由钩子
  const router = useRouter();
  // 订单状态列表
  const [statusList, setStatusList] = useState<StatusType>();
  // 订单列表
  const [tableData, setTableData] = useState<ListType>();
  // 表格分页配置
  const [pagination, setPagination] = useState<
    PaginationProps & { totalCount: number }
  >({
    pageSize: 10,
    pageNo: 1,
    totalCount: 0,
  });
  // 获取商城订单
  const getGoodsOrderList = async () => {
    const res = await OrderAPI.getMallOrderList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    });
    if (res && res.code === '200') {
      const { list, pageNo, pageSize, totalCount } = res.result; // 解构
      setPagination({
        ...pagination,
        pageNo,
        pageSize,
        totalCount,
      });
      setTableData(list || []);
      // console.log('商城订单 --->', list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getGoodsOrderList().then();
  };
  // 获取订单状态字典
  const getMallOrderStatusList = async () => {
    const res = await OrderAPI.uavOrderStatusList();
    if (res && res.code === '200') {
      setStatusList(res.result);
    }
  };
  // 获取订单价格
  const getOrderPrice = (item: ListType[0]) => {
    const total = item?.skuDTOList?.reduce(
      (sum, value) => sum + Number(value.orderNum) * Number(value.unitPrice),
      0,
    );
    // 求和
    return `￥${total?.toLocaleString()}`;
  };
  // 跳转商品详情
  const handleProduct = async (item: ListType[0]['skuDTOList'][0]) => {
    await router.push(`/mall/product/${item?.mallGoodsId}`);
  };
  // 跳转订单详情
  const handleDetail = async (item: ListType[0]) => {
    await router.push(`/order/product/${item?.id}`);
  };
  // 页面挂载
  useEffect(() => {
    if (!system?.token) {
      dispatch(
        setGlobalData({
          loginModalVisible: true,
          loginModalBack: true,
        }),
      );
    } else {
      getMallOrderStatusList().then();
      getGoodsOrderList().then();
    }
  }, [system]);
  const tableColumns: ColumnsType<ListType[0]> = [
    {
      title: '商品',
      dataIndex: 'id',
      align: 'center',
      width: 200,
      render: (_text, record) => (
        <TableItem
          td={<>订单编号：{record?.orderNo}</>}
          tr={
            <>
              {record.skuDTOList?.map((i, j) => (
                <div className="flex items-start pt-2" key={j}>
                  <img
                    className="h-12 w-12"
                    src={i.skuImage}
                    alt={i.tradeName}
                  />
                  <div className="ml-2 flex flex-col items-start">
                    <Button
                      className="h-auto w-48 text-ellipsis p-0 text-left"
                      type="link"
                      onClick={() => handleProduct(i)}
                    >
                      {i.tradeName}
                    </Button>
                    <div>
                      {Object.entries(JSON.parse(i.productSpec)).map(
                        (v, index) => (
                          <span key={index} className="mr-2 last:mr-0">
                            {v.join('：')}
                          </span>
                        ),
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </>
          }
        />
      ),
    },
    {
      title: '数量',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => (
        <TableItem
          tr={
            <>
              {record.skuDTOList?.reduce(
                (sum, value) => sum + Number(value?.orderNum),
                0,
              )}
            </>
          }
        />
      ),
    },
    {
      title: '价格',
      dataIndex: 'id',
      align: 'center',
      render: (_text, record) => (
        <TableItem
          td={<>下单时间：{record?.createTime}</>}
          tr={<>{getOrderPrice(record)}</>}
        />
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'statusCode',
      align: 'center',
      width: 150,
      render: (text) => (
        <TableItem
          tr={<>{statusList?.find((i) => i.code === text)?.status || text}</>}
        />
      ),
    },
    {
      title: '操作',
      dataIndex: 'id',
      align: 'center',
      width: 150,
      render: (_text, record) => (
        <TableItem
          tr={
            <>
              <Button type={'link'} onClick={() => handleDetail(record)}>
                订单详情
              </Button>
            </>
          }
        />
      ),
    },
  ];
  return (
    <>
      <Table
        rowKey={'id'}
        bordered={false}
        dataSource={tableData}
        columns={tableColumns}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) =>
            paginationChange(page, pageSize),
          showTotal: (total, range) =>
            `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
    </>
  );
};

export default MallOrderListTable;
