/* 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 { PAYMENT_MANAGE } from '@/../config/permission.config';
import ToExamineModal from './ToExamine';
import { columns, toolBarRender } from './data';
import {
  query,
  selfPaymentExport,
  selfPaymentexportDetail,
  settlement,
  merchantView,
} 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 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 merchantView(params);
    if (data.businessCode === '0000') {
      settoExamineData({ ...data.data });
      setToExamineModalVisibel(true);
    }
  };
  // 0申请结算 1上传发票 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) {
      setstatus(status);
      invoiceDetail(id);
    } else if (status === 3) {
      exportDetail(id);
    }
  };

  const onColse = () => {
    if (status === 1) {
      reload();
    }
    setToExamineModalVisibel(false);
  };
  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 onToolBarRender = toolBarRender();

  const res = {
    edit,
    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();
          }}
        />
      </PageHeaderWrapper>
    </Spin>
  );
};

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