/* eslint-disable no-shadow */
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 { saveAs } from 'file-saver';
import { format } from 'date-fns';
import { connect } from 'dva';
import { RECONCILIATION_QUERY } from '@/../config/permission.config';
import { columns, toolBarRender } from './data';
import { query, confirmSelfBill, downloadSelfBillDetail } from './service';

const ReconciliationQuery = props => {
  const { permissions } = props;
  const canEditable = permissions[RECONCILIATION_QUERY.EDITABLE];

  const actionRef = useRef();
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [selectedRows, setselectedRows] = useState([]);
  const [loading, setloading] = useState(false);
  const [pages, setpages] = useState({});
  const [billName, setbillName] = useState('');

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

  // 检查是否是同类型的
  const checkedBillType = data => {
    const billType = data[0]?.billType;
    const sameData = data.filter(item => item.billType === billType);
    if (data.length === sameData.length && sameData.length < 32) {
      const billName = billType === 10 ? '销售' : '售后';
      setbillName(billName);
      return true;
    }
    if (sameData.length > 31) {
      notification.error({ message: '一次最多选择31个账单批次' });
      return false;
    }
    notification.error({ message: '不同账单类型不可批量操作' });
    return false;
  };

  // 检查是否是确认账单
  const checkedStatus = data => {
    const sameData = data.filter(item => item.status === 1);
    if (sameData.length > 0 && data.length === sameData.length) {
      return true;
    }
    if (!sameData.length && !data.length) {
      notification.error({ message: '请选择1~31条账单批次' });
      return false;
    }
    notification.error({ message: '只有待确认账单可以确认' });
    return false;
  };

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    if (checkedBillType(selectedRows)) {
      setselectedRowKeys(selectedRowKeys);
      setselectedRows(selectedRows);
    }
  };
  const queryData = async params => {
    const { current, pageSize } = params;
    setpages({ current, pageSize });
    setselectedRowKeys([]);
    setselectedRows([]);
    const data = await query({ ...params });
    return data;
  };
  const confirmAction = async () => {
    setloading(true);
    if (checkedStatus(selectedRows)) {
      const data = await confirmSelfBill(selectedRowKeys);
      if (data.businessCode === '0000') {
        setselectedRowKeys([]);
        setselectedRows([]);
        actionRef.current.reloadAndRest();

        // reload();
        // queryData({ current: 1, pageSize: 20 })
        notification.success({ message: '确认成功' });
      }
      setloading(false);
    } else {
      setloading(false);
    }
  };

  const onDownload = async () => {
    if (selectedRowKeys.length && selectedRowKeys.length < 32) {
      setloading(true);
      const data = await downloadSelfBillDetail(selectedRowKeys);
      const blob = new Blob([data]);
      saveAs(blob, `${billName}-${format(new Date(), 'yyyyMMddHHmmss')}.xlsx`);
      setloading(false);
      setselectedRowKeys([]);
      setselectedRows([]);
      reload();
    } else {
      notification.error({ message: '请选择1~31条账单批次' });
      setloading(false);
    }
  };

  const gather = {
    onDownload,
    confirmAction,
    canEditable,
  };

  const onToolBarRender = toolBarRender(gather);

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  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.id}
          search={{
            collapsed: false,
            optionRender: searchRender,
          }}
          rowSelection={rowSelection}
          bordered
          toolBarRender={onToolBarRender}
          scroll={{ x: '100%', y: 400 }}
        />
      </PageHeaderWrapper>
    </Spin>
  );
};

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