import InvoiceRecordDetailModal from '@/pages/Invoice/InvoiceRecord/components/InvoiceRecordDetailModal';
import InvoiceModal from '@/pages/Invoice/waitProcessRecord/components/InvoiceModal';
import InvoicingModal from '@/pages/Invoice/waitProcessRecord/components/InvoicingModal';
import ManualInvoicingModal from '@/pages/Invoice/waitProcessRecord/components/ManualInvoicingModal';
import { PAYEE_OPTIONS } from '@/pages/Order/constant';
import {
  postServiceConstBeforeInvoicingInvoiceRecordStatus,
  postServiceConstInvoiceType,
  postServiceConstInvoicingType,
  postServiceInvoiceQueryInvoiceRecordList,
  postServiceOrderQuerySalesCode,
} from '@/services';
import { enumToProTableEnumValue, enumToSelect } from '@/utils';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Divider, Space, Table, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

const InvoiceRecord = () => {
  const waitDealrecordActionRef = useRef<ActionType>();
  const [invoiceTypeValueEnum, setInvoiceTypeValueEnum] = useState({});
  const [invoicingTypeValueEnum, setInvoicingTypeValueEnum] = useState({});
  const [salesCodeValueEnum, setSalesCodeValueEnum] = useState({});
  const [invoiceRecordDetailVisible, setInvoiceRecordDetailVisible] =
    useState(false);
  const [invoiceRecord, setInvoiceRecord] = useState({});

  useEffect(() => {
    async function extracted() {
      let invoiceTypeRet = await postServiceConstInvoiceType();
      setInvoiceTypeValueEnum(invoiceTypeRet.data);
    }

    extracted().catch(console.error);
  }, []);

  useEffect(() => {
    async function extracted() {
      let invoicingTypeRet = await postServiceConstInvoicingType();
      setInvoicingTypeValueEnum(invoicingTypeRet.data);
    }

    extracted().catch(console.error);
  }, []);

  useEffect(() => {
    async function extracted() {
      const res = await postServiceOrderQuerySalesCode();
      let map = {};
      res.data?.forEach((item) => {
        map[item.userName] = { text: item.userName, status: item.userName };
      });
      setSalesCodeValueEnum(map);
    }

    extracted().catch(console.error);
  }, []);

  const reloadRecordTable = () => {
    waitDealrecordActionRef.current?.reload();
  };

  const waitDealRecordColumns = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      hideInSearch: true,
      ellipsis: true,
      width: 48,
    },
    {
      title: '开票编号',
      valueType: 'text',
      dataIndex: 'id',
      copyable: true,
      hideInSearch: true,
      ellipsis: true,
      width: 100,
    },
    {
      title: '发票状态',
      valueType: 'Text',
      dataIndex: 'statusText',
      ellipsis: true,
      width: 100,
      hideInSearch: true,
    },
    {
      title: '重开发票',
      key: 'reissueInvoiceNumbers',
      ellipsis: true,
      width: 160,
      hideInSearch: true,
      render: (_, record) => {
        //将record.reissueInvoiceNumbers用,拼接
        const numbersText = record.reissueInvoiceNumbers?.join(',');
        return record.reissueInvoiceNumbers?.map((item) => {
          return (
            <Tooltip title={numbersText} key={item}>
              <Space>
                {item}
                <Divider type={'vertical'} />
              </Space>
            </Tooltip>
          );
        });
      },
    },
    {
      title: '申请开票时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      width: 160,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '订单号',
      valueType: 'text',
      dataIndex: 'mainOrderId',
      hideInTable: true,
    },
    {
      title: '申请人',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
      width: 100,
      dataIndex: 'createByName',
    },
    {
      title: '购方名称',
      valueType: 'text',
      dataIndex: 'partyAName',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '联系人',
      valueType: 'text',
      dataIndex: 'contacts',
      width: 100,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '购方税号',
      valueType: 'text',
      hideInSearch: true,
      dataIndex: 'partyATaxid',
      ellipsis: true,
    },
    {
      title: '收款单位',
      valueType: 'text',
      hideInSearch: true,
      dataIndex: 'partyBName',
      ellipsis: true,
    },
    {
      title: '开票金额',
      valueType: 'money',
      dataIndex: 'price',
      width: 100,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '开具类型',
      valueType: 'Text',
      dataIndex: 'invoicingTypeText',
      width: 100,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '发票类型',
      valueType: 'Text',
      dataIndex: 'typeText',
      width: 100,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '是否加急',
      valueType: 'Text',
      dataIndex: 'isUrgentText',
      width: 50,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '申请备注',
      valueType: 'text',
      dataIndex: 'applyInvoicingNotes',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '购方名称',
      valueType: 'Text',
      dataIndex: 'partyANameLike',
      hideInTable: true,
    },
    {
      title: '联系人',
      valueType: 'text',
      dataIndex: 'contactsLike',
      hideInTable: true,
    },
    {
      title: '收款单位',
      valueType: 'select',
      dataIndex: 'partyB',
      filters: true,
      onFilter: true,
      hideInTable: true,
      valueEnum: enumToProTableEnumValue(PAYEE_OPTIONS),
    },
    {
      title: '主订单号',
      valueType: 'Text',
      dataIndex: 'mainOrderId',
      hideInTable: true,
    },
    {
      title: '子订单号',
      valueType: 'Text',
      dataIndex: 'subOrderId',
      hideInTable: true,
    },
    {
      title: '销售代表',
      valueType: 'select',
      dataIndex: 'salesCode',
      filters: true,
      onFilter: true,
      hideInTable: true,
      valueEnum: salesCodeValueEnum,
    },
    {
      title: '发票类型',
      valueType: 'select',
      dataIndex: 'type',
      filters: true,
      onFilter: true,
      hideInTable: true,
      valueEnum: enumToProTableEnumValue(invoiceTypeValueEnum),
    },
    {
      title: '开具类型',
      valueType: 'select',
      dataIndex: 'invoicingType',
      filters: true,
      onFilter: true,
      hideInTable: true,
      valueEnum: enumToProTableEnumValue(invoicingTypeValueEnum),
    },
    {
      title: '开票状态',
      valueType: 'select',
      key: 'status',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      hideInTable: true,
      request: async () => {
        const res = await postServiceConstBeforeInvoicingInvoiceRecordStatus();
        return enumToSelect(res.data);
      },
    },
    {
      title: '是否加急',
      valueType: 'select',
      dataIndex: 'isUrgent',
      filters: true,
      onFilter: true,
      hideInTable: true,
      valueEnum: {
        true: {
          text: '是',
          status: true,
        },
        false: {
          text: '否',
          status: false,
        },
      },
    },
    {
      title: '申请开票时间',
      dataIndex: 'createTime',
      valueType: 'dateTimeRange',
      width: 200,
      hideInTable: true,
      search: {
        transform: (value) => {
          if (value) {
            return {
              createTimeGe: value[0],
              createTimeLe: value[1],
            };
          }
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 200,
      render: (text, record) => {
        return [
          /*<InvoiceRecordDetailModal
                                          key="detail"
                                          id={record.id}
                                          subOrderIds={record.subOrderIds}
                                          onClose={()=>{
                                            waitDealrecordActionRef.current?.reload();
                                          }
                                          }
                                        />*/
          <>
            {record.paths.includes('DETAIL') && (
              <a
                key="detail"
                onClick={() => {
                  setInvoiceRecordDetailVisible(true);
                  setInvoiceRecord(record);
                }}
              >
                详情
              </a>
            )}
          </>,
          <>
            {record.paths.includes('PREVIEW') && (
              <InvoiceModal key="invoiceModal" recordId={record.id} />
            )}
          </>,
          <>
            {record.paths.includes('INVOICING') && (
              <ManualInvoicingModal
                key={'ManualInvoicingModal'}
                record={record}
              ></ManualInvoicingModal>
            )}
          </>,
        ];
      },
    },
  ];
  return (
    <div className="invoice-index">
      <ProTable
        columns={waitDealRecordColumns}
        actionRef={waitDealrecordActionRef}
        cardBordered
        pagination={{
          showSizeChanger: true, // 显示可以选择每页显示条数的下拉菜单
          pageSizeOptions: ['10', '20', '50', '100'], // 设置可以选择的每页显示条数选项
        }}
        rowSelection={{
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          alwaysShowAlert: true,
        }}
        tableAlertOptionRender={({ selectedRowKeys, selectedRows }) => {
          console.log(selectedRows);
          console.log(selectedRowKeys);
          return (
            <Space size={16}>
              <InvoicingModal
                reloadRecordTable={reloadRecordTable}
                key="button"
                selectedRowKeys={selectedRowKeys}
              />
            </Space>
          );
        }}
        request={async (params) => {
          let res = await postServiceInvoiceQueryInvoiceRecordList({
            data: {
              ...params,
              statusIn: [
                'WAITING_FOR_INVOICING',
                'AUDITING',
                'AUDITING_NOT_PASSED',
              ],
              needBuildDetails: true,
              needBuildSubOrders: true,
            },
          });
          return {
            data: res?.data?.data,
            total: res?.data?.total || 0,
          };
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{}}
        dateFormatter="string"
        headerTitle="待开票列表"
        scroll={{ x: 2000, y: 500 }}
      />
      {invoiceRecordDetailVisible ? (
        <InvoiceRecordDetailModal
          key="detail"
          id={invoiceRecord.id}
          setVisible={setInvoiceRecordDetailVisible}
          reloadTable={() => {
            waitDealrecordActionRef?.current?.reload();
          }}
        />
      ) : (
        ''
      )}
    </div>
  );
};

export default InvoiceRecord;