import SearchBox from '~/components/search-box';
import { searchColumns as searchColumnsType } from '~/components/search-box';
import { Button, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/es/table/InternalTable';
import { createRef, useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { OrderManageAPI } from '~/api';
import { InterDataType, InterListType, PaginationProps } from '~/api/interface';
import { serviceOrderFormListType } from '~/api/interface/orderManageType';
import { orderLevelList } from '~/utils/dictionary';

// 需求订单列表返回类型
type demandOrderListType = InterDataType<serviceOrderFormListType>['list'];
// 需求订单列表请求类型
type demandOrderListParameterType = InterListType<serviceOrderFormListType>;

const DemandOrderList = () => {
  const location = useLocation();
  // 路由钩子
  const navigate = useNavigate();
  // 表格数据
  const [tableData, setTableData] = useState<demandOrderListType>([]);
  // 翻页数据
  const [pagination, setPagination] = useState<Array<PaginationProps & { totalCount: number }>>([
    {
      pageNo: 1,
      pageSize: 10,
      totalCount: 0,
    },
    {
      pageNo: 1,
      pageSize: 10,
      totalCount: 0,
    },
  ]);
  // 搜索数据
  const [query, setQuery] = useState<demandOrderListParameterType>();
  // 订单状态列表
  const [orderStatusList, setOrderStatusList] = useState<{ label: string; value: string }[]>([]);
  // 刷新子组件
  // const [refresh, setRefresh] = useState<boolean>(true);
  // 是否是派单
  const isPilotOrder = Number(location?.pathname?.split('/')?.at(-1));
  // 获取需求订单列表
  const getServiceOrderFormList = (query?: demandOrderListParameterType) => {
    OrderManageAPI.getServiceOrderFormList({
      pageNo: pagination[isPilotOrder].pageNo,
      pageSize: pagination[isPilotOrder].pageSize,
      isPilotOrder: Number(location?.pathname?.split('/')?.at(-1)),
      ...query,
    }).then(({ result }) => {
      const list = (result.list || [])?.map((i) => ({
        ...i,
        childrenRequire: i.childrenRequire?.length ? i.childrenRequire : undefined,
      }));
      setTableData(list);
      pagination[isPilotOrder].totalCount = result.totalCount;
      setPagination({ ...pagination });
    });
  };
  // 订单详情
  const toOrderDetail = (record: demandOrderListType[0]) => {
    navigate({ pathname: '/serviceManage/demandOrderDetail', search: `id=${record.id}` });
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination[isPilotOrder].pageNo = pageNo;
    pagination[isPilotOrder].pageSize = pageSize;
    getServiceOrderFormList(query);
  };
  // 筛选成功事件
  const searchSuccessEvent = (value: any) => {
    setQuery(value);
    pagination[isPilotOrder].pageNo = 1;
    pagination[isPilotOrder].pageSize = 10;
    getServiceOrderFormList(value);
  };
  // 获取订单进度条字典
  const getFlowDictionary = async () => {
    const res = await OrderManageAPI.getFlowDictionary();
    if (res && res.code === '200') {
      setOrderStatusList(
        res.result
          ?.map((i) => ({ value: i.orderStatus, label: i.waiting }))
          ?.sort((a, b) => Number(a.value) - Number(b.value)),
      );
    }
  };
  // 创建子组件实例
  const SearchBoxRef = createRef<any>();
  // 组件挂载
  useEffect(() => {
    // 还原列表
    setTableData([]);
    setQuery(undefined);
    SearchBoxRef.current.handleRestForm();
    // 还原分页
    // setPagination({ pageNo: 1, pageSize: 10, totalCount: 0 });
    // 获取数据
    getFlowDictionary().then();
    getServiceOrderFormList();
  }, [location]);
  const searchColumns: searchColumnsType[] = [
    {
      label: '订单编号',
      name: 'publisherNumber',
      type: 'input',
      placeholder: '请输入订单编号',
    },
    {
      label: '订单状态',
      name: 'orderStatus',
      type: 'Select',
      placeholder: '请选择订单状态',
      options: orderStatusList,
    },
    {
      label: '发单手机号',
      name: 'publishPhone',
      type: 'input',
      placeholder: '请输入发单手机号',
    },
    {
      label: '接单手机号',
      name: 'preemptPhone',
      type: 'input',
      placeholder: '请输入接单手机号',
    },
    {
      label: '订单属性',
      name: 'orderAttribute',
      type: 'Select',
      placeholder: '请选择订单属性',
      options: [
        { label: '正常订单', value: 1 },
        { label: '争议订单', value: 2 },
      ],
    },
  ];
  const tableColumns: ColumnsType<demandOrderListType[0]> = [
    {
      title: '订单编号',
      align: 'center',
      dataIndex: 'publisherNumber',
      render: (text: string, record) => (
        <>
          <Tag
            color={
              record?.fatherRequireId === 0
                ? record?.childrenRequire?.length
                  ? 'green'
                  : 'volcano'
                : 'blue'
            }
          >
            {record?.fatherRequireId === 0 ? '主订单' : '子订单'}
          </Tag>
          <span>{text}</span>
        </>
      ),
      width: 280,
    },
    {
      title: '订单状态',
      align: 'center',
      dataIndex: 'waiting',
      render: (text, record) => (!record?.childrenRequire?.length ? text : ''),
    },
    {
      title: '订单类型',
      align: 'center',
      dataIndex: 'serviceName',
    },
    {
      title: '订单级别',
      align: 'center',
      dataIndex: 'orderLevel',
      render: (text: string) => (
        <Tag>{orderLevelList.find((v) => v.code === text)?.label || ''}</Tag>
      ),
    },
    {
      title: '发单方信息',
      align: 'center',
      dataIndex: 'publishPhone',
      render: (text, record) =>
        record?.orderRelease?.phoneNum ? (
          <>
            <div>{record?.orderRelease?.phoneNum}</div>
            <div>{record?.orderRelease?.userName || record?.orderRelease?.nickName}</div>
          </>
        ) : (
          text
        ),
    },
    {
      title: '接单方信息',
      align: 'center',
      dataIndex: 'preemptPhone',
      render: (text, record) =>
        record?.orderReceive?.phoneNum ? (
          <>
            <div>{record?.orderReceive?.phoneNum}</div>
            <div>{record?.orderReceive?.userName || record?.orderReceive?.nickName}</div>
          </>
        ) : (
          text
        ),
    },
    {
      title: '订单属性',
      align: 'center',
      dataIndex: 'orderAttribute',
      render: (text: number) => (text === 1 ? '正常订单' : '争议订单'),
    },
    {
      title: '订单收益',
      align: 'center',
      dataIndex: 'orderEarnings',
      render: (text: number) => text.toFixed(2).toLocaleString(),
    },
    {
      title: '发单时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      render: (_text: any, record) =>
        !record?.childrenRequire?.length && (
          <Button type='link' onClick={() => toOrderDetail(record)}>
            查看订单
          </Button>
        ),
    },
  ];
  return (
    <div className='demand-order'>
      <SearchBox search={searchColumns} searchData={searchSuccessEvent} onRef={SearchBoxRef} />
      <Table
        columns={tableColumns}
        bordered
        rowKey='id'
        dataSource={tableData}
        expandable={{
          defaultExpandAllRows: false,
          childrenColumnName: 'childrenRequire',
        }}
        scroll={{ x: 1000 }}
        pagination={{
          total: pagination[isPilotOrder].totalCount,
          pageSize: pagination[isPilotOrder].pageSize,
          current: pagination[isPilotOrder].pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
    </div>
  );
};
export default DemandOrderList;
