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 { getUserInfo } from '@/utils/user';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Avatar, Button, Dropdown, Tabs, Tag, 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 userInfo = getUserInfo();

  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) => [
        <a
          key="editable"
          onClick={() => {
            setInvoiceVerificationVisible(true);
            setInvoiceId(record.invoiceId);
          }}
        >
          核销
        </a>,
        <Button
          className="p-0"
          key="view"
          type="link"
          onClick={() => {
            setInvoiceVerificationVisible(true);
            setInvoiceId(record.invoiceId);
          }}
        >
          查看
        </Button>,
        <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 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') {
          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) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <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 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 (
    <>
      <PageContainer
        className="invoice-index"
        header={{
          title: '发票管理',
          extra: [
            <Avatar key="0" style={{ verticalAlign: 'middle' }} size="large">
              {userInfo?.username}
            </Avatar>,
            <Tag key="nickName">{userInfo?.nickName}</Tag>,
            <Dropdown
              key="dropdown"
              trigger={['click']}
              menu={{
                items: [
                  {
                    label: '退出登录',
                    key: '1',
                    onClick: () => {
                      localStorage.removeItem('token');
                      history.push('/login');
                    },
                  },
                  // {
                  //   label: '修改密码',
                  //   key: '2',
                  // },
                ],
              }}
            >
              <Button key="4" style={{ padding: '0 8px' }}>
                <EllipsisOutlined />
              </Button>
            </Dropdown>,
          ],
        }}
      >
        <Tabs defaultActiveKey="1" items={tabsItems} />
      </PageContainer>

      {bankImportModalVisible ? (
        <BankImportModal
          setVisible={setBankImportModalVisible}
          onClose={() => {}}
        ></BankImportModal>
      ) : (
        ''
      )}

      {invoiceVerificationVisible ? (
        <InvoiceVerificationModal
          setVisible={setInvoiceVerificationVisible}
          invoiceId={invoiceId}
          onClose={() => {}}
        ></InvoiceVerificationModal>
      ) : (
        ''
      )}
    </>
  );
};

export default InvoicePage;