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 { InterDataType, InterReqType, PaginationProps } from '~/api/interface';
import { serviceOrderStatusType, serviceOrderType } from '~/api/interface/orderManageType';
import { filterObjAttr } from '~/utils';

// 表格数据类型
type TableType = InterDataType<serviceOrderType>['list'];
//服务-订单请求参数类型
type serviceOrderTypeParameters = Omit<InterReqType<serviceOrderType>, 'pageSize' | 'pageNo'>;
//字典返回类型
type serviceStatusType = InterDataType<serviceOrderStatusType>;

// 订单状态搜索列表
const statusCodeButtonList = [
  { value: -1, label: '全部订单' },
  { value: 0, label: '待付款' },
  { value: 1, label: '待验收' },
  { value: 2, label: '已完成' },
  { value: 3, label: '已取消' },
];

function ServiceOrderView() {
  // 路由钩子
  const navigate = useNavigate();
  // 当前选择的是第几个按钮
  const [statusCodeButtonIndex, setStatusCodeButtonIndex] = useState<number>(0);
  // 表格分页配置
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    totalCount: 0,
    pageSize: 10,
    pageNo: 1,
  });
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  //服务订单-字典
  const [serviceStatusList, setServiceStatusList] = useState<serviceStatusType>([]);
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: '商品',
      dataIndex: 'userName',
      align: 'center',
      width: 250,
      render: (_text, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {/*<Image src={record.images[0]} style={{ width: 48, height: 48 }} />*/}
          <div style={{ marginLeft: 10, textAlign: 'left', lineHeight: '16px' }}>
            <div style={{ color: '#1677ff' }}>{record.orderName}</div>
            <div>订单编号：{record.orderNo}</div>
            <div>创建时间：{record.createdTime}</div>
          </div>
        </div>
      ),
    },
    {
      title: '单价(元)',
      dataIndex: 'orderAmt',
      align: 'center',
      render: (text) => `￥${text.toLocaleString()}`,
    },
    {
      title: '数量',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '买家',
      align: 'center',
      width: '130px',
      render: (_text, record) => (
        <>
          <div>{record.uid}</div>
          <div>
            {record.userName}({record.phoneNum})
          </div>
        </>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      align: 'center',
      render: (text) => serviceStatusList.find((v) => v.orderStatus === text)?.managePort || '',
    },
    {
      title: '实收款',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '相关运营',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '推荐人',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '订单交期',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    {
      title: '备注',
      align: 'center',
      render: (_text, _record) => `--`,
    },
    // {
    //   title: '操作',
    //   align: 'center',
    //   fixed: 'right',
    //   render: (_text, record) => (
    //     <>
    //       <Button type={'link'} onClick={() => handleDetail(record)}>
    //         详情
    //       </Button>
    //     </>
    //   ),
    // },
  ];
  //筛选数据
  const [query, setQuery] = useState<serviceOrderTypeParameters>();

  // 订单状态筛选
  const statusChangeEvent = (i: number) => {
    setStatusCodeButtonIndex(i);
    pagination.pageNo = 1;
    setQuery({
      ...query,
      orderStatus: statusCodeButtonList[i].value === -1 ? undefined : statusCodeButtonList[i].value,
    });
    getServiceOrderList({
      ...query,
      orderStatus: statusCodeButtonList[i].value === -1 ? undefined : statusCodeButtonList[i].value,
    });
  };
  // 跳转订单详情
  const handleDetail = (record: TableType[0]) => {
    navigate(`/orderManage/serviceOrder/detail?${qs.stringify({ id: record.id })}`);
  };
  //服务订单列表
  const getServiceOrderList = (query?: serviceOrderTypeParameters) => {
    OrderManageAPI.getServiceOrderList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    }).then(({ result }) => {
      setTableData(result.list || []);
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
    });
  };
  //服务-订单字典
  const getServiceStatusList = () => {
    OrderManageAPI.getServiceStatusList().then(({ result }) => {
      setServiceStatusList(result);
    });
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getServiceOrderList(query);
  };
  //筛选
  const searchSuccess = (value: any) => {
    setQuery(filterObjAttr(value, ['time']));
    pagination.pageNo = 1;
    getServiceOrderList(filterObjAttr(value, ['time']));
  };
  useEffect(() => {
    getServiceStatusList();
    getServiceOrderList();
  }, []);
  return (
    <>
      <SearchBox
        search={[
          {
            label: '订单编号',
            name: 'orderNameOrNo',
            type: 'input',
            placeholder: '请输入订单编号',
          },
          // {
          //   label: '买家账号',
          //   name: 'keyword2',
          //   type: 'input',
          //   placeholder: '请输入用户账号',
          // },
          // {
          //   label: '相关销售',
          //   name: 'saleId',
          //   type: 'Select',
          //   placeholder: '请选择相关销售',
          //   options: [],
          // },
          {
            label: '时间',
            name: 'time',
            type: 'rangePicker',
            placeholder: '请选择创建时间',
          },
        ]}
        searchData={searchSuccess}
        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.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} 条数据`,
        }}
        // rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
      />
    </>
  );
}

export default ServiceOrderView;
