import SearchBox from '~/components/search-box';
import { Button, Image, Table } from 'antd';
import { useEffect, useState } from 'react';
import { OrderManageAPI } from '~/api';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { useNavigate } from 'react-router-dom';
import { InterListType, InterReqListType, PaginationProps } from '~/api/interface';
import { listPurchaseOrderType } from '~/api/interface/orderManageType';
import TableItem from '~/components/order/selfTableItem';
import SureOrder from '~/components/order/productOrder/sureOrder';
import './index.scss';
import { filterObjAttr } from '~/utils';
import dayjs from 'dayjs';
import qs from 'query-string';

// 采购订单列表返回类型
type procurementOrderListType = InterListType<listPurchaseOrderType>;
// 采购订单列表请求类型
type procurementOrderParamsType = InterReqListType<listPurchaseOrderType>;

const ProcurementOrderList = () => {
  const navigate = useNavigate();

  // 订单操作按钮列表
  const operateBtnList = [
    {
      btnStr: '确认订单',
      status: 200,
      btnClick: (record: procurementOrderListType[0]) => {
        setCurrentOrderItem(record);
        setSureOrderShow(true);
      },
    },
    {
      btnStr: '凭证审批',
      status: 420,
      btnClick: (record: procurementOrderListType[0]) => {},
    },
    {
      btnStr: '发货',
      status: 500,
      btnClick: (record: procurementOrderListType[0]) => {},
    },
  ];
  // 订单状态
  const [orderStatusList, setOrderStatusList] = useState<{ value: number; label: string }[]>([]);
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: number | undefined; label: string }[]
  >([]);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);

  // 表格数据
  const [tableData, setTableData] = useState<procurementOrderListType>([]);
  const [currentOrderItem, setCurrentOrderItem] = useState<procurementOrderListType[0]>();
  const [query, setQuery] = useState<procurementOrderParamsType>();
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const tableColumns: ColumnsType<procurementOrderListType[0]> = [
    {
      title: '商品',
      dataIndex: 'userName',
      width: 280,
      align: 'center',
      fixed: 'left',
      render: (_text, record) => (
        <TableItem
          td={
            <div>
              <span>订单编号：</span>
              <span>{record.orderNo}</span>
            </div>
          }
          tr={record?.skuDTOList?.map((v) => (
            <div key={v.id} className='procurement-sku-item'>
              <Image src={v.skuImage} className='sku-img' />
              <div className='sku-info'>
                <div className='info-name'>{v.tradeName}</div>
                <div className='info-spec'>
                  {Object.entries(JSON.parse(v.productSpec)).map((v, index) => (
                    <span key={index}>{v.join('：')}</span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        />
      ),
    },
    {
      title: '订单金额(元)',
      dataIndex: 'orderAmount',
      align: 'center',
      render: (text, record) => (
        <TableItem
          tr={<div className='goods-text'>￥{text?.toLocaleString()}</div>}
          td={
            <div>
              <span>创建时间:</span>
              <span>{dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
            </div>
          }
        />
      ),
    },
    {
      title: '供应商信息',
      align: 'center',
      render: () => <TableItem />,
    },
    {
      title: '订单状态',
      align: 'center',
      dataIndex: 'statusCode',
      render: (text) => (
        <TableItem
          tr={
            <div className='goods-text'>
              {orderStatusList.find((i) => i.value === text)?.label || text}
            </div>
          }
        />
      ),
    },
    {
      title: '备注',
      align: 'center',
      render: () => <TableItem tr={<Button type='link'>--</Button>} />,
    },
    {
      title: '操作',
      align: 'center',
      render: (_text: any, record) => (
        <TableItem
          tr={
            <>
              {getCurrentOperateBtn ? (
                <Button
                  type={'link'}
                  onClick={() => getCurrentOperateBtn(record.statusCode)?.btnClick(record)}
                >
                  {getCurrentOperateBtn(record.statusCode)?.btnStr}
                </Button>
              ) : (
                ''
              )}
              <Button type='link' onClick={() => toProcurementOrderDetail(record)}>
                详情
              </Button>
            </>
          }
        />
      ),
    },
  ];
  // 订单流程操作
  const [sureOrderShow, setSureOrderShow] = useState<boolean>(false);

  // 获取当前操作按钮
  const getCurrentOperateBtn = (status: number) => {
    return operateBtnList.find((v) => v.status === status);
  };
  // 获取订单状态
  const getOrderStatusList = () => {
    OrderManageAPI.getMallOrderStatusList().then(({ result }) => {
      if (result) {
        const list = result.map((item) => ({ value: item.code, label: item.status }));
        setOrderStatusList(list);
        setTranStatusList([{ label: '全部', value: undefined }, ...list]);
      }
    });
  };
  // 采购订单列表
  const getListPurchaseOrder = (query?: procurementOrderParamsType) => {
    OrderManageAPI.getListPurchaseOrder({
      pageSize: pagination.pageSize,
      pageNo: pagination.pageNo,
      ...query,
    }).then(({ result }) => {
      pagination.totalCount = result.totalCount;
      setPagination({ ...pagination });
      setTableData(result.list || []);
    });
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListPurchaseOrder(query);
  };
  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    setStatusCodeButtonIndex(i);
    const req = { ...query, statusCode: tranStatusList[i].value };
    setQuery(req);
    getListPurchaseOrder(req);
  };
  // 筛选
  const searchSuccess = (value: any) => {
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    const reqData = filterObjAttr(value, ['rangeTime']);
    setQuery({ ...reqData });
    getListPurchaseOrder(reqData);
  };
  // 采购订单详情
  const toProcurementOrderDetail = (record: procurementOrderListType[0]) => {
    navigate({
      pathname: '/orderManage/procurementOrder/detail',
      search: qs.stringify({ id: record.id }),
    });
  };

  // 确认订单
  const sureOrderOk = () => {
    setSureOrderShow(false);
  };
  const sureOrderCancel = () => {
    setSureOrderShow(false);
  };

  useEffect(() => {
    getOrderStatusList();
    getListPurchaseOrder();
  }, []);
  return (
    <div className='procurement-order-list'>
      <SearchBox
        search={[
          {
            label: '订单编号',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        sufFixBtn={
          <>
            {tranStatusList?.map((i, j) => {
              return (
                <Button
                  key={j}
                  type={j === statusCodeButtonIndex ? 'primary' : 'default'}
                  onClick={() => statusChangeEvent(j)}
                  style={{ marginTop: '5px' }}
                >
                  {i.label}
                </Button>
              );
            })}
          </>
        }
        searchData={searchSuccess}
      />
      <Table
        columns={tableColumns}
        dataSource={tableData}
        rowKey='id'
        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} 条数据`,
        }}
      />
      <SureOrder
        open={sureOrderShow}
        onCancel={sureOrderCancel}
        onOk={sureOrderOk}
        orderItem={currentOrderItem}
        type={0}
      />
    </div>
  );
};
export default ProcurementOrderList;
