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 { listPcWechatOrderType } from '~/api/interface/orderManageType';
import { OrderManageAPI } from '~/api';
import DetailDeliver from '~/pages/orderManage/equipmentOrder/comp/detailDeliver';

// 表格数据类型
type TableType = InterListType<listPcWechatOrderType>;
// 请求数据的类型
type ReqType = InterReqType<listPcWechatOrderType>;
// 搜索表单的数据
let query: ReqType = {};
// 订单状态
const orderStatus = [
  { value: '100', label: '等待买家付款', button: '关闭订单' },
  { value: '200', label: '等待卖家发货', button: '去发货' },
  { value: '300', label: '待买家收货' },
  { value: '400', label: '待归还' },
  { value: '500', label: '等待卖家确认', button: '确认收货' },
  { value: '600', label: '交易完成' },
  { value: '700', label: '退款中' },
  { value: '999', label: '订单关闭' },
  { value: '1000', label: '已取消' },
];

function EquipmentOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  // 发货弹窗是否显示
  const [deliverVisible, setDeliverVisible] = useState<boolean>(false);
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 订单状态搜索列表
  const [tranStatusList, setTranStatusList] = useState<
    { value: string | undefined; label: string }[]
  >([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 需要编辑的数据
  const [editData, setEditData] = useState<TableType[0]>(); // 用于编辑
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    const res = await OrderManageAPI.listPcWechatOrder({
      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) => {
    if (i === statusCodeButtonIndex) {
      setStatusCodeButtonIndex(0);
    } else {
      setStatusCodeButtonIndex(i);
    }
    query = { ...query, tranStatus: tranStatusList[i].value };
    getTableList().then();
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    const search = { id: record.id, orderNo: record.orderNo };
    navigate(`/orderManage/equipmentOrder/detail?${qs.stringify(search)}`);
  };
  // 获取订单状态
  const getOrderStatus = async () => {
    const res = await OrderManageAPI.listTranStatus({});
    if (res && res.code === '200') {
      const arr = res.result.map((item) => ({ value: item.status, label: item.waiting }));
      setTranStatusList([{ value: undefined, label: '全部订单' }, ...arr]);
      // console.log('getOrderStatus --->', arr);
    }
  };
  // 是否显示按钮
  const showStatusButton = (code: string) => {
    return orderStatus
      .filter((i) => i.button)
      .map((i) => i.value)
      .includes(code);
  };
  // 转化按钮文字
  const getStatusButton = (code: string) => {
    return orderStatus.filter((i) => i.button).find((i) => i.value === code)?.button || code;
  };
  // 点击事件
  const handleAction = (data: TableType[0]) => {
    const { tranStatus } = data;
    setEditData(data);
    if (tranStatus === '200') {
      setDeliverVisible(true);
    }
  };
  // 关闭弹窗
  const handleClosed = () => {
    setEditData(undefined);
    setDeliverVisible(false);
  };
  // componentDidMount
  useEffect(() => {
    query = {};
    getOrderStatus().then();
    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: 'waiting',
      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',
      width: '130px',
      render: (_text, record) => (
        <>
          {showStatusButton(record?.tranStatus) && (
            <Button
              type={'link'}
              disabled={['999', '1000'].includes(record?.tranStatus)}
              onClick={() => handleAction(record)}
            >
              {getStatusButton(record?.tranStatus)}
            </Button>
          )}
          <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={
          <>
            {tranStatusList?.map((i, j) => {
              return (
                <Button
                  key={j}
                  type={j === statusCodeButtonIndex ? 'primary' : 'default'}
                  onClick={() => statusChangeEvent(j)}
                  style={{ marginTop: '5px', marginBottom: '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 }}
      />
      {/*发货弹窗*/}
      <DetailDeliver open={deliverVisible} title={'发货'} data={editData} closed={handleClosed} />
    </>
  );
}

export default EquipmentOrderView;
