/*
 * Create:      HYG
 * CreateDate:  2023/02/09
 * Describe：   病案首页生成PDF
 * */
import React, { Component } from 'react';
import { Spin, Row, Col, Button, message, Progress, Modal } from 'antd';
import { Util } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';

class MedicalRecordExportPDF extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      spinLoading: true,
      page: 1,
      pageSize: 20,
      columns: [],
      queryFormData: [],
      totalWidth: 0,
      tableData: [],
      loading: false,
      total: 0,
      clientQueryHeight: 0,
      rowID: '',
      selectedRows: [],
      selectedRowKeys: [],
      fullLoading: false,
      percentCount: 0,
      successCount: 0,
      errorCount: 0
    };
    this.percentTimer = null;
  }

  componentDidMount() {
    this.getColumnsData();
  }

  componentWillUnmount() {
    this.percentTimer && clearInterval(this.percentTimer);
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          type: 'C',
          compontName: 'MedicalRecordExportPDF',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let nColumns = res.result?.C || [];
      if (nColumns && nColumns.length > 0) {
        this.setState({ columns: nColumns, totalWidth: res.totalWidth });
      }
      let nFormData = res.result?.formData || [];
      this.setState({ queryFormData: nFormData, spinLoading: false }, () => {
        if (this.state.queryFormData && this.state.queryFormData.length > 0) {
          let clientQueryDom = document.getElementById('MREPEF-header-query');
          this.setState({ clientQueryHeight: clientQueryDom?.clientHeight || 64 });
        }
        this.getTableData();
      });
    } catch (error) {
      this.setState({ spinLoading: false });
    }
  }

  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async () => {
    try {
      const { page, pageSize } = this.state;
      let values = await this.formRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ loading: true }); // 分页loading
      let data = {
        params: [{
          ...values,
          error: undefined
        }],
        pagination: [{
          pageSize,
          currentPage: page,
        }]
      };
      let res = await React.$asyncPost(this, '05900004', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || [], 'patEMRRecDataID');
      this.setState({
        tableData, total: res.result?.total || 0,
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
        rowID: '',
        successCount: 0,
        errorCount: 0,
        percentCount: 0
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false });
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key });
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 导出pdf
  handleExportPDF = async (record, type, exportType, index, resolve, rejeck) => {
    try {
      const { selectedRowKeys } = this.state;
      let data = {
        params: [{
          patEMRRecDataIDArr: type === 'record' ? [record?.patEMRRecDataID || ''] : selectedRowKeys
        }]
      }
      let res = await React.$asyncPost(this, '05900005', data);
      let fileUrl = res?.fileUrl || '';
      let dataArr = res?.result || [];
      dataArr && dataArr.map((item, i) => {
        handleExcel.downloadPDF(item.base64Str, fileUrl + item.fileURL, item.savefileName);
      })
      exportType === 'all' && this.handleRecordUploadStatus(index, 'success', resolve, rejeck)
    } catch (error) {
      console.log(error);
      exportType === 'all' && this.handleRecordUploadStatus(index, 'error', resolve, rejeck)
    }
  }

  // 批量导出
  handleBatchExportPDF = () => {
    let _this = this;
    const { selectedRows } = this.state;
    if (!(selectedRows && selectedRows.length > 0)) {
      message.error('请勾选需要操作的数据');
      return;
    }
    this.setState({ fullLoading: true, percentCount: 0 }, () => {
      this.percentTimer = setInterval(() => {
        this.setState({ percentCount: this.state.percentCount + 1 > 99 ? 99 : this.state.percentCount + 1 })
      }, 300);
      async function run() {
        for (let i = 0; i < selectedRows.length; i++) {
          if (selectedRows[i].patEMRRecDataID) {
            await _this.httpBatchExportPDF(selectedRows[i], 'record', i);
          }
        }
      }
      run().then((res) => {
        console.log(res, '执行完成');
      })
    })
  }

  httpBatchExportPDF = async (record, type, index) => {
    let _this = this;
    await Promise.resolve(record, index);
    return await new Promise((resolve, rejeck) => {
      setTimeout(async () => {
        _this.handleExportPDF(record, type, 'all', index, resolve, rejeck)
      }, 300)
    });
  }

  handleRecordUploadStatus = (index, type, resolve, rejeck) => {
    let { selectedRows } = this.state;
    if (type === 'success') {
      this.state.successCount = this.state.successCount + 1;
      resolve();
    } else {
      this.state.errorCount = this.state.successCount + 1;
      resolve();
    }
    this.setState({ percentCount: parseInt(((index + 1) / selectedRows.length) * 100) }, () => {
      let { successCount, errorCount } = this.state;
      if (selectedRows.length - 1 === index) {
        clearInterval(this.percentTimer);
        Modal.success({
          title: '批量导出完成',
          content: '成功了：' + successCount + '个；失败了：' + errorCount + '个。'
        });
        // 清除操作数据
        this.setState({ successCount: 0, errorCount: 0, fullLoading: false, percentCount: 100, selectedRows: [], selectedRowKeys: [] })
      }
    });
  }

  render() {
    let { spinLoading, queryFormData, tableData, total, page, loading, totalWidth, columns, clientQueryHeight, selectedRowKeys, selectedRows, fullLoading, percentCount } = this.state;
    let nQueryFormData = queryFormData && queryFormData.length > 0 ? [...queryFormData, {
      col: 2,
      title: '查询',
      typeCode: 'Button',
      onClick: () => this.handleQuery(),
    }] : [];
    // 列表多选操作
    let rowSelection = {
      selectedRowKeys,
      selectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows,
          selectedRowKeys,
        })
      },
      getCheckboxProps: record => ({
        disabled: record.ifEMRflag !== 'Y',
      }),
    };

    let operationObj = {
      width: '120px',
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <Button
          icon="edit"
          type="link"
          disabled={record.ifEMRflag !== 'Y'}
          onClick={(e) => this.handleExportPDF(record, 'record')}
        >
          导出PDF
        </Button>
      ),
    }
    return (
      <Spin
        indicator={null}
        spinning={spinLoading || fullLoading}
        tip={(
          spinLoading ? '资源加载中' : (
            <div style={{ textAlign: 'ceter' }}>
              <Progress style={{ width: '240px' }} percent={percentCount} />
              <div>
                {percentCount === 100 ? '导出完成' : '批量导出中，请耐心等待…'}
              </div>
            </div>
          )
        )}>
        <div className="dynamic-component">
          <Row id="MREPEF-header-query" style={{ padding: '14px 24px 0 12px' }}>
            <Col span={20}>
              <DynamicRenderingForm
                className="dynamic-component-form"
                onRef={ref => this.formRef = ref}
                rowData={{}}
                formData={nQueryFormData && nQueryFormData.map((item => {
                  return {
                    ...item,
                    onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                  }
                }))}
              />
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <Button disabled={!(selectedRowKeys && selectedRowKeys.length > 0)} type="primary" onClick={this.handleBatchExportPDF}>批量导出</Button>
            </Col>
          </Row>
          <div className="common-query-split-line"></div>
          <div style={{ padding: 24 }} className="table-body-height">
            <PublicTablePagination
              param={{
                total, // 数据总条数
                page, // 当前页数
                loading,
                pageSize: '20',
                data: tableData, // 表格数据
                x: totalWidth, // 表格的宽度
                componentName: 'MedicalRecordExportPDF',
                y: store.getState().tableHeight.y + 96 - clientQueryHeight,
                height: store.getState().tableHeight.y + 146 - clientQueryHeight + 'px',
                columns: columns && columns.length > 0 ? [...columns, operationObj] : [], 	// 表头配置
              }}
              compilePage={this.compilePage}
              getColumns={this.getColumnsData}
              rowSelectionPublic={rowSelection}
              onClickRowPublic={this.onClickRowPublic}
              setRowClassNamePublic={this.setRowClassNamePublic}
            />
          </div>
        </div>
      </Spin>
    )
  }
};

export default MedicalRecordExportPDF;