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 { 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<PaginationProps & { totalCount: number }>({
    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 getServiceOrderFormList = (query?: demandOrderListParameterType) => {
    OrderManageAPI.getServiceOrderFormList({
      pageNo: pagination.pageNo,
      pageSize: pagination.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.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.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getServiceOrderFormList(query);
  };
  // 筛选成功事件
  const searchSuccessEvent = (value: any) => {
    setQuery(value);
    pagination.pageNo = 1;
    pagination.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)),
      );
    }
  };
  // 组件挂载
  useEffect(() => {
    getFlowDictionary().then();
    getServiceOrderFormList();
    // console.log('组件挂载 --->', );
  }, [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: 260,
    },
    {
      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} />
      <Table
        columns={tableColumns}
        bordered
        rowKey='id'
        dataSource={tableData}
        expandable={{
          defaultExpandAllRows: false,
          childrenColumnName: 'childrenRequire',
        }}
        scroll={{ x: 1000 }}
        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} 条数据`,
        }}
      />
    </div>
  );
};
export default DemandOrderList;
