import ButtonConfirm from '@/components/ButtomConfirm';
import EllipsisDiv from '@/components/Div/EllipsisDiv';
import { RESPONSE_CODE } from '@/constants/enum';
import {
  BANK_STATEMENT_COLUMNS,
  INVOICE_COLUMNS,
  INVOICE_STATUS,
} from '@/pages/Invoice/constant';
import {
  postServiceBankStatementDeleteBankStatement,
  postServiceBankStatementEditBankStatement,
  postServiceBankStatementQueryBankStatement,
  postServiceInvoiceDeleteInvoice,
  postServiceInvoiceQueryInvoice,
} from '@/services';
import { enumValueToLabel, formatDateTime } from '@/utils';
import { formatDate } from '@/utils/time';
import { PlusOutlined } from '@ant-design/icons';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { Button, Tabs, message } from 'antd';
import { useRef, useState } from 'react';
import { INVOCING_STATUS, PAYEE_OPTIONS } from '../Order/constant';
import BankImportModal from './components/BankImportModal';
import InvoiceVerificationModal from './components/InvoiceVerificationModal';
import './index.less';
const InvoicePage = () => {
  const invoiceActionRef = useRef<ActionType>();
  const bankActionRef = useRef<ActionType>();
  const [bankImportModalVisible, setBankImportModalVisible] = useState(false);
  const [invoiceVerificationVisible, setInvoiceVerificationVisible] =
    useState(false);
  const [invoiceId, setInvoiceId] = useState(undefined);

  const reloadInvoiceTable = () => {
    invoiceActionRef.current?.reload();
  };

  const reloadBankStatementTable = () => {
    bankActionRef.current?.reload();
  };

  const getTableCellText = (target: any) => {
    if (!target) {
      return '';
    }

    if (target.props) {
      return target.props.text;
    }

    return target;
  };

  /**
   * 加载发票列表表格的各个列格式
   */
  const invoicecColumnsInit = () => {
    let columns = INVOICE_COLUMNS.map((item) => {
      let newItem = { ...item };
      let dataIndex = item.dataIndex;
      let dataType = item.valueType;

      newItem.render = (text, record) => {
        let textValue = record[dataIndex];

        if (dataType === 'dateRange' || dataType === 'date') {
          textValue = formatDate(textValue);
        }

        if (dataType === 'dateTime') {
          textValue = formatDateTime(textValue);
        }

        if (dataType === 'money') {
          textValue = '¥' + textValue;
        }

        switch (dataIndex) {
          case 'invoiceStatus':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  INVOCING_STATUS,
                )}
              />
            );

          case 'status':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  INVOICE_STATUS,
                )}
              />
            );

          case 'payee':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  PAYEE_OPTIONS,
                )}
              />
            );

          default:
            return <EllipsisDiv text={getTableCellText(textValue)} />;
        }
      };

      return newItem;
    });

    columns.push({
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      render: (text, record) => {
        let btns = [];
        if (record.path?.includes('writeOff')) {
          btns.push(
            <a
              key="editable"
              onClick={() => {
                setInvoiceVerificationVisible(true);
                setInvoiceId(record.invoiceId);
              }}
            >
              核销
            </a>,
          );
        }

        if (record.path?.includes('queryInvoiceDetails')) {
          btns.push(
            <Button
              className="p-0"
              key="view"
              type="link"
              onClick={() => {
                setInvoiceVerificationVisible(true);
                setInvoiceId(record.invoiceId);
              }}
            >
              查看
            </Button>,
          );
        }

        if (record.path?.includes('deleteInvoice')) {
          btns.push(
            <ButtonConfirm
              key="delete"
              className="p-0"
              title={
                '确认删除发票号码为[ ' + record.invoiceNumber + ' ]的发票吗?'
              }
              text="删除"
              onConfirm={async () => {
                let res = await postServiceInvoiceDeleteInvoice({
                  data: { invoiceId: record.invoiceId },
                });
                if (res) {
                  message.success(res.message);
                  reloadInvoiceTable();
                }
              }}
            />,
          );
        }
        return btns;
      },
    });

    return columns;
  };

  const bankStatemetColumnsInit = () => {
    let columns = BANK_STATEMENT_COLUMNS.map((item) => {
      let newItem = { ...item };
      let dataIndex = item.dataIndex;
      let dataType = item.valueType;

      newItem.render = (text, record) => {
        let textValue = record[dataIndex];

        if (dataType === 'date') {
          textValue = formatDate(textValue);
        }

        if (dataType === 'dateTime') {
          textValue = formatDateTime(textValue);
        }

        if (dataType === 'money') {
          if (textValue === null || textValue === undefined) {
            textValue = '';
          } else {
            textValue = '¥' + textValue;
          }
        }

        switch (dataIndex) {
          case 'invoiceStatus':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  INVOCING_STATUS,
                )}
              />
            );

          case 'status':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  INVOICE_STATUS,
                )}
              />
            );

          case 'payee':
            return (
              <EllipsisDiv
                text={enumValueToLabel(
                  getTableCellText(textValue),
                  PAYEE_OPTIONS,
                )}
              />
            );

          default:
            return <EllipsisDiv text={getTableCellText(textValue)} />;
        }
      };

      return newItem;
    });

    columns.push({
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 120,
      render: (text, record, _, action) => {
        let btns = [];
        if (record.path?.includes('editBankStatement')) {
          btns.push(
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.id);
              }}
            >
              编辑
            </a>,
          );
        }

        if (record.path?.includes('deleteBankStatement')) {
          btns.push(
            <ButtonConfirm
              key="delete"
              className="p-0"
              title={'是否删除该银行流水记录?'}
              text="删除"
              onConfirm={async () => {
                let res = await postServiceBankStatementDeleteBankStatement({
                  data: { id: record.id },
                });
                if (res.result === RESPONSE_CODE.SUCCESS) {
                  message.success(res.message);
                  reloadBankStatementTable();
                }
              }}
            />,
          );
        }
        return btns;
      },
    });

    return columns;
  };

  const tabsItems = [
    {
      key: 1,
      label: '发票管理',
      children: (
        <ProTable
          columns={invoicecColumnsInit()}
          actionRef={invoiceActionRef}
          cardBordered
          pagination={{
            pageSize: 10,
          }}
          request={async (params) => {
            const res = await postServiceInvoiceQueryInvoice({
              data: { ...params },
            });
            if (res) {
              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: 1400, y: 360 }}
        />
      ),
    },
    {
      key: 2,
      label: '银行流水',
      children: (
        <ProTable
          columns={bankStatemetColumnsInit()}
          actionRef={bankActionRef}
          cardBordered
          pagination={{
            pageSize: 10,
          }}
          editable={{
            type: 'multiple',
            onSave: async (rowKey, data) => {
              await postServiceBankStatementEditBankStatement({ data: data });
            },
            actionRender: (row, config, defaultDom) => [
              defaultDom.save,
              defaultDom.cancel,
            ],
          }}
          request={async (params) => {
            const res = await postServiceBankStatementQueryBankStatement({
              data: { ...params },
            });
            if (res) {
              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: 1400, y: 360 }}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setBankImportModalVisible(true);
              }}
              type="primary"
            >
              导入
            </Button>,
          ]}
        />
      ),
    },
  ];
  return (
    <div className="invoice-index">
      <Tabs
        defaultActiveKey="1"
        items={tabsItems}
        onChange={(value) => {
          if (value === 1) {
            invoiceActionRef.current?.reload();
          } else {
            bankActionRef.current?.reload();
          }
        }}
      />

      {bankImportModalVisible ? (
        <BankImportModal
          setVisible={setBankImportModalVisible}
          onClose={() => {
            setBankImportModalVisible(false);
            invoiceActionRef.current?.reload();
            bankActionRef.current?.reload();
          }}
        ></BankImportModal>
      ) : (
        ''
      )}

      {invoiceVerificationVisible ? (
        <InvoiceVerificationModal
          setVisible={setInvoiceVerificationVisible}
          invoiceId={invoiceId}
          onClose={() => {
            invoiceActionRef.current?.reload();
            bankActionRef.current?.reload();
          }}
        ></InvoiceVerificationModal>
      ) : (
        ''
      )}
    </div>
  );
};

export default InvoicePage;