import {
  deleteOrderErpOrderStagesDelect,
  getOrderErpOrderStagesListAll,
  postOrderErpOrderStagesSearch,
} from '@/services';
import { downloadFile } from '@/services/order';
import { VerticalAlignTopOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Space, Table, Tag, message } from 'antd';
import { Key, useRef, useState } from 'react';
import TableCheckModal from '../checkModal/TableCheckModal';
import CheckModal from '../checkModal/checkModal';
import Comfire from '../comfire/comfire';
import AddModel from '../detail/detail';
import EditorModel from '../edit/edit';
import ReadModel from '../read/read';
import UploadModel from '../upload/uploadModel';
import './title.less';

export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

type OrderStagesItem = {
  //文件编号
  id?: number;
  //合同编号
  contract?: string;
  //供应商名称
  vendor?: string;
  //签合同日期
  dateRange?: Date;
  //终端名称
  terminal?: string;
  //设备编号
  dId?: number;
  //设备名称
  deviceName?: string;
  //设备型号
  deviceModel?: string;
  //数量
  count?: number;
  //单价
  unitPrice?: number;
  //总价
  price?: number;
  //合同总金额
  totalPrice?: number;
  //付款方式
  payWay?: string;
  //附件
  annex?: string;
  //备注
  remark?: string;
  //可选操作
  opt?: string[];
  //账单状态
  status?: string;
  //审核备注
  statusMark?: string;
  //子类
  // children?: OrderStagesItem[];
  orderStagesDeviceVoList: orderStagesDevice[];
};

type OrderStagesWithListItem = {
  //文件编号
  id: number;
  //合同编号
  contract: string;
  //供应商名称
  vendor: string;
  //签合同日期
  dateRange: Date;
  //终端名称
  terminal: string;
  orderStagesDeviceVoList: orderStagesDevice[];
  //合同总金额
  totalPrice: number;
  //付款方式
  payWay: string;
  //附件
  annex: string;
  //备注
  remark: string;
  //可选操作
  paths: string[];
  //账单状态
  status?: string;
  //审核备注
  statusMark?: string;
};

type orderStagesDevice = {
  //设备id
  dId: number;
  //设备名称
  deviceName: string;
  //设备型号
  deviceModel: string;
  //数量
  count: number;
  //单价
  unitPrice: number;
  //总价
  price: number;
};

// const loopOrderStagesFilter = (
//     data: readonly OrderStagesItem[],
//     dId: React.Key | undefined,
// ): OrderStagesItem[] => {
//     return data
//         .map((item) => {
//             if (item.dId !== dId) {
//                 if (item.children) {
//                     if (item.children.length !== 0) {
//                         const newChildren = loopOrderStagesFilter(item.children, dId);
//                         return {
//                             ...item,
//                             children: newChildren.length > 0 ? newChildren : undefined,
//                         };
//                     }
//                 }
//                 return item;
//             }
//             return null;
//         })
//         .filter(Boolean) as OrderStagesItem[];
// };

