// 新增药品
import React from 'react';
import { Button, Icon, message, Row, Col } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';

// 医嘱项
import ADAEssentialInformation from './component/ADAEssentialInformation.jsx'; // 基本信息
import ADAPharmaceuticalInformation from './component/ADAPharmaceuticalInformation.jsx'; // 药学相关信息
import ADAEquivalentUnit from './component/ADAEquivalentUnit.jsx'; // 等效单位
import ADADoctorAdviceAlias from './component/ADADoctorAdviceAlias.jsx'; // 医嘱项别名
import ADADrugRestriction from './component/ADADrugRestriction.jsx'; // 限制用药
// 库存项
import AIITollItem from './component/AIITollItem.jsx'; // 收费项
import AIIStorageCondition from './component/AIIStorageCondition.jsx'; // 存储条件 
import AIIInventoryItemAlias from './component/AIIInventoryItemAlias.jsx'; // 库存项别名
import AIIUnitMaintenance from './component/AIIUnitMaintenance.jsx'; // 发药单位维护

import '../style/index.less';

class AddDrugs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      active: 'all',
      scroll: 'all',
      essentialInformationSubValue: {}, // 基本信息form表单数据
      pharmaceuticalInformationSubValue: {}, // 药学相关信息form表单数据
      equivalentUnitTableData: [], // 等效单位表格数据
      doctorAdviceAliasTableData: [], // 医嘱项别名表格数据
      drugRestrictionTableData: [], // 限制用药表格数据
      rowId: '',
      medDetailData: {}, // 医嘱项明细
      isSaveAnother: '',
      ChineseEnglishSize: {}, //中英翻译
    }
  }

  componentDidMount() {
    this.props.onRef(this);
    document.getElementById("advice-floor-box").addEventListener('scroll', this.bindHandleScroll)
  }

  componentWillUnmount() {
    document.getElementById("advice-floor-box").removeEventListener('scroll', this.bindHandleScroll);
  }

  bindHandleScroll = event => {
    if (event.target.scrollTop === 0) {
      this.setState({ scroll: 'all' })
    } else if (event.target.scrollTop > 0 && event.target.scrollTop < 280) {
      this.setState({ scroll: '1' })
    } else if (event.target.scrollTop > 288 && event.target.scrollTop < 480) {
      this.setState({ scroll: '2' })
    } else if (event.target.scrollTop > 480 && event.target.scrollTop < 660) {
      this.setState({ scroll: '3' })
    } else if (event.target.scrollTop > 660) {
      this.setState({ scroll: '4' })
    }
  }

  // 获取医嘱项明细
  getMedDetailData = () => {
    if (!(this.state.rowId)) {
      return;
    }
    this.essentialInformationChild.resetFields();
    this.pharmaceuticalInformationChild.resetFields()
    var data = {
      params: [{
        medID: this.state.rowId
      }],
    }
    $http.post('url', this, {
      code: "02020223",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let medDetailData = res.result;
          let doseUnitTableData = medDetailData && medDetailData.doseUnit && medDetailData.doseUnit.rows ? medDetailData.doseUnit.rows : [];
          let medAliasTableData = medDetailData && medDetailData.medAlias && medDetailData.medAlias.rows ? medDetailData.medAlias.rows : [];
          let medAutTableData = medDetailData && medDetailData.medAut && medDetailData.medAut.rows ? medDetailData.medAut.rows : [];
          this.equivalentUnitChild.getTableData(doseUnitTableData);
          this.doctorAdviceAliasChild.getTableData(medAliasTableData);
          this.drugRestrictionChild.getTableData(medAutTableData);
          this.setState({ medDetailData })
        }
      }
    });
  }

  // 切换显示组件
  handleToggleActive = (key) => {
    this.setState({ active: key, scroll: key }, () => {
      if (this.state.active === "all") {
        document.getElementById("advice-floor-box").scrollTop = 0
      }
    })
  }

  resetFields = () => {
    this.essentialInformationChild.resetFields();
    this.pharmaceuticalInformationChild.resetFields();
    this.equivalentUnitChild.resetFields();
    this.doctorAdviceAliasChild.resetFields();
    this.drugRestrictionChild.resetFields();
  }

  // 重置编辑状态
  resetFieldsEditingKey = () => {
    this.equivalentUnitChild.resetFieldsEditingKey();
    this.doctorAdviceAliasChild.resetFieldsEditingKey();
    this.drugRestrictionChild.resetFieldsEditingKey();
  }

  // 新增
  handleNewlyAdded = (isQuery) => {
    this.setState({ active: 'all', medDetailData: {} }, () => {
      this.resetFields();
      isQuery ? this.props.handleQuery() : "";
    })
  }

  // 基本信息
  essentialInformationOnRef = ref => {
    this.essentialInformationChild = ref
  }

  // 药学相关信息
  pharmaceuticalInformationOnRef = ref => {
    this.pharmaceuticalInformationChild = ref
  }

  // 等效单位
  equivalentUnitOnRef = ref => {
    this.equivalentUnitChild = ref
  }

  // 医嘱项别名
  doctorAdviceAliasOnRef = ref => {
    this.doctorAdviceAliasChild = ref
  }

  // 限制用药
  drugRestrictionOnRef = ref => {
    this.drugRestrictionChild = ref
  }

  // 接收子组件form表单中的值
  receiveSubcomponentsValue = (values, flag) => {
    if (flag === 'essentialInformation') { // 基本信息
      this.setState({ essentialInformationSubValue: values })
    } else if (flag === 'pharmaceuticalInformation') { // 药学相关信息
      this.setState({ pharmaceuticalInformationSubValue: values })
    } else if (flag === 'equivalentUnit') {
      this.setState({ equivalentUnitTableData: values })
    } else if (flag === 'doctorAdviceAlias') {
      this.setState({ doctorAdviceAliasTableData: values })
    } else if (flag === 'drugRestriction') {
      this.setState({ drugRestrictionTableData: values })
    }
  }

  // 保存  flag -- 保存方式（另存，保存，默认保存） isReset -- 是否重置数据
  handleSave = (flag = "save", isReset) => {
    // 调用子组件获取值的方法
    this.essentialInformationChild.handleValidateFields();
    this.pharmaceuticalInformationChild.handleValidateFields();
    this.equivalentUnitChild.handleValidateFields();
    this.doctorAdviceAliasChild.handleValidateFields();
    this.drugRestrictionChild.handleValidateFields();

    setTimeout(() => {
      let { essentialInformationSubValue, pharmaceuticalInformationSubValue, equivalentUnitTableData, doctorAdviceAliasTableData, drugRestrictionTableData, ChineseEnglishSize } = this.state;
      if (!(essentialInformationSubValue && essentialInformationSubValue.errors)) {
        message.info(ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveBasicInfoMeg.descripts : "请完善基本信息必填项")
        return;
      }
      if (!(pharmaceuticalInformationSubValue && pharmaceuticalInformationSubValue.medSpec)) {
        message.info(ChineseEnglishSize.DrugMaintenanceimproveDrugRelatedInfoMeg ? ChineseEnglishSize.DrugMaintenanceimproveDrugRelatedInfoMeg.descripts : "请完善药品相关必填项")
        return;
      }
      let obj = { ...essentialInformationSubValue, ...pharmaceuticalInformationSubValue };
      let data = {
        params: []
      }
      obj.medID = this.state.rowId ? (flag === 'save' ? this.state.rowId : '') : '';
      obj.doseUnit = flag === 'save' ? equivalentUnitTableData : equivalentUnitTableData && equivalentUnitTableData.map(item => {
        return {
          doseUnitDesc: item.doseUnitDesc,
          doseUnitID: item.doseUnitID,
          doseQty: item.doseQty,
          defaultQty: item.defaultQty,
        }
      });
      obj.medAlias = flag === 'save' ? doctorAdviceAliasTableData : doctorAdviceAliasTableData && doctorAdviceAliasTableData.map(item => {
        return {
          medAlias: item.medAlias,
        }
      });
      obj.medAut = flag === 'save' ? drugRestrictionTableData : drugRestrictionTableData && drugRestrictionTableData.map(item => {
        return {
          operTypeID: item.operTypeID, // 类型ID
          pointerID: item.pointerID, // 类型值ID
          operateID: item.operateID, // 操作ID
          levelID: item.levelID, // 管控级别ID
        }
      });
      data.params.push(obj);
      $http.post('urlADS', this, {
        code: "02020224",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // 成功提示
            message.success(res.errorMessage);
            if (isReset === "reset") {
              this.handleNewlyAdded(true);
            } else {
              this.getMedDetailData();
            }
          } else {
            this.getMedDetailData();
          }
        },
        error: function () {
          this.getMedDetailData();
        }
      })
    }, 500)
  }

  // 收费项
  tollItemOnRef = ref => {
    this.tollItemChild = ref;
  }

  // 存储条件
  storageConditionOnRef = ref => {
    this.storageConditionChild = ref;
  }

  // 库存项别名
  inventoryItemAliasOnRef = ref => {
    this.inventoryItemAliasChild = ref;
  } 

  // 发药单位维护
  unitMaintenanceOnRef = ref => {
    this.unitMaintenanceChild = ref;
  }

  // 某点定位
  handleAnchorPositioning = item => {
    let scrollElement = document.getElementById("advice-floor-box");    // 对应id的滚动容器
    let anchorElement = document.getElementById(item.id);  // 需要定位看到的锚点元素
    if (scrollElement) {
      scrollElement.scrollTo({ top: anchorElement.offsetTop });
    }
  }

  render() {
    let { active, medDetailData, ChineseEnglishSize, scroll } = this.state;
    let isSaveAnother = this.props.isSaveAnother;
    let inventoryDetailData = [];
    let anchorData = [{
      id: "ADAEssentialInformation",
      title: "1"
    }, {
      id: "ADAPharmaceuticalInformation",
      title: "2"
    }, {
      id: "ADAEquivalentUnit",
      title: "3"
    }, {
      id: "ADADoctorAdviceAlias",
      title: "4"
    }, {
      id: "ADADrugRestriction",
      title: "5"
    }, {
      id: "AIITollItem",
      title: "6"
    }, {
      id: "AIIStorageCondition",
      title: "7"
    }, {
      id: "AIIInventoryItemAlias",
      title: "8"
    }, {
      id: "AIIUnitMaintenance",
      title: "9"
    }];
    return (
      <div className="dm-common-style">
        <Row style={{ height: "100%" }}>
          <Col span={22}>
            <div className="handle-save" style={{ border: "1px solid #e8e8e8", height: "38px", lineHeight: "38px" }}>
              <span onClick={() => this.handleNewlyAdded(true)} style={{ color: "#1999db" }}><Icon type="plus" />{ChineseEnglishSize.DrugMaintenanceadd ? ChineseEnglishSize.DrugMaintenanceadd.descripts : '新增'}</span>
              {isSaveAnother === "saveAnother" ? (
                <span onClick={() => this.handleSave('saveAs', "reset")} style={{ color: "#1890ff" }}><Icon type="nordered-list" />{ChineseEnglishSize.DrugMaintenancesaveAs ? ChineseEnglishSize.DrugMaintenancesaveAs.descripts : '另存'}</span>) : (
                <span onClick={() => this.handleSave('save', "reset")} style={{ color: "#1890ff" }}><Icon type="file" />{ChineseEnglishSize.DrugMaintenancesave ? ChineseEnglishSize.DrugMaintenancesave.descripts : '保存'}</span>
              )}

              {/* <span><Icon type="api" />最大码</span> */}
            </div>
            {/* <div className="header-button">
              <Button onClick={() => this.handleToggleActive('all')} className={(scroll === 'all') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenancecompleteInfo ? ChineseEnglishSize.DrugMaintenancecompleteInfo.descripts : '全部信息'}
              </Button>
              <Button onClick={() => this.handleToggleActive('1')} className={(scroll === '1') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenancessentialInfo ? ChineseEnglishSize.DrugMaintenancessentialInfo.descripts : '基本信息'}
              </Button>
              <Button onClick={() => this.handleToggleActive('2')} className={(scroll === '2') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenancepharmacyRelatedInfo ? ChineseEnglishSize.DrugMaintenancepharmacyRelatedInfo.descripts : '药学相关信息'}
              </Button>
              <Button onClick={() => this.handleToggleActive('3')} className={(scroll === '3') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenanceequivalentUnit ? ChineseEnglishSize.DrugMaintenanceequivalentUnit.descripts : '等效单位'}
              </Button>
              <Button onClick={() => this.handleToggleActive('4')} className={(scroll === '4') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenanceorderItemAlias ? ChineseEnglishSize.DrugMaintenanceorderItemAlias.descripts : '医嘱项别名'}
              </Button>
              <Button onClick={() => this.handleToggleActive('5')} className={(scroll === '5') ? 'active' : ''}>
                {ChineseEnglishSize.DrugMaintenancedrugRestriction ? ChineseEnglishSize.DrugMaintenancedrugRestriction.descripts : '限制用药'}
              </Button>
            </div> */}
            <div style={{ height: store.getState().tableHeight.y + 202 + 'px', overflow: 'auto' }} id="advice-floor-box">
              <div style={{ display: (active === 'all' || active === '1') ? 'block ' : 'none' }} id="ADAEssentialInformation">
                <ADAEssentialInformation
                  userInfo={medDetailData}
                  onRef={this.essentialInformationOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  selectData={this.props.medicalOrderSelectData}
                  ChineseEnglishSize={ChineseEnglishSize}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '2') ? 'block ' : 'none' }} id="ADAPharmaceuticalInformation">
                <ADAPharmaceuticalInformation
                  userInfo={medDetailData}
                  onRef={this.pharmaceuticalInformationOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  selectData={this.props.medicalOrderSelectData}
                  ChineseEnglishSize={ChineseEnglishSize}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '3') ? 'block ' : 'none' }} id="ADAEquivalentUnit">
                {/* 等效单位 */}
                <ADAEquivalentUnit
                  onRef={this.equivalentUnitOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  selectData={this.props.medicalOrderSelectData}
                  isSaveAnother={isSaveAnother}
                  ChineseEnglishSize={ChineseEnglishSize}
                  handleSave={this.handleSave}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '4') ? 'block ' : 'none' }} id="ADADoctorAdviceAlias">
                {/* 医嘱项别名 */}
                <ADADoctorAdviceAlias
                  onRef={this.doctorAdviceAliasOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  isSaveAnother={isSaveAnother}
                  ChineseEnglishSize={ChineseEnglishSize}
                  handleSave={this.handleSave}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '5') ? 'block ' : 'none' }} id="ADADrugRestriction">
                {/* 限制用药 */}
                <ADADrugRestriction
                  onRef={this.drugRestrictionOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  selectData={this.props.medicalOrderSelectData}
                  isSaveAnother={isSaveAnother}
                  ChineseEnglishSize={ChineseEnglishSize}
                  handleSave={this.handleSave}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '22') ? 'block ' : 'none' }} id="AIITollItem">
                <AIITollItem
                  userInfo={inventoryDetailData}
                  onRef={this.tollItemOnRef}
                  selectData={this.props.inventoryItemSelectData}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  ChineseEnglishSize={ChineseEnglishSize}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '33') ? 'block ' : 'none' }} id="AIIStorageCondition">
                <AIIStorageCondition
                  userInfo={inventoryDetailData}
                  onRef={this.storageConditionOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  ChineseEnglishSize={ChineseEnglishSize}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '44') ? 'block ' : 'none' }} id="AIIInventoryItemAlias">
                {/* 库存项别名 */}
                <AIIInventoryItemAlias
                  onRef={this.inventoryItemAliasOnRef}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  isSaveAnother={isSaveAnother}
                  ChineseEnglishSize={ChineseEnglishSize}
                  handleSave={this.handleSave}
                />
              </div>
              <div style={{ display: (active === 'all' || active === '55') ? 'block ' : 'none' }} id="AIIUnitMaintenance">
                {/* 发药单位维护 */}
                <AIIUnitMaintenance
                  onRef={this.unitMaintenanceOnRef}
                  selectData={this.props.inventoryItemSelectData}
                  receiveSubcomponentsValue={this.receiveSubcomponentsValue}
                  isSaveAnother={isSaveAnother}
                  ChineseEnglishSize={ChineseEnglishSize}
                  handleSave={this.handleSave}
                />
              </div>
            </div>
          </Col>
          <Col span={2} className="anchor-point-col">
            <ul className="anchor-point">
              {anchorData && anchorData.map((item, index) => {
                return <li key={index} onClick={() => this.handleAnchorPositioning(item)}>
                  {item.title}
                </li>
              })}
            </ul>
          </Col>
        </Row>
      </div>
    )
  }
};
export default AddDrugs;