/*
 * Create:      柿子
 * CreateDate:  2022/12/29
 * Describe：   更新病历模板数据并保存
 * */
import React, { Component } from 'react';
import { message, Modal, Card, Progress } from 'antd';
import CourseOfDiseaseTemplate from 'pages/common/CourseOfDiseaseTemplate.jsx';
import iconListvisits from 'assets/images/icon_listvisits.png';

class UpdateTemplateData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      rowData: {},
      templateDesc: '',
      templateData: [],
      loadingErrorCount: 0, // 加载失败次数
      percentCount: 0,
      loadingTemplateParams: {},
    };
    this.timer = null;
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

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

  // 修改弹窗状态
  modifyVisible = (visible, rowData) => {
    this.setState({ visible, rowData }, () => {
      if (this.state.visible) {
        this.handleSynchronizeXML();
      } else {
        setTimeout(() => {
          clearInterval(this.timer);
          this.setState({
            loadingErrorCount: 0, // 加载失败次数
            percentCount: 0
          });
        }, 100)
      }
    });
  }

  // 同步当前xml内容到其他模板 - 同步到其他模板
  handleSynchronizeXML = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{
          patEMRRecordID: rowData?.BSEMRRDParRef || rowData.patEMRRecordID || rowData.ID || '',
          admID: rowData && rowData.admID ? rowData.admID : ''
        }]
      }
      let res = await React.$asyncPost(this, '06050109', data);
      let templateData = res?.result || [];
      if (templateData && templateData.length > 0) {
        let templateDesc = '';
        for (let i = 0; i < templateData.length; i++) {
          templateDesc += templateData[i]?.templateName + '，'
        }
        this.setState({ templateData, templateDesc }, () => {
          this.newLoadingMedicalRecords();
          this.timer = setInterval(() => {
            this.getPercentCount();
          }, 100);
        });
      } else {
        this.modifyVisible(false);
        message.info('暂时没有数据需要同步到其他模板，请确认是否已经保存！');
      }
    } catch (error) {
      console.log(error);
      this.modifyVisible(false);
    }
  }

  newLoadingMedicalRecords = async () => {
    // const { templateData } = this.state;
    // if (templateData && templateData.length > 0) {
    //   for (let i = 0; i < templateData.length; i++) {
    //     let index = i;
    //     templateData[i].updataFlag === 'Y' && this.getEMRData(templateData[i], index);
    //   }
    // }
    const { templateData } = this.state;
    if (templateData && templateData.length > 0) {
      for (let i = 0; i < templateData.length; i++) {
        if (templateData[i].updataFlag === 'Y') {
          await this.getEMRData(templateData[i], i); // 使用await确保在进入下一次循环前完成当前请求
        }
      }
    }
  }

  // 获取病历数据
  getEMRData = async (rowData, index) => {
    try {
      let data = {
        params: [{
          patEMRRecordID: rowData?.patEMRRecordID || '',
          admID: rowData?.admID || ''
        }]
      }
      let res = await React.$asyncPost(this, '06050008', data);
      let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
      let paramsArr = [
        templatePath,
        res.result.dataSource,
        rowData,
        index,
        this.handleSave]
      this.state.loadingTemplateParams['recordID' + rowData?.patEMRRecordID || ''] = paramsArr;
      this.setState({}, () => {
        templatePath && this['caseTemplateChild' + index] && this['caseTemplateChild' + index].setElementTextByID(...paramsArr);
      })
    } catch (error) {
      console.log(error);
    }
  }

  getPercentCount = () => {
    let { templateData, percentCount, visible } = this.state;
    let succCount = 0;
    let errorCount = 0;
    let updataFlagCount = 0;
    let errorTemplateDesc = '';
    for (let i = 0; i < templateData.length; i++) {
      if (templateData[i].updataFlag === 'Y') {
        updataFlagCount += 1;
      }
      if (templateData[i].saveFlag === 'Y') {
        succCount += 1;
      } else if (templateData[i].saveFlag === 'N') {
        errorCount += 1;
        errorTemplateDesc += (templateData[i]?.templateName || '') + '^'
      }
    }
    let count = succCount + errorCount;
    if (count === updataFlagCount) {
      if (!visible) { // 预防弹窗关闭了但是定时器没关掉
        clearInterval(this.timer);
        return;
      }
      // 完成
      message.success('数据同步完成，同步了' + count + '份病历！成功了' + succCount + '份；失败了' + errorCount + '份。' + (errorCount > 0 ? '失败模板为【' + errorTemplateDesc + '】' : ''));
      this.setState({ percentCount: 100 }, () => {
        this.modifyVisible(false);
      });
    } else {
      this.setState({ percentCount: percentCount + 1 > 99 ? 99 : percentCount + 1 });
    }
  }

  handleSave = async (rowData, index, isFlag) => {
    try {
      const { loadingErrorCount, loadingTemplateParams } = this.state;
      let emrData = this['caseTemplateChild' + index] && this['caseTemplateChild' + index].getTemplateXml ? this['caseTemplateChild' + index].getTemplateXml('form', rowData, index) : '';
      if (isFlag === 'N' || emrData?.isEmptyTemplate === 'Y') {
        if (loadingErrorCount < 5) { // 加载失败次数超过五次则默认同步失败
          this.setState({ loadingErrorCount: loadingErrorCount + 1 }, () => {
            setTimeout(() => {
              let recordID = 'recordID' + (rowData?.patEMRRecordID || '');
              loadingTemplateParams && recordID in loadingTemplateParams && this['caseTemplateChild' + index] && this['caseTemplateChild' + index].setElementTextByID(...(loadingTemplateParams[recordID]));
            }, 300)
          })
        } else {
          this.state.templateData[index].saveFlag = 'N';
          this.setState({ loadingErrorCount: 0, percentCount: parseInt(((index + 1) / this.state.templateData.length) * 100) });
        }
        return;
      }
      let data = {
        params: [{
          BSEMRRDParRef: rowData?.patEMRRecordID || '', // 病历记录ID
          recordData: emrData && emrData.xmlStr ? emrData.xmlStr : '', // 病历记录数据 --- 模板xml
          progressRecIDAry: emrData && emrData.allRecordID ? emrData.allRecordID : [], // 病历记录数据 --- 病程记录ID
          progressRecDataSource: emrData?.recordDataSource || [],
          submitOrNot: 'N', // submitOrNot
          auditOrNot: 'N', // 是否审核标志
          lockStatus: 'Y', // 锁定标志
          archivingStatus: 'U', // 归档标志
          wCatalogueID: rowData?.wCatalogueID || '', // 分组目录ID
          versionID: rowData?.versionID || '', // 病历模板ID
          patRecDataSource: this['caseTemplateChild' + index] && this['caseTemplateChild' + index].getMedicalRecordFileIDAndValue && this['caseTemplateChild' + index].getMedicalRecordFileIDAndValue(), // 病历所有的输入域以及对应的值
        }]
      }
      let res = await React.$asyncPost(this, '06050004', data);
      this.state.templateData[index].saveFlag = 'Y';
    } catch (error) {
      console.log('UpdateTemplateData-193行：', error);
      this.state.templateData[index].saveFlag = 'N';
    }
    this.setState({ loadingErrorCount: 0, percentCount: parseInt(((index + 1) / this.state.templateData.length) * 100) });
  }

  render() {
    let { templateData, templateDesc, visible, percentCount } = this.state;

    return (
      <Modal
        width={800}
        visible={visible}
        title="病历数据同步中，请耐心等待……"
        footer={null}
        onCancel={() => this.modifyVisible(false)}
      >
        <div>
          <Progress percent={percentCount} />
        </div>
        <Card
          size="small"
          style={{ marginTop: '12px' }}
          title={(
            <div className="card-title-left-img">
              <img src={iconListvisits} alt="" />
              同步内容明细
            </div>
          )}
        >
          <div style={{ height: '62vh', overflow: 'auto' }}>
            <div>
              <p style={{ color: '#666', fontWeight: 'normal' }}>同步的模板如下：</p>
              <div style={{ paddingLeft: '24px' }}>
                <p>{templateDesc || '暂无信息'}</p>
              </div>
            </div>
            <div>
              {templateData && templateData.map((item, index) => {
                return (
                  <div key={index}>
                    <p style={{ color: '#666', fontWeight: 'normal' }}>{item?.templateName || ''}同步内容如下：</p>
                    {item && 'fieldArr' in item && Array.isArray(item.fieldArr) ? item.fieldArr.map((childItem, childIndex) => {
                      return (
                        <p key={childIndex} style={{ paddingLeft: '24px' }}>
                          {childItem.fieldID}：{childItem.sourceDataValue}
                        </p>
                      )
                    }) : (
                      <p style={{ paddingLeft: '24px' }}>{item?.templateName || ''}暂无同步明细</p>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        </Card>
        <div>
          {templateData && templateData.map((item, index) => {
            return (
              <div key={index} style={{ height: '0px', overflow: 'auto' }}>
                {item.updataFlag === 'Y' ? (
                  <CourseOfDiseaseTemplate
                    operationFlag="N"
                    editorID={'UpdateTemplateData' + index}
                    onRef={ref => this['caseTemplateChild' + index] = ref}
                  />
                ) : ''}
              </div>
            )
          })}
        </div>
      </Modal>
    )
  }
}

export default UpdateTemplateData;