/*
 * Create:      柿子
 * CreateDate:  2022/11/04
 * Describe：   添加范例病例
 * */
import React, { Component } from 'react';
import { Modal, Spin, Row, Col, Button, Input, Menu, Icon, Radio, Card, Dropdown, message } from 'antd';
import { Util } from 'tools';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import './style/index.less';

class MedicalRecordTemplateSelection extends Component {
  constructor(props) {
    super(props);
    var recordData = React.$getSessionData('patientData');
    var titleData = JSON.parse(sessionStorage.getItem('titleData'));
    this.state = {
      recordData,
      titleData,
      visible: false,
      spinLoading: false,
      selectData: {},
      expandedKeys: [],
      selectedKeys: [],
      templateData: {},
      treeSelectData: {},
      treeData: [],
      copyTreeData: [],
      templateName: '', // 模板名称
      sampleTemplateName: undefined, // 病历模板名称
      locBtnData: [],
      currentLocID: '',
      typeID: undefined,
      childMenuData: [],
      copyChildMenuData: [],
      childCurrentKey: '',
      childMouseOver: undefined,
      btnLoading: false,
      quoteBtnDisabled: false,
      tempMouseOver: '', // 鼠标移入模板ID
    }
  }

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

  // 修改弹窗状态
  modifyVisible = (visible, treeSelectData = {}, treeData = [], defaultSelectedKeys) => {
    let { selectData } = this.state;
    if (defaultSelectedKeys) { // 修改完成之后重新加载病历
      // let examTempID = defaultSelectedKeys && defaultSelectedKeys.indexOf('-') > -1 ? defaultSelectedKeys.split('-')[1] : defaultSelectedKeys;
      this.handleChildMenuClick({
        examTempID: defaultSelectedKeys
      });
    } else {
      if (visible && treeData && treeData.length > 0) {
        for (let i = 0; i < treeData.length; i++) {
          treeData[i].seqNo = i;
        }
        let selectedKeys = [];
        selectedKeys.push(treeData[0].templateID);
        this.setState({ treeSelectData, treeData, copyTreeData: treeData, selectedKeys, templateData: treeData[0] }, () => {
          if (JSON.stringify(selectData) === '{}') {
            this.getSelectData();
          } else {
            this.getLocBtnData('N', 'Y');
          }
        });
      }
    }
    this.setState({ visible }, () => {
      if (!visible) {
        this.setState({ btnLoading: false });
      }
    });
  }

