/* eslint-disable no-undef */
/* eslint-disable no-shadow */
/* eslint-disable no-return-assign */
import { Button, Upload, notification, Spin } from 'antd';
import React, { useRef, useEffect, useState } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect } from 'dva';
import { columns, toolBarRender, dateStateEnum } from './data';
import { query, selfPaymentBill } from './service';
import { SETTLEMENT_SHEET } from '@/../config/permission.config';

const SettlementSheet = props => {
  const { permissions } = props;
  const canEditable = permissions[SETTLEMENT_SHEET.EDITABLE];
  const actionRef = useRef();
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [selectedRowsList, setselectedRowsList] = useState([]);
  const [loading, setloading] = useState(false);
  const [pages, setpages] = useState({});

  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };
  // 计算当前结算金额为0或负
  const checkedAmount = data => {
    const totalPrice = data.reduce(
      (totalPrice, item) => (totalPrice += Number(item.payableAmount)),
      0,
    );
    if (totalPrice <= 0) {
      notification.warning({ message: '当前结算金额为0或负' });
    }
  };
  // 检查帐期类型的最多下载条数
  const checkedBillType = data => {
    if (!data.length) {
      notification.error({ message: '请选择数据' });
      return false;
    }
    const billPeriodType = data[0]?.billPeriodType;
    const billPeriodData = dateStateEnum[billPeriodType];
    if (data.length <= billPeriodData.maxlength) {
      return true;
    }
    notification.error({
      message: `${billPeriodData.text}帐期最多可选${billPeriodData.maxlength}条`,
    });
    return false;
  };
  // 检查帐期周期是否连续
  const checkedTime = data => {
    const minTime = data[0]?.billPeriodStart;
    const maxTime = data[0]?.billPeriodEnd;
    let minTimeNum = new Date(minTime).getTime();
    let maxTimeNum = new Date(maxTime).getTime();
    if (data.length < 2) {
      return true;
    }
    for (let i = 1; i < data.length; i += 1) {
      const startTime = data[i]?.billPeriodStart;
      const endTime = data[i]?.billPeriodEnd;
      const startTimeNum = new Date(startTime).getTime();
      const endTimeNum = new Date(endTime).getTime();
      if (startTimeNum > maxTimeNum && maxTimeNum + 24 * 3600 * 1000 === startTimeNum) {
        maxTimeNum = endTimeNum;
      } else if (minTimeNum > endTimeNum && endTimeNum + 24 * 3600 * 1000 === minTimeNum) {
        minTimeNum = startTimeNum;
      }
    }
    const endRulstTime = data[data.length - 1]?.billPeriodEnd;
    const endRulstTimeNum = new Date(endRulstTime).getTime();
    if (endRulstTimeNum <= maxTimeNum && minTimeNum <= endRulstTimeNum) {
      return true;
    }
    notification.error({ message: '账单周期不连续' });
    return false;
  };
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    if (selectedRowsList.length > selectedRows.length) {
      setselectedRowKeys(selectedRowKeys);
      setselectedRowsList(selectedRows);
    } else if (checkedTime(selectedRows)) {
      setselectedRowKeys(selectedRowKeys);
      setselectedRowsList(selectedRows);
    }
  };

  const paymentOrder = async () => {
    if (checkedBillType(selectedRowsList)) {
      setloading(true);
      checkedAmount(selectedRowsList);
      const data = await selfPaymentBill(selectedRowKeys);
      if (data.businessCode === '0000') {
        setselectedRowKeys([]);
        setselectedRowsList([]);
        reload();
        notification.success({ message: '生成付款单成功' });
      }
      setloading(false);
    }
  };
  const queryData = async params => {
    const { current, pageSize } = params;
    setpages({ current, pageSize });
    setselectedRowKeys([]);
    setselectedRowsList([]);
    const data = await query({ ...params });
    return data;
  };

  const onToolBarRender = toolBarRender({ paymentOrder, canEditable });

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: record => ({
      disabled: !(record.settleState === 1 && !record.payBatchNo), // Column configuration not to be checked
    }),
  };

  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>,
  ];
  return (
    <Spin tip="处理中..." spinning={loading} delay={100}>
      <PageHeaderWrapper>
        <ProTable
          actionRef={actionRef}
          request={params => queryData(params)}
          columns={columns(pages)}
          rowKey={r => r.settleBatchNo}
          search={{
            collapsed: false,
            optionRender: searchRender,
          }}
          rowSelection={rowSelection}
          bordered
          toolBarRender={onToolBarRender}
          scroll={{ x: '100%', y: 400 }}
        />
      </PageHeaderWrapper>
    </Spin>
  );
};

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