export default () => {
  interface ActionType {
    reload: (resetPageIndex?: boolean) => void;
    reloadAndRest: () => void;
    reset: () => void;
    clearSelected?: () => void;
    startEditable: (rowKey: Key) => boolean;
    cancelEditable: (rowKey: Key) => boolean;
  }
  const [specialPath, setSpecialPath] = useState<string[]>([]);

  const ref = useRef<ActionType>({
    reload: () => {
      // implementation for reload
    },
    reloadAndRest: () => {
      // implementation for reloadAndRest
    },
    reset: () => {
      // implementation for reset
    },
    startEditable: () => {
      // implementation for startEditable
    },
    cancelEditable: () => {
      // implementation for cancelEditable
    },
  });

  function reload() {
    ref.current.reload();
  }

  async function toDelete(value) {
    const res = await deleteOrderErpOrderStagesDelect({
      data: {
        ids: value,
        deviceIds: null,
      },
    });
    if (res) {
      message.success('删除成功');
      ref.current.reload();
    } else {
      message.error('删除失败');
    }
  }

  const exportLoadingDestory = () => {
    message.success('导出成功');
  };

  async function toExport() {
    // await getOrderErpOrderStagesExport()
    downloadFile(
      '/api/order/erp/orderStages/export',
      '分期订单.xlsx',
      'get',
      {},
      exportLoadingDestory,
    );
  }

  const columns: ProColumns<OrderStagesItem>[] = [
    {
      title: '文件编号',
      dataIndex: 'id',
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
      // align: 'center',
      render: (_, record) => {
        if (record?.id) {
          const text = record?.id?.toString();
          const paddedText = '0'.repeat(4 - text.length) + text;
          return (
            <>
              {paddedText}
              {/* {record?.orderStagesDeviceVoList?.length > 1 && (
                <>
                  <Badge
                    count={record?.orderStagesDeviceVoList?.length}
                    style={{
                      marginBlockStart: -2,
                      marginInlineStart: 4,
                      color: '#1890FF',
                      backgroundColor: '#E6F7FF',
                    }}
                  />
                </>
              )} */}
            </>
          );
        }
      },
    },
    {
      title: '签合同日期',
      dataIndex: 'dateRange',
      valueType: 'date',
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
    },
    {
      title: '合同编号',
      dataIndex: 'contract',
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '供应商名称',
      dataIndex: 'vendor',
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
    },
    {
      title: '终端名称',
      dataIndex: 'terminal',
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        CHECK: { text: '待审核', status: 'CHECK' },
        PASS: { text: '审核通过', status: 'PASS' },
        NOT_PASS: { text: '审核未通过', status: 'NOT_PASS' },
      },
      render: (_, record) => {
        if (record.status !== null) {
          if (
            record.status === 'UPDATE_CHECK' ||
            record.status === 'SAVE_CHECK' ||
            record.status === 'IMPORT_CHECK'
          ) {
            return <Tag color="blue">待审核</Tag>;
          }
          if (record.status === 'PASS') {
            return <Tag color="green">审核通过</Tag>;
          }
          if (record.status === 'NOT_PASS') {
            return <Tag color="red">审核未通过</Tag>;
          }
        }
        // return <Tag color="orange">暂无状态</Tag>;
      },
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
      hideInSearch: true,
      width: 200,
      disable: true,
      onFilter: true,
      ellipsis: true,
      hideInTable: true,
    },
    {
      title: '数量',
      dataIndex: 'count',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
      hideInTable: true,
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
      hideInTable: true,
    },
    {
      title: '总价',
      dataIndex: 'price',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
      hideInTable: true,
    },
    {
      title: '合同总金额',
      dataIndex: 'totalPrice',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
    },
    {
      title: '付款方式',
      dataIndex: 'payWay',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
    },
    {
      title: '附件',
      dataIndex: 'annex',
      hideInSearch: true,
      width: 100,
      disable: true,
      onFilter: true,
      ellipsis: true,
      render: (_, record) => {
        if (record.id && record.annex !== null) {
          return <a href={record.annex}>附件文件</a>;
        }
      },
    },
    {
      disable: true,
      title: '备注',
      dataIndex: 'remark',
      filters: true,
      hideInSearch: true,
      onFilter: false,
      ellipsis: true,
      width: 100,
      hideInTable: false,
    },
    {
      disable: true,
      title: '审核备注',
      dataIndex: 'statusMark',
      filters: true,
      hideInSearch: true,
      onFilter: false,
      ellipsis: true,
      width: 100,
      hideInTable: false,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      width: 160,
      disable: true,
      onFilter: true,
      ellipsis: true,
      render: (_text, record) => {
        if (record?.id) {
          const hasOnlyReaderPermission = record?.opt?.includes('ONLYREAD');
          // const hasReaderPermission = record?.opt?.includes("READ");
          const hasDeletePermission = record?.opt?.includes('DELETE');
          const hasCheckPermission = record?.opt?.includes('CHECK');
          const hasEditPermission = record?.opt?.includes('EDIT');
          const hasRePutPermission = record?.opt?.includes('REPUT');
          return (
            <>
              {hasCheckPermission && (
                <>
                  <CheckModal id={[record.id]} toReload={reload}></CheckModal>
                  &nbsp;
                </>
              )}

              {hasOnlyReaderPermission && (
                <>
                  <ReadModel currentContract={record.contract}></ReadModel>
                  &nbsp;
                </>
              )}
              {hasEditPermission && (
                <>
                  <EditorModel
                    currentContract={record.contract}
                    toReload={reload}
                    showTarget={'编辑'}
                  ></EditorModel>
                  &nbsp;
                </>
              )}
              {hasRePutPermission && (
                <>
                  <EditorModel
                    currentContract={record.contract}
                    toReload={reload}
                    showTarget={'重新上传'}
                  ></EditorModel>
                  &nbsp;
                </>
              )}
              {hasDeletePermission && (
                <>
                  <Comfire currtDid={record.id} sureDelete={toDelete}></Comfire>
                </>
              )}
            </>
          );
        }
        return null;
      },
    },
  ];

  return (
    <>
      <EditableProTable<OrderStagesItem>
        className="title-index"
        columnEmptyText=""
        columns={columns}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          defaultSelectedRowKeys: [],
        }}
        cardBordered
        actionRef={ref}
        scroll={{ x: 1400 }}
        recordCreatorProps={false}
        request={async (params) => {
          if (params.id === '') {
            params.id = null;
          }
          if (params.contract === '') {
            params.contract = null;
          }
          if (params.vendor === '') {
            params.vendor = null;
          }
          if (params.terminal === '') {
            params.terminal = null;
          }
          if (params.deviceName === '') {
            params.deviceName = null;
          }
          if (params.dateRange === '') {
            params.dateRange = null;
          }
          if (params.status === '') {
            params.status = null;
          }
          if (
            params.id !== null ||
            params.contract !== null ||
            params.vendor !== null ||
            params.terminal !== null ||
            params.deviceName !== null ||
            params.dateRange !== null ||
            params.status !== null ||
            params.current !== null ||
            params.pageSize !== null
          ) {
            let PostOrderErpOrderStagesSearchOption = {
              id: params.id,
              contract: params.contract,
              vendor: params.vendor,
              terminal: params.terminal,
              deviceName: params.deviceName,
              dateRange: params.dateRange,
              statusText: params.status,
              current: params.current,
              pageSize: params.pageSize,
            };
            let res = await postOrderErpOrderStagesSearch({
              data: { ...PostOrderErpOrderStagesSearchOption },
            });
            await waitTime(2000);
            if (res) {
              const orderStagesWithList: OrderStagesWithListItem[] =
                res?.data.data;
              setSpecialPath(res.data.specialPath);
              let orderStagesList: OrderStagesItem[] = [];
              for (let ind = 0; ind < orderStagesWithList.length; ind++) {
                for (
                  let index = 0;
                  index <
                  orderStagesWithList[ind].orderStagesDeviceVoList.length;
                  index++
                ) {
                  let item: OrderStagesItem = {
                    id: undefined,
                    contract: undefined,
                    vendor: undefined,
                    dateRange: undefined,
                    terminal: undefined,
                    dId: undefined,
                    deviceName: undefined,
                    deviceModel: undefined,
                    count: undefined,
                    unitPrice: undefined,
                    price: undefined,
                    totalPrice: undefined,
                    payWay: undefined,
                    annex: undefined,
                    remark: undefined,
                    opt: undefined,
                    status: undefined,
                    statusMark: undefined,
                    orderStagesDeviceVoList: [],
                  };
                  if (index === 0) {
                    item.id = orderStagesWithList[ind].id;
                    item.contract = orderStagesWithList[ind].contract;
                    item.vendor = orderStagesWithList[ind].vendor;
                    item.dateRange = orderStagesWithList[ind].dateRange;
                    item.terminal = orderStagesWithList[ind].terminal;
                    item.dId =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].dId;
                    item.deviceName =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].deviceName;
                    item.deviceModel =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].deviceModel;
                    item.count =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].count;
                    item.unitPrice =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].unitPrice;
                    item.price =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].price;
                    item.totalPrice = orderStagesWithList[ind].totalPrice;
                    item.payWay = orderStagesWithList[ind].payWay;
                    item.annex = orderStagesWithList[ind].annex;
                    item.remark = orderStagesWithList[ind].remark;
                    item.status = orderStagesWithList[ind].status;
                    item.statusMark = orderStagesWithList[ind].statusMark;
                    item.orderStagesDeviceVoList =
                      orderStagesWithList[ind].orderStagesDeviceVoList;
                    // item.children = [];
                    if (orderStagesWithList[ind].paths) {
                      item.opt = [...orderStagesWithList[ind].paths];
                      if (orderStagesWithList[ind]?.paths?.includes('READ')) {
                        item.opt.push('ONLYREAD');
                      }
                    }
                    // item.children = [];
                    // if (
                    //     orderStagesWithList[ind].orderStagesDeviceVoList.length <=
                    //     1
                    // ) {
                    //     delete item.children;
                    // }
                    orderStagesList.push(item);
                  }
                  // else {
                  //     item.id = orderStagesWithList[ind].id;
                  //     item.contract = orderStagesWithList[ind].contract;
                  //     item.vendor = orderStagesWithList[ind].vendor;
                  //     item.dateRange = orderStagesWithList[ind].dateRange;
                  //     item.terminal = orderStagesWithList[ind].terminal;
                  //     item.dId =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].dId;
                  //     item.deviceName =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].deviceName;
                  //     item.deviceModel =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].deviceModel;
                  //     item.count =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].count;
                  //     item.unitPrice =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].unitPrice;
                  //     item.price =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].price;
                  //     item.totalPrice = orderStagesWithList[ind].totalPrice;
                  //     item.payWay = orderStagesWithList[ind].payWay;
                  //     item.annex = orderStagesWithList[ind].annex;
                  //     item.remark = orderStagesWithList[ind].remark;
                  //     if (orderStagesWithList[ind].paths) {
                  //         if (orderStagesList[ind]?.opt?.includes('READ')) {
                  //             item.opt = ['ONLYREAD'];
                  //         }
                  //     }
                  //     item.status = orderStagesWithList[ind].status;
                  //     item.statusMark = orderStagesWithList[ind].statusMark;
                  //     if (
                  //         orderStagesWithList[ind].orderStagesDeviceVoList.length >
                  //         1
                  //     ) {
                  //         orderStagesList[ind].children?.push(item);
                  //     }
                  // }
                }
              }
              return {
                data: orderStagesList || [],
                total: res?.data?.total || 0,
              };
            }
          } else {
            let res = await getOrderErpOrderStagesListAll();
            await waitTime(2000);
            if (res) {
              const orderStagesWithList: OrderStagesWithListItem[] = res?.data;
              let orderStagesList: OrderStagesItem[] = [];
              for (let ind = 0; ind < orderStagesWithList.length; ind++) {
                for (
                  let index = 0;
                  index <
                  orderStagesWithList[ind].orderStagesDeviceVoList.length;
                  index++
                ) {
                  let item: OrderStagesItem = {
                    id: undefined,
                    contract: undefined,
                    vendor: undefined,
                    dateRange: undefined,
                    terminal: undefined,
                    dId: undefined,
                    deviceName: undefined,
                    deviceModel: undefined,
                    count: undefined,
                    unitPrice: undefined,
                    price: undefined,
                    totalPrice: undefined,
                    payWay: undefined,
                    annex: undefined,
                    remark: undefined,
                    opt: undefined,
                    // children: undefined,
                    status: undefined,
                    statusMark: undefined,
                    orderStagesDeviceVoList: [],
                  };
                  if (index === 0) {
                    item.id = orderStagesWithList[ind].id;
                    item.contract = orderStagesWithList[ind].contract;
                    item.vendor = orderStagesWithList[ind].vendor;
                    item.dateRange = orderStagesWithList[ind].dateRange;
                    item.terminal = orderStagesWithList[ind].terminal;
                    item.dId =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].dId;
                    item.deviceName =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].deviceName;
                    item.deviceModel =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].deviceModel;
                    item.count =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].count;
                    item.unitPrice =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].unitPrice;
                    item.price =
                      orderStagesWithList[ind].orderStagesDeviceVoList[
                        index
                      ].price;
                    item.totalPrice = orderStagesWithList[ind].totalPrice;
                    item.payWay = orderStagesWithList[ind].payWay;
                    item.annex = orderStagesWithList[ind].annex;
                    item.remark = orderStagesWithList[ind].remark;
                    item.opt = orderStagesWithList[ind].paths;
                    item.status = orderStagesWithList[ind].status;
                    item.statusMark = orderStagesWithList[ind].statusMark;
                    item.orderStagesDeviceVoList =
                      orderStagesWithList[ind].orderStagesDeviceVoList;
                    if (orderStagesWithList[ind].paths) {
                      item.opt = [...orderStagesWithList[ind].paths];
                      if (orderStagesWithList[ind]?.paths?.includes('READ')) {
                        item.opt.push('ONLYREAD');
                      }
                    }
                    // if (
                    //     orderStagesWithList[ind].orderStagesDeviceVoList.length <=
                    //     1
                    // ) {
                    //     delete item.children;
                    // }
                    orderStagesList.push(item);
                  }
                  // else {
                  //     item.id = orderStagesWithList[ind].id;
                  //     item.contract = orderStagesWithList[ind].contract;
                  //     item.vendor = orderStagesWithList[ind].vendor;
                  //     item.dateRange = orderStagesWithList[ind].dateRange;
                  //     item.terminal = orderStagesWithList[ind].terminal;
                  //     item.dId =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].dId;
                  //     item.deviceName =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].deviceName;
                  //     item.deviceModel =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].deviceModel;
                  //     item.count =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].count;
                  //     item.unitPrice =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].unitPrice;
                  //     item.price =
                  //         orderStagesWithList[ind].orderStagesDeviceVoList[
                  //             index
                  //         ].price;
                  //     item.totalPrice = orderStagesWithList[ind].totalPrice;
                  //     item.payWay = orderStagesWithList[ind].payWay;
                  //     item.annex = orderStagesWithList[ind].annex;
                  //     item.remark = orderStagesWithList[ind].remark;
                  //     if (orderStagesWithList[ind].paths) {
                  //         if (orderStagesList[ind]?.opt?.includes('READ')) {
                  //             item.opt = ['ONLYREAD'];
                  //         }
                  //     }
                  //     item.status = orderStagesWithList[ind].status;
                  //     item.statusMark = orderStagesWithList[ind].statusMark;
                  //     if (
                  //         orderStagesWithList[ind].orderStagesDeviceVoList.length >
                  //         1
                  //     ) {
                  //         orderStagesList[ind].children?.push(item);
                  //     }
                  // }
                }
              }
              return {
                data: orderStagesList || [],
              };
            }
          }
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        rowKey="dId"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 800,
          },
        }}
        form={{
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle={[]}
        tableAlertOptionRender={({ selectedRows, onCleanSelected }) => {
          return (
            <Space size={16}>
              <TableCheckModal
                id={selectedRows
                  .filter(
                    (item) =>
                      item.status === 'SAVE_CHECK' ||
                      item.status === 'UPDATE_CHECK' ||
                      item.status === 'IMPORT_CHECK',
                  )
                  .map((item) => item.id)}
                toReload={reload}
                isShow={!specialPath?.includes('BatchModeration')}
              />
              <Button
                title="确认删除所选中的分期账单吗?"
                type="primary"
                disabled={!specialPath?.includes('BatchDelete')}
                onClick={() => {
                  let ids = selectedRows.map((item: any) => {
                    return item.id;
                  });
                  toDelete(ids);
                  onCleanSelected();
                }}
              >
                批量删除
              </Button>
              <Button
                type="primary"
                onClick={onCleanSelected}
                disabled={!specialPath?.includes('UnSelect')}
              >
                取消选中
              </Button>
            </Space>
          );
        }}
        toolBarRender={() => [
          <>
            <AddModel toReload={reload}></AddModel>
            <UploadModel toReload={reload}></UploadModel>
            <Button
              type="primary"
              onClick={() => {
                toExport();
              }}
            >
              <VerticalAlignTopOutlined />
              导出
            </Button>
          </>,
        ]}
      />
    </>
  );
};