  // 获取范例病历类型
  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '06050100');
      this.setState({ selectData: res.result, typeID: res.result?.defaultExamListTypeID || this.state.typeID }, () => {
        this.getLocBtnData('N', 'Y');
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 类型切换
  handleTypeChange = e => {
    this.setState({ typeID: e.target.value }, () => {
      this.getLocBtnData('Y', 'N');
    });
  }

  // 科室切换
  handleLocChange = item => {
    this.setState({ currentLocID: item.examListID }, () => {
      this.getChildMenuData(item);
    });
  }

  // 病历选择
  handleMenuClick = (item) => {
    this.setState({ selectedKeys: [item?.templateID || ''], templateData: item }, () => {
      this.getLocBtnData('Y', 'Y');
    })
  }

  // 获取科室层按钮数据
  getLocBtnData = async (isClearSelectKeys, isLoadingTemp) => {
    try {
      const { typeID, selectedKeys } = this.state;
      let data = {
        params: [{
          examListType: typeID, // 主表ID
          groupTemplateID: '',
          templateID: selectedKeys && selectedKeys.length > 0 ? selectedKeys[0] : '',
          type: '1', // 引用界面传入1，区别在于没有目录下没有模板就不返回目录
        }]
      }
      let res = await React.$asyncPost(this, '06050104', data);
      let locBtnData = res.result?.examListData || [];
      let allExamListSubData = [];
      if (locBtnData && locBtnData.length > 0) {
        for (var i = 0; i < locBtnData.length; i++) {
          if (locBtnData[i] && 'examListSubData' in locBtnData[i] && Array.isArray(locBtnData[i].examListSubData)) {
            allExamListSubData = [...allExamListSubData, ...(locBtnData[i]?.examListSubData || [])];
            for (var j = 0; j < locBtnData[i].examListSubData.length; j++) {
              locBtnData[i].examListSubData[j].examListID = locBtnData[i]?.examListID || '';
              locBtnData[i].examListSubData[j].examListDesc = locBtnData[i].examListDesc || '';
            }
          }
        }
      }
      locBtnData.unshift({
        examListID: '',
        examListDesc: '全部',
        examListSubData: [{
          examTempDesc: '空白模板',
          examTempID: '',
        }, ...allExamListSubData]
      })
      if (isClearSelectKeys === 'Y') {
        this.setState({ currentLocID: '' });
      }
      if (locBtnData && locBtnData.length > 0) {
        this.getChildMenuData(locBtnData[0], isLoadingTemp);
      }
      this.setState({ locBtnData });
    } catch (error) {
      console.log(error)
    }
  }

  // 子模版选择
  handleChildMenuClick = (item) => {
    this.setState({ childCurrentKey: item.examTempID, spinLoading: true }, () => {
      this.handleLoadingMedicalRecordTemplate();
    });
  }

  // 获取子模板数据
  getChildMenuData = (record, isLoadingTemp) => {
    let childMenuData = record?.examListSubData || [];
    this.setState({
      childMenuData,
      copyChildMenuData: childMenuData,
      spinLoading: isLoadingTemp === 'Y' ? true : false,
      childCurrentKey: isLoadingTemp === 'Y' && childMenuData && childMenuData.length > 0 ? childMenuData[0].examTempID : this.state.childCurrentKey
    }, () => {
      isLoadingTemp === 'Y' ? this.handleLoadingMedicalRecordTemplate() : '';
    });
  }

  // 获取病历相关数据
  handleLoadingMedicalRecordTemplate = Util.debounce(async () => {
    try {
      let { recordData, childCurrentKey, titleData, templateData } = this.state;
      if (childCurrentKey === undefined) {
        this.setState({ spinLoading: false });
        return;
      };
      let data = {
        params: [{
          // templateData && templateData.BSEMRRDParRef ? templateData.BSEMRRDParRef : (templateData?.patEMRRecordID || '')
          patEMRRecordID: '',
          admID: this.props && this.props.historyAdmID ? this.props.historyAdmID : (recordData && recordData.admID ? recordData.admID : ''),
          groupTemplateID: templateData?.templateID || '',
          power: this.props.medicalType == 'Z' ? 'OutHospRecord' : '',
          examTempID: childCurrentKey
        }]
      }
      let res = await React.$asyncPost(this, '06050106', data);
      let authority = res.result?.authority || {};
      let templatePath = res.result && res.result.templatePath ? res.result.templatePath : '';
      let progressID = templateData && templateData.progressID ? templateData.progressID : ''; // 病程记录ID
      if (authority && 'noChangeTip' in authority && authority.noChangeTip) {
        message.warning(authority.noChangeTip);
      }
      if (authority && 'updateOrNot' in authority && authority.updateOrNot !== 'Y') {
        this.setState({ quoteBtnDisabled: true });
      } else {
        this.setState({ quoteBtnDisabled: false });
      }
      let templateParams = [templatePath, res.result.dataSource, 'N', 'boolFalse', titleData && titleData.patSexDesc ? titleData.patSexDesc : '', { ...templateData, releaseVersion: templateData.releaseVersion }, templateData.templateID, progressID];
      this.caseTemplateChild && this.caseTemplateChild.setElementTextByID(...templateParams);
      this.setState({ spinLoading: false });
    } catch (error) {
      this.setState({ spinLoading: false });
    }
  })

  handleChildMenuMouseOver = item => {
    this.setState({ childMouseOver: item?.examTempID || undefined });
  }

  // 编辑
  handleModify = (item, e) => {
    e?.stopPropagation();
    this.modifyVisible(false);
    this.props.handleModify && this.props.handleModify(item);
  }

  // 删除
  handleDelete = (item, e) => {
    e?.stopPropagation();
    Modal.confirm({
      title: '删除（' + item.examTempDesc + '）提醒',
      content: '删除后不可恢复，您确定要删除吗???',
      okType: 'danger',
      onOk: () => this.handleConfirmDetele(item),
      onCancel: () => { },
    });
  }

  // 确认删除
  handleConfirmDetele = async (item) => {
    try {
      const { userData, childCurrentKey } = this.state;
      let examTempID = item?.examTempID || '';
      if (!examTempID) return;
      let data = {
        params: [{
          userID: userData?.userID || '', // 用户ID
          examTempID
        }]
      }
      let res = await React.$asyncPost(this, '06050107', data);
      message.success(res?.errorMessage || '删除成功');
      this.getLocBtnData('N', childCurrentKey === examTempID ? 'Y' : 'N');
    } catch (error) {
      console.log(error)
    }
  }

  // 根据名称过滤模板数据
  handleFilterChildMenuData = () => {
    let { sampleTemplateName, copyChildMenuData } = this.state;
    let nCopyChildMenuData = JSON.parse(JSON.stringify(copyChildMenuData));
    nCopyChildMenuData = nCopyChildMenuData && nCopyChildMenuData.filter(item => item.examTempDesc.indexOf(sampleTemplateName) > -1);
    // , childCurrentKey: nCopyChildMenuData && nCopyChildMenuData.length > 0 ? nCopyChildMenuData[0].examTempID : ''; // 默认选择模板
    this.setState({ childMenuData: nCopyChildMenuData });
  }

  // 病历引用
  handleEMRQuote = () => {
    let { templateData, childCurrentKey } = this.state;
    this.setState({ btnLoading: true }, () => {
      this.props.handleOk && this.props.handleOk({ ...templateData, examTempID: childCurrentKey });
    })
  }

  handleTemplateChange = e => {
    this.setState({ templateName: e.target.value }, () => {
      let { templateName, copyTreeData } = this.state;
      if (!templateName) {
        this.setState({ treeData: copyTreeData })
      }
    })
  }

  // 过滤版本
  handleTemplateSearch = () => {
    const { templateName, copyTreeData } = this.state;
    let treeData = JSON.parse(JSON.stringify(copyTreeData));
    treeData = treeData.filter(item => (item?.descripts.indexOf(templateName) > -1) || ('spCode' in item && typeof (item.spCode) === 'string' && (item?.spCode).toLowerCase().indexOf(templateName.toLowerCase()) > -1));
    this.setState({ treeData });
  };

  handleMenuMouseOver = item => {
    this.setState({ tempMouseOver: item?.templateID || '' })
  };

  // 移动
  handleMove = (record, index, direction, e) => {
    React.$stopPropagation(e);
    let { treeData } = this.state;
    if (index === 0 && direction === 'up') {
      message.warning('已经到顶了');
      return;
    }
    if ((index === treeData.length - 1) && direction === 'down') {
      message.warning('已经到底了');
      return;
    }
    const rowKey = record?.seqNo;
    const currentIndex = treeData.findIndex(item => item.seqNo === rowKey);
    if (direction === 'up' && currentIndex > 0) {
      [treeData[currentIndex - 1], treeData[currentIndex]] = [treeData[currentIndex], treeData[currentIndex - 1]];
      // 更新seqNo值
      treeData[currentIndex].seqNo = currentIndex;
      treeData[currentIndex - 1].seqNo = currentIndex - 1;
    } else if (direction === 'down' && currentIndex < (treeData.length - 1)) {
      [treeData[currentIndex + 1], treeData[currentIndex]] = [treeData[currentIndex], treeData[currentIndex + 1]];
      // 更新seqNo值
      treeData[currentIndex].seqNo = currentIndex;
      treeData[currentIndex + 1].seqNo = currentIndex + 1;
    };
    this.setState({ treeData }, () => {
      this.handleMoveSave();
    })
  };

  // 保存排序数据
  handleMoveSave = async () => {
    try {
      const { treeData } = this.state;
      let data = {
        params: [{
          type: 'EMR',
          listData: treeData && treeData.map((item, index) => { return { id: item?.templateSortID || '', seqNo: index + 1 } })
        }]
      }
      let res = await React.$asyncPost(this, '03020074', data);
      message.success(res?.errorMessage || '保存成功');
    } catch (error) {
      console.log(error);
    }
  };

  render() {
    const { visible, spinLoading, treeData, selectData, templateName, sampleTemplateName, treeSelectData, locBtnData, typeID, currentLocID, selectedKeys, childMenuData, childCurrentKey, childMouseOver, btnLoading,
      quoteBtnDisabled, tempMouseOver
    } = this.state;

    let param = {
      isDelete: true,
      formView: 'Normal',
      isBasicOperation: true,
      prCont: false,
      isFont: true,
      isInsert: 'hidden',
    }
    return (
      <Modal
        width="1300px"
        title={'新建病历' + (treeSelectData && treeSelectData.templateDesc ? '（' + treeSelectData.templateDesc + '）' : '')}
        footer={false}
        visible={visible}
        className="medical-record-template-selection add-sample-template"
        onCancel={() => this.modifyVisible(false)}
      >
        <Spin tip="资源加载中，请耐心等待" spinning={spinLoading} delay={300} style={{ height: '100%' }}>
          <div className="common-query-split-line" style={{ height: 2 }}></div>
          <Row>
            <Col span={4} onMouseOver={() => this.handleChildMenuMouseOver({})}>
              <div style={{ paddingRight: '6px', position: 'relative' }}>
                <div>
                  <div style={{ padding: '12px 8px' }}>
                    <Input
                      value={templateName}
                      title="回车触发信息查询"
                      style={{ width: '100%' }}
                      placeholder="请输入名称后回车查询"
                      prefix={<Icon type="search" style={{ color: '#999' }} />}
                      onChange={this.handleTemplateChange}
                      onPressEnter={this.handleTemplateSearch}
                    />
                  </div>
                  <div
                    className="mrts-right-menu"
                    style={{ height: 'calc(60vh + 86px)' }}
                  >
                    {/* <Menu
                      selectedKeys={selectedKeys}
                      onClick={this.handleMenuClick}
                    >
                      {treeData && treeData.map(item => {
                        return (
                          <Menu.Item
                            key={item.templateID}
                            title={item.descripts}
                            onMouseOver={() => this.handleMenuMouseOver(item)}
                          >
                            {item.descripts}
                            {tempMouseOver && tempMouseOver === item.templateID ? (
                              <Dropdown placement="bottomRight" overlay={(
                                <Menu style={{ minWidth: '100px' }}>
                                  <Menu.Item onClick={(e) => this.handleMove(item, 'up', e)}>
                                    <span>前移</span>
                                  </Menu.Item>
                                  <Menu.Item onClick={(e) => this.handleMove(item, 'down', e)}>
                                    <span>后移</span>
                                  </Menu.Item>
                                </Menu>
                              )}>
                                <Icon style={{ float: 'right', marginTop: '12px' }} type="menu" />
                              </Dropdown>
                            ) : ''}
                          </Menu.Item>
                        )
                      })}
                    </Menu> */}
                    {treeData && treeData.map((item, index) => {
                      return (
                        <div
                          key={item?.templateID || index}
                          className={(selectedKeys && selectedKeys.length > 0 && item.templateID === selectedKeys[0] ? 'mrts-right-menu-item-active' : '') + (item.templateID === '' ? ' mrts-right-menu-item-first' : '') + ' mrts-right-menu-item'}
                          onMouseOver={() => this.handleMenuMouseOver(item)}
                          onMouseLeave={() => this.handleMenuMouseOver({})}
                        >
                          <div style={{ padding: '0 12px' }} className="mrts-right-menu-title ellipsis flex-between-center">
                            <span style={{ width: '80%', display: 'inline-block' }} className="ellipsis" title={item.descripts} onClick={() => this.handleMenuClick(item)}>{item.descripts}</span>
                            {(tempMouseOver && tempMouseOver === item.templateID) || (selectedKeys && selectedKeys.length > 0 && item.templateID === selectedKeys[0]) ? (
                              <Dropdown placement="bottomRight" overlay={(
                                <Menu style={{ minWidth: '100px' }}>
                                  <Menu.Item onClick={(e) => this.handleMove(item, index, 'up', e)}>
                                    <span>前移</span>
                                  </Menu.Item>
                                  <Menu.Item onClick={(e) => this.handleMove(item, index, 'down', e)}>
                                    <span>后移</span>
                                  </Menu.Item>
                                </Menu>
                              )}>
                                <Icon type="menu" />
                              </Dropdown>
                            ) : ''}
                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>
                <div className='common-card-right-split-line' style={{ width: 6 }}></div>
              </div>
            </Col>
            <Col span={20}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-icon">
                    <div></div>
                    病历内容
                  </div>
                )}
              >
                <div>
                  模板名称：
                  <Input
                    value={sampleTemplateName}
                    style={{ width: '300px', marginRight: 12 }}
                    placeholder="请输入名称后回车查询"
                    className="common-query-input"
                    onChange={e => this.setState({ sampleTemplateName: e.target.value })}
                    onPressEnter={this.handleFilterChildMenuData}
                  />
                  级别：
                  <Radio.Group
                    value={typeID}
                    buttonStyle="solid"
                    style={{ marginRight: 24 }}
                    onChange={this.handleTypeChange}
                  >
                    {selectData && 'examListType' in selectData && Array.isArray(selectData.examListType) ? selectData.examListType.map((item, index) => {
                      return (
                        <Radio.Button value={item.id} key={index}>{item.descripts}</Radio.Button>
                      )
                    }) : ''}
                  </Radio.Group>
                  <Button
                    type="primary"
                    onClick={this.handleFilterChildMenuData}
                  >
                    查询
                  </Button>
                </div>
                <div style={{ margin: '12px 0' }}>
                  {locBtnData && locBtnData.map((item, index) => {
                    return (
                      <Button
                        key={index}
                        size="small"
                        shape="round"
                        style={{ marginRight: 12 }}
                        ghost={currentLocID === item.examListID ? true : false}
                        type={currentLocID === item.examListID ? "primary" : 'default'}
                        onClick={() => this.handleLocChange(item)}
                      >
                        {item.examListDesc}
                      </Button>
                    )
                  })}
                </div>
                <Row>
                  <Col span={5}>
                    <div className="mrts-right-menu scroll-bar-style">
                      {childMenuData && childMenuData.map((item, index) => {
                        return (
                          <div
                            key={index}
                            className={(item.examTempID === childCurrentKey ? 'mrts-right-menu-item-active' : '') + (item.examTempID === '' ? ' mrts-right-menu-item-first' : '') + ' mrts-right-menu-item'}
                            onClick={() => this.handleChildMenuClick(item)}
                            onMouseOver={() => this.handleChildMenuMouseOver(item)}
                          >
                            <div className="mrts-right-menu-title ellipsis" title={item.examTempDesc}>
                              <Icon type="snippets" style={{ fontSize: '16px' }} />
                              {item.examTempDesc}
                              {(childMouseOver && childMouseOver === item.examTempID) || (childCurrentKey && childCurrentKey === item.examTempID) ? (
                                <Dropdown placement="bottomRight" overlay={(
                                  <Menu style={{ minWidth: '100px' }}>
                                    <Menu.Item>
                                      <Icon type="edit" style={{ color: '#108EE9', fontSize: 16 }}></Icon>
                                      <span className="span" onClick={(e) => this.handleModify(item, e)}>编辑</span>
                                    </Menu.Item>
                                    <Menu.Item>
                                      <Icon type="delete" style={{ fontSize: 16 }} className="common-record-delete-span"></Icon>
                                      <span className="span common-record-delete-span" onClick={(e) => this.handleDelete(item, e)}>删除</span>
                                    </Menu.Item>
                                  </Menu>
                                )}>
                                  <Icon className="mrts-right-menu-desc-icon" type="menu" />
                                </Dropdown>
                              ) : ''}
                            </div>
                            <div className="mrts-right-menu-desc ellipsis" title={item?.examListDesc || '未指定'}>
                              {item?.examListDesc || '未指定'}
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </Col>
                  <Col span={19}>
                    <div
                      style={{ height: '60vh', position: 'relative' }}
                      onMouseOver={() => this.handleChildMenuMouseOver({})}>
                      {visible ? (
                        <ElectronicCaseTemplate
                          param={param}
                          editorID="addSampleTemplate"
                          onRef={ref => this.caseTemplateChild = ref}
                          handleSave={this.handleSave}
                        />
                      ) : ''}
                      {/* <div className="mrts-emr-mask"></div> */}
                      <div className="mrts-emr-footer flex-center">
                        <Button loading={btnLoading} disabled={quoteBtnDisabled} type={quoteBtnDisabled ? 'default' : 'primary'} onClick={this.handleEMRQuote}>引用此份病历</Button>
                      </div>
                    </div>
                  </Col>
                </Row>
              </Card>
            </Col>
          </Row>
        </Spin>
      </Modal>
    )
  }
};

export default MedicalRecordTemplateSelection;