import { useEffect, useState } from 'react';
import SearchBox from '~/components/search-box';
import { Button, Image, Table, Tooltip } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { InterListType, InterReqType } from '~/api/interface';
import { listOfRentalOrdersType } from '~/api/interface/orderManageType';
import { OrderManageAPI } from '~/api';

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

// 订单状态搜索列表
const statusCodeButtonList = [
  { value: -1, label: '全部订单' },
  { value: 0, label: '沟通意向' },
  { value: 1, label: '签约付款' },
  { value: 2, label: '待发货' },
  { value: 3, label: '待收货' },
  { value: 4, label: '已完成' },
  { value: 5, label: '已关闭' },
];

function EquipmentOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await OrderManageAPI.listOfRentalOrders({
      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);
      console.log('加载列表 --->', 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) => {
    console.log('订单状态筛选 --->', i);
    setStatusCodeButtonIndex(i);
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    console.log('跳转订单详情 --->', record.id);
    navigate(`/orderManage/equipmentOrder/detail?${qs.stringify({ id: record.id })}`);
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    getTableList().then();
  }, []);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '商品',
      dataIndex: 'wareTitle',
      align: 'center',
      width: 250,
      render: (_text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Image src={record.wareImg} style={{ width: 48, height: 48 }} />
          <div style={{ marginLeft: 10, textAlign: 'left', lineHeight: '16px' }}>
            <div style={{ color: '#1677ff' }}>{record.wareTitle}</div>
            <div>{record.wareNo}</div>
            <div>订单编号：{record.orderNo}</div>
            <div>创建时间：{record.createTime}</div>
          </div>
        </div>
      ),
    },
    {
      title: '单价(元)',
      dataIndex: 'unitPrice',
      align: 'center',
      render: (text) => `￥${text.toLocaleString()}`,
    },
    {
      title: '数量',
      dataIndex: 'wareNum',
      align: 'center',
    },
    {
      title: '买家',
      dataIndex: 'userName',
      align: 'center',
      width: '130px',
      render: (_text, record) => (
        <>
          <div>{record.uid}</div>
          <div>
            {record.buyerName || record.nickName}({record.buyerPhone})
          </div>
        </>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'leaseOrderStatus',
      align: 'center',
    },
    {
      title: '实收款',
      dataIndex: 'shouldPay',
      align: 'center',
      render: (text) => `￥${text.toLocaleString()}`,
    },
    {
      title: '相关运营',
      dataIndex: 'userName',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '推荐人',
      dataIndex: 'userName',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '订单交期',
      dataIndex: 'userName',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      align: 'center',
      ellipsis: true,
      width: '100px',
      render: (text) => (
        <Tooltip placement='top' title={text}>
          <div className='remark-wrap'>{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      fixed: 'right',
      render: (_text, record) => (
        <>
          <Button type={'link'} onClick={() => handleDetail(record)}>
            详情
          </Button>
        </>
      ),
    },
  ];
  return (
    <>
      <SearchBox
        search={[
          {
            label: '订单编号',
            name: 'orderNo',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          {
            label: '买家账号',
            name: 'buyerAccount',
            type: 'input',
            placeholder: '请输入用户账号',
          },
          {
            label: '相关销售',
            name: 'saleId',
            type: 'Select',
            placeholder: '请选择相关销售',
            options: [],
          },
          {
            label: '时间',
            name: 'rangeTime',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        searchData={onFinish}
        sufFixBtn={
          <>
            {statusCodeButtonList?.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 }}
      />
    </>
  );
}

export default EquipmentOrderView;
