import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, Image, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { OrderManageAPI } from '~/api';
import { listPageManagerVerOne } from '~/api/interface/orderManageType';
import { InterListType, InterReqType } from '~/api/interface';
import DistributionOrder from './components/distributionOrder';
import SureOrder from './components/sureOrder';
import ApprovalOrder from './components/approvalOrder';
import ShipmentsOrder from './components/shipmentsOrder';

// 表格数据类型
type TableType = InterListType<listPageManagerVerOne>;
// 请求数据的类型
type ReqType = InterReqType<listPageManagerVerOne>;
// 搜索表单的数据
let query: ReqType = {};

function ProductOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: number | undefined; label: string }[]
  >([]);
  // 订单状态
  const [orderStatusList, setOrderStatusList] = useState<{ value: number; label: string }[]>([]);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  // const [editData, setEditData] = useState<TableType[0]>(); // 用于编辑

  // 订单流程操作
  const [distributionOrderShow, setDistributionOrderShow] = useState<boolean>(false); //分配
  const [sureOrderShow, setSureOrderShow] = useState<boolean>(false); //确认订单
  const [approvalOrderShow, setApprovalOrderShow] = useState<boolean>(false); //审核
  const [shipmentsOrderShow, setShipmentsOrderShow] = useState<boolean>(false); //发货

  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await OrderManageAPI.listPageManagerVerOne({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === '200') {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: ReqType) => {
    pagination.current = 1;
    query = data;
    getTableList(data).then();
  };
  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    if (i === statusCodeButtonIndex) {
      setStatusCodeButtonIndex(0);
    } else {
      setStatusCodeButtonIndex(i);
    }
    if (i === 0) return;
    query = { ...query, statusCode: [Number(tranStatusList[i].value)] };
    getTableList().then();
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    navigate(`/orderManage/productOrder/detail?${qs.stringify({ id: record.id })}`);
  };
  // 获取订单状态
  const getOrderStatus = async () => {
    const res = await OrderManageAPI.orderListStatus({});
    if (res && res.code === '200') {
      const list = res.result.map((item) => ({ value: item.code, label: item.status }));
      setOrderStatusList(list);
      const arr = list
        .filter((i) => [999, 800, 720, 300, 200, 100, 50].includes(i.value))
        .reverse();
      setTranStatusList([{ value: undefined, label: '全部订单' }, ...arr]);
    }
  };
  // 分配订单
  const showDistributionOrderEvent = () => {
    setDistributionOrderShow(true);
  };
  const distributionOrderOk = () => {
    setDistributionOrderShow(false);
  };
  const distributionOrderCancel = () => {
    setDistributionOrderShow(false);
  };
  // 确认订单
  const showSureOrderEvent = () => {
    setSureOrderShow(true);
  };
  const sureOrderCancel = () => {
    setSureOrderShow(false);
  };
  const sureOrderOk = () => {
    setSureOrderShow(false);
  };
  // 凭证审批
  const showApprovalOrderEvent = () => {
    setApprovalOrderShow(true);
  };
  const approvalOrderOk = () => {
    setApprovalOrderShow(false);
  };
  const approvalOrderCancel = () => {
    setApprovalOrderShow(false);
  };
  // 发货
  const showShipmentsOrderEvent = () => {
    setShipmentsOrderShow(true);
  };
  const shipmentsOrderCancel = () => {
    setShipmentsOrderShow(false);
  };
  const shipmentsOrderOk = () => {
    setShipmentsOrderShow(false);
  };

  // componentDidMount
  useEffect(() => {
    query = {};
    getOrderStatus().then();
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '商品',
      dataIndex: 'userName',
      align: 'center',
      width: 280,
      render: (_text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Image src={record.orderMainImg} style={{ width: 48, height: 48 }} />
          <div style={{ marginLeft: 10, textAlign: 'left', lineHeight: '16px' }}>
            <div style={{ color: '#1677ff' }}>{record.orderName}</div>
            <div>{record.mallOrderProdListDTOList.map((i) => i.prodSkuSpecName).join(' + ')}</div>
            <div>订单编号：{record.orderNo}</div>
            <div>创建时间：{record.createTime}</div>
          </div>
        </div>
      ),
    },
    {
      title: '订单金额(元)',
      dataIndex: 'orderAmount',
      align: 'center',
      render: (text) => text.toLocaleString(),
    },
    {
      title: '买家',
      dataIndex: 'uid',
      align: 'center',
      render: (text, record) => (
        <>
          <div>{text}</div>
          <div>{record.userName}</div>
          <div>{record.entName}</div>
        </>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'statusCode',
      align: 'center',
      render: (text) => orderStatusList.find((i) => i.value === text)?.label || text,
    },
    {
      title: '实收款',
      dataIndex: 'realPayAmount',
      align: 'center',
      render: (text) => text?.toLocaleString() || 0,
    },
    {
      title: '相关运营',
      dataIndex: 'userName',
      align: 'center',
      render: (_text) => `--`,
    },
    {
      title: '推荐人',
      dataIndex: 'userName',
      align: 'center',
      render: (_text) => `--`,
    },
    {
      title: '订单交期',
      dataIndex: 'userName',
      align: 'center',
      render: (_text) => `--`,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      render: (_text, record) => (
        <>
          {/*<Button type={'link'} onClick={() => showDistributionOrderEvent()}>*/}
          {/*  分配运营*/}
          {/*</Button>*/}
          {/*<Button type={'link'} onClick={() => showSureOrderEvent()}>*/}
          {/*  确认订单*/}
          {/*</Button>*/}
          {/*<Button type={'link'} onClick={() => showApprovalOrderEvent()}>*/}
          {/*  凭证审批*/}
          {/*</Button>*/}
          <Button type={'link'} onClick={() => showShipmentsOrderEvent()}>
            发货
          </Button>
          <Button type={'link'} onClick={() => handleDetail(record)}>
            详情
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '订单编号',
            name: 'keyword',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '买家账号',
            name: 'keyword2',
            type: 'input',
            placeholder: '请输入用户账号',
          },
          {
            label: '时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        searchData={onFinish}
        sufFixBtn={
          <>
            {tranStatusList?.map((i, j) => {
              return (
                <Button
                  key={j}
                  type={j === statusCodeButtonIndex ? 'primary' : 'default'}
                  onClick={() => statusChangeEvent(j)}
                  style={{ marginTop: '5px' }}
                >
                  {i.label}
                </Button>
              );
            })}
          </>
        }
      />
      <Table
        size='small'
        dataSource={tableData}
        columns={columns}
        rowKey='id'
        scroll={{ x: 1200 }}
        pagination={{
          total: pagination.total,
          pageSize: pagination.pageSize,
          current: pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
      />
      {/*分配订单*/}
      <DistributionOrder
        open={distributionOrderShow}
        onOk={distributionOrderOk}
        onCancel={distributionOrderCancel}
      />
      {/*确认订单*/}
      <SureOrder open={sureOrderShow} onCancel={sureOrderCancel} onOk={sureOrderOk} />
      {/*凭证审批*/}
      <ApprovalOrder
        open={approvalOrderShow}
        onCancel={approvalOrderCancel}
        onOk={approvalOrderOk}
      />
      {/*发货*/}
      <ShipmentsOrder
        open={shipmentsOrderShow}
        onCancel={shipmentsOrderCancel}
        onOk={shipmentsOrderOk}
      />
    </>
  );
}

export default ProductOrderView;
