/* eslint-disable no-shadow */

import { Button, notification, Modal, Spin } from 'antd';
import React, { useRef, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { saveAs } from 'file-saver';
import { format } from 'date-fns';
import moment from 'moment';
import { connect } from 'dva';
import PaymentBillModal from './components/PaymentBillModal';
import UploadInvoiceModal from './components/UploadInvoiceModal';
import InvoiceListModal from './components/InvoiceListModal';
import { PAYMENT_MANAGE } from '@/../config/permission.config';
import ToExamineModal from './ToExamine';
import { columns, toolBarRender } from './data';
import {
  query,
  selfPaymentExport,
  selfPaymentexportDetail,
  settlement,
  apiMerchantView,
} from './service';

const { confirm } = Modal;

const PaymentMange = props => {
  const { permissions } = props;
  const canEditable = permissions[PAYMENT_MANAGE.EDITABLE];
  const actionRef = useRef();
  const formRef = useRef();
  const [toExamineData, settoExamineData] = useState({});
  const [loading, setloading] = useState(false);
  const [status, setstatus] = useState(1);
  const [pages, setpages] = useState({});
  const [toExamineModalVisibel, setToExamineModalVisibel] = useState(false);
  const [visiblePaymentBill, setVisiblePaymentBill] = useState(false);
  const [paymentStatus, setPaymentStatus] = useState(0);
  const [supplierInfo, setSupplierInfo] = useState({});
  const [visibleUploadInvoice, setVisibleUploadInvoice] = useState(false);
  const [visibleInvoiceList, setVisibleInvoiceList] = useState(false);

  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 下载账单付款单明细
  const exportDetail = async params => {
    setloading(true);
    const data = await selfPaymentexportDetail(params);
    if (data) {
      const blob = new Blob([data]);
      saveAs(blob, `账单付款单明细-${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`);
    } else {
      notification.error({ message: '下载失败' });
    }
    setloading(false);
  };
  // 申请结算
  const applySettlement = async params => {
    setloading(true);
    const data = await settlement(params);
    if (data.businessCode === '0000') {
      reload();
      notification.success({ message: '申请成功' });
    }
    setloading(false);
  };
  const showConfirm = params => {
    confirm({
      title: '申请结算',
      content: '现在结算？',
      onOk() {
        applySettlement(params);
      },
    });
  };
  // 查看发票
  const invoiceDetail = async params => {
    const data = await apiMerchantView(params);
    if (data.businessCode === '0000') {
      settoExamineData({ ...data.data });
      // setToExamineModalVisibel(true);
      setVisibleInvoiceList(true);
    }
  };
  // 0申请结算 1上传发票 11补充发票 2查看发票 3下载账单付款单明细
  const edit = async (status, { id }) => {
    if (status === 0) {
      showConfirm(id);
    } else if (status === 1) {
      setstatus(status);
      settoExamineData({ id });
      setToExamineModalVisibel(true);
    } else if (status === 2) {
      settoExamineData({ id });
      setVisibleInvoiceList(true);
    } else if (status === 3) {
      exportDetail(id);
    } else if (status === 11) {
      console.log('id :>> ', id);
      settoExamineData({ id });
      setVisibleUploadInvoice(true);
    }
  };

  const onColse = () => {
    if (status === 1) {
      reload();
    }
    setToExamineModalVisibel(false);
  };
  const onCloseUploadInvoice = v => {
    setVisibleUploadInvoice(false);
    if (v === true) {
      reload();
    }
  };

  const checkedTime = ({ dateTimeRange }) => {
    const startTimeStr = moment(dateTimeRange?.[0]).format('YYYY-MM-DD');
    const endTimeStr = moment(dateTimeRange?.[1]).format('YYYY-MM-DD');
    const diffTime = moment(endTimeStr).valueOf() - moment(startTimeStr).valueOf();
    const maxTime = 62 * 3600 * 24 * 1000;
    if (!dateTimeRange?.[0]) {
      notification.error({ message: '付款单开始时间不能为空' });
      return false;
    }
    if (diffTime > maxTime) {
      notification.error({ message: '只允许下载2个月的数据' });
      return false;
    }
    return true;
  };
  const onExport = async () => {
    const params = formRef.current.getFieldsValue();
    setloading(true);
    if (checkedTime(params)) {
      const data = await selfPaymentExport(params);
      const blob = new Blob([data]);
      saveAs(blob, `付款单导出数据-${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`);
    }
    setloading(false);
  };
  // 上传付款单和查看付款单
  const onPaymentOrder = (status, row) => {
    setPaymentStatus(status);
    setSupplierInfo(row);
    setVisiblePaymentBill(!0);
  };

  const onToolBarRender = toolBarRender();

  const res = {
    edit,
    onPaymentOrder,
    canEditable,
  };

  const searchRender = ({ searchText, resetText }, { form }) => [
    <Button
      key="search"
      type="primary"
      style={{ marginRight: '10px' }}
      onClick={() => {
        // eslint-disable-next-line no-unused-expressions
        form?.submit();
      }}
    >
      {searchText}
    </Button>,
    <Button
      key="rest"
      style={{ marginRight: '10px' }}
      onClick={() => {
        // eslint-disable-next-line no-unused-expressions
        form?.resetFields();
        // eslint-disable-next-line no-unused-expressions
        form?.submit();
      }}
    >
      {resetText}
    </Button>,
    <Button
      key="export"
      type="primary"
      style={{ marginRight: '10px' }}
      onClick={() => {
        // eslint-disable-next-line no-unused-expressions
        onExport();
      }}
    >
      导出
    </Button>,
  ];

  return (
    <Spin tip="处理中..." spinning={loading} delay={100}>
      <PageHeaderWrapper>
        <ProTable
          actionRef={actionRef}
          formRef={formRef}
          request={params => {
            const { current, pageSize } = params;
            setpages({ current, pageSize });
            return query({ ...params });
          }}
          columns={columns(res, pages)}
          rowKey={r => r.id}
          search={{
            collapsed: false,
            optionRender: searchRender,
          }}
          bordered
          toolBarRender={onToolBarRender}
          scroll={{ x: '100%', y: 500 }}
        />

        <ToExamineModal
          visible={toExamineModalVisibel}
          toExamineData={toExamineData}
          status={status}
          close={() => {
            onColse();
          }}
        />

        {visiblePaymentBill && (
          <PaymentBillModal
            visible={visiblePaymentBill}
            status={paymentStatus}
            info={supplierInfo}
            onRefresh={() => reload()}
            onClose={() => setVisiblePaymentBill(false)}
          />
        )}
      </PageHeaderWrapper>
      {visibleUploadInvoice && (
        <UploadInvoiceModal onCancel={onCloseUploadInvoice} id={toExamineData.id} />
      )}
      {visibleInvoiceList && (
        <InvoiceListModal onCancel={setVisibleInvoiceList} id={toExamineData.id} />
      )}
    </Spin>
  );
};

export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(PaymentMange);
