
import React from 'react';
import { Row, Col, Card, Button, Select, Input, Checkbox, message, Divider, Popconfirm, Table, Modal, Form, DatePicker } from 'antd';
import './style.less';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
import { TemplateTable, TemplateModalA, TemplateModalB } from './TemplateTable';
const { Option } = Select;
const { TextArea } = Input;

@Form.create()
class MedicalTemplate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bingliList: [],//选择病历
      templateLevelList: [],//模板级别
      muluList: [],//所属目录
      selectBingliID: "",//选择病历的ID

      tableArray: [],//表格数据
      // 病历目录
      muluVisible: false,
      muluStatus: 1,//1是添加 2是编辑
      IEMRMouldCataID: "",//编辑的目录id

      // 病历模板
      bingliVisible: false,
      bingliStatus: 1,//1是添加 2是编辑
      IEMRMoudleID: "",//编辑的模板id

      // 右侧保存
      saveMoudleID: "",

      elementList: [],
      searchStr: "",//查询模板名称
      // isShow: false,//仅显示生效
    }
  }
  componentDidMount() {
    this.getSelectList();
    this.queryLevelMulu();
  }

  // 1.选择病历
  getSelectList = () => {
    var patientData = sessionStorage.patientData ? JSON.parse(sessionStorage.patientData) : {};
    var params = {
      params: [{
        hospID: patientData.hospID,
        admID: patientData.admID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "10020001",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          if (res.result.TemplateList.length > 0) {
            this.setState({ bingliList: res.result.TemplateList }, () => {
              this.onSelectBingli(res.result.TemplateList[0].IEMRTemplateID);
            });
          }
        }
      }
    });
  }

  //2.查询模板级别及所属目录
  queryLevelMulu = () => {
    let obj = {
      power: "mould"
    };
    var params = {
      params: [obj]
    }
    $http.post('urlDeault', this, {
      code: "10020010",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          this.setState({ templateLevelList: res.result.data ? res.result.data : [] });
        }
      }
    });
  }

  //3.选择病历
  onSelectBingli = (e) => {
    this.setState({ selectBingliID: e }, () => {
      this.queryTableList();
    });
  }

  // 查询table数据
  queryTableList = () => {
    let obj = {
      // IEMRTemplateID: this.state.selectBingliID,
      power: "mould"
    };
    if (this.state.searchStr !== "") {
      obj.IEMRMoudleDesc = this.state.searchStr;
    }
    // if(this.state.isShow){
    //   obj.IEMRMoudleStatusCode = "Y";
    // }
    var params = {
      params: [obj]
    }
    $http.post('urlDeault', this, {
      code: "10020010",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          let newArray = res.result.data.map((data, index) => {
            return {
              key: "level"+data.id,
              id: data.id,
              rank: data.descripts,
              level: "1",
              children: data.item && data.item.map((sData, sIndex) => {
                let obj = {
                  key: sData.IEMRMouldCataID,
                  parentId:data.id,
                  classify: sData.IEMRMouldCataDesc,
                  level: "2",
                  ...sData,
                  children: sData.moudleItem && sData.moudleItem.map((ssData, ssIndex) => {
                    return {
                      key: ssData.IEMRMoudleID,
                      name: ssData.IEMRMoudleDesc,
                      handle: ssData.IEMRMoudleStatus,
                      level: "3",
                      templetTypeID: sData.templetTypeID,
                      IEMRMouldCataID: sData.IEMRMouldCataID,
                      ...ssData
                    }
                  })
                }
                if (sData.fieldType == "mould") {
                  obj.handle = sData.IEMRMoudleStatus;
                }
                return obj
              })
            }
          });
          this.setState({ tableArray: newArray, templateLevelList: res.result.data ? res.result.data : [] });
        }
      }
    });
  }

  // 查询右侧信息
  queryTemplateDetail = () => {
    var params = {
      params: [{
        IEMRMoudleID: this.state.saveMoudleID
      }]
    }
    $http.post('urlDeault', this, {
      code: "10020011",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          if (res.result.data.length > 0) {
            this.setState({ elementList: res.result.data });
          } else {
            this.queryTemplateDetail2();
          }
        }
      }
    });
  }
  queryTemplateDetail2 = () => {
    var params = {
      params: [{
        IEMRTemplateID: this.state.selectBingliID,
        power: "mouldMaintain"
      }]
    }
    $http.post('urlDeault', this, {
      code: "10020012",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          let newArray = res.result.map(item => {
            let { elementTypeCode, IEMRTempElementENDesc, ...other } = item;
            return {
              TempElementTypeCode: item.elementTypeCode,
              IEMRMoudleElementData: "",
              ...other
            }
          });
          this.setState({ elementList: newArray });
        }
      }
    });
  }

  onChangeValue = ({ target: { value } }, id) => {
    let index = this.state.elementList.findIndex(data => {
      return data.IEMRTempElementID == id;
    });
    this.state.elementList[index].IEMRMoudleElementData = value;
    this.setState({ elementList: this.state.elementList });
  }

  // 保存医生电子病历模板元素数据
  saveTempElement = () => {
    let detailData = this.state.elementList.map(item => {
      return {
        IEMRMoudleDelID: item.IEMRMoudleDelID,
        IEMRTempElementID: item.IEMRTempElementID,
        IEMRMoudleElementData: item.IEMRMoudleElementData
      }
    });
    var params = {
      params: [{
        IEMRMoudleID: this.state.saveMoudleID,
        detailData: detailData
      }]
    }
    $http.post('urlDeault', this, {
      code: "10020009",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          message.success("保存成功");
        }
      }
    });
  }

  onPressEnter = () => {
    if (this.state.selectBingliID !== "") {
      this.setState({ tableArray: [] }, () => {
        this.queryTableList();
      });
    }
  }

  // onIsShowChange = (e) => {
  //   if (this.state.selectBingliID !== "") {
  //     this.setState({ isShow: e.target.checked }, () => {
  //       this.setState({tableArray:[]},()=>{
  //         this.queryTableList();
  //       });
  //     })
  //   }
  // }

  editTemp = (row) => {
    // 目录修改
    if (row.fieldType == "catalog") {
      this.refs.muluRef.setFieldsValue({
        IEMRMouldCataDesc: row.IEMRMouldCataDesc,
        templetTypeID: Number(row.templetTypeID),
        IEMRMouldCataStartDate: row.IEMRMouldCataStartDate ? moment(row.IEMRMouldCataStartDate) : undefined,
        IEMRMouldCataStopDate: row.IEMRMouldCataStopDate ? moment(row.IEMRMouldCataStopDate) : undefined
      });
      this.setState({ muluVisible: true,muluStatus:"2", IEMRMouldCataID: row.IEMRMouldCataID });
    } else if(row.fieldType == "mould") {
      // 病历模板修改
      let templetTypeID = row.templetTypeID ?row.templetTypeID:row.parentId;
      this.onLevelChange(templetTypeID, () => {
        this.refs.bingliRef.setFieldsValue({
          IEMRMoudleDesc: row.IEMRMoudleDesc,
          templetTypeID: Number(templetTypeID),
          IEMRMouldCataID: row.templetTypeID ?row.IEMRMouldCataID+"":undefined,
          IEMRMoudleStartDate: row.IEMRMoudleStartDate ? moment(row.IEMRMoudleStartDate) : undefined,
          IEMRMoudleStopDate: row.IEMRMoudleStopDate ? moment(row.IEMRMoudleStopDate) : undefined
        });

        this.setState({ bingliVisible: true,bingliStatus:"2", IEMRMoudleID: row.IEMRMoudleID });
      });

    }
  }

  onDelete = (row) => {
    // 目录删除
    if (row.fieldType == "catalog") {
      this.setState({ IEMRMouldCataID: row.IEMRMouldCataID }, () => {
        this.onMuluOk({}, true);
      });
    } else if (row.fieldType == "mould") {
      // 病历模板删除
      this.setState({ IEMRMoudleID: row.IEMRMoudleID, saveMoudleID: "" }, () => {
        this.onBingliOk({}, true);
      });
    }
  }

  // ===病历目录===
  onOpenMuluModal = () => {
    this.refs.muluRef.resetFields();
    this.setState({ muluVisible: true,muluStatus:"1", IEMRMouldCataID: "" });
  }
  onMuluOk = (values, isDelete) => {
    let obj = {}
    // 删除
    if (isDelete) {
      obj.IEMRMouldCataID = this.state.IEMRMouldCataID;
      obj.power = "delete";
    } else {
      // 新增
      obj.IEMRMouldCataDesc = values.IEMRMouldCataDesc;
      obj.templetTypeID = values.templetTypeID;
      obj.IEMRMouldCataStartDate = values.IEMRMouldCataStartDate ? moment(values.IEMRMouldCataStartDate).format('YYYY-MM-DD') || "" : "",
        obj.IEMRMouldCataStopDate = values.IEMRMouldCataStopDate ? moment(values.IEMRMouldCataStopDate).format('YYYY-MM-DD') || "" : ""
      // 修改
      if (this.state.IEMRMouldCataID !== "") {
        obj.IEMRMouldCataID = this.state.IEMRMouldCataID;
      }
    }

    let params = {
      params: [obj]
    }
    $http.post('urlDeault', this, {
      code: "10020014",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          message.success("操作成功");
          this.closeMuluModal(() => {

            this.setState({ tableArray: [] }, () => {
              this.queryTableList();
            });

          })
        }
      }
    });
  }
  onMuluCancel = () => {
    this.closeMuluModal();
  }
  closeMuluModal = (cb) => {
    this.setState({ muluVisible: false }, () => {
      if (cb) cb();
    });
  }

  // 病历模板
  onOpenModal = () => {
    this.refs.bingliRef.resetFields();
    this.setState({ bingliVisible: true,bingliStatus:"1", IEMRMoudleID: "" });
  }

  onBingliOk = (values, isDelete) => {
    let obj = {};
    if (isDelete) {
      obj.IEMRMoudleID = this.state.IEMRMoudleID;
      obj.power = "delete";
    } else {
      // 新增
      obj.IEMRTemplateID = this.state.selectBingliID;
      obj.IEMRMoudleDesc = values.IEMRMoudleDesc;
      obj.templetTypeID = values.templetTypeID;
      obj.IEMRMouldCataID = values.IEMRMouldCataID;
      obj.IEMRMoudleStartDate = values.IEMRMoudleStartDate ? moment(values.IEMRMoudleStartDate).format('YYYY-MM-DD') || "" : "";
      obj.IEMRMoudleStopDate = values.IEMRMoudleStopDate ? moment(values.IEMRMoudleStopDate).format('YYYY-MM-DD') || "" : "";
      // 修改
      if (this.state.IEMRMoudleID !== "") {
        obj.IEMRMoudleID = this.state.IEMRMoudleID;
      }
    }
    var params = {
      params: [obj]
    }
    $http.post('urlDeault', this, {
      code: "10020007",
      data: params,
      success: function (res) {
        if (res.errorCode == '0') {
          message.success("操作成功");
          this.closeBingliModal(() => {
            this.setState({ tableArray: [] }, () => {
              this.queryTableList();
            });
          })
        }
      }
    });
  }
  onBingliCancel = () => {
    this.closeBingliModal();
  }
  closeBingliModal = (cb) => {
    this.setState({ bingliVisible: false }, () => {
      if (cb) cb();
    });
  }
  //切换
  onLevelChange = (e, cb) => {
    if (this.state.templateLevelList.length > 0) {
      this.refs.bingliRef.setFieldsValue({
        IEMRMouldCataID: ""
      });
      let obj = this.state.templateLevelList.find(data => {
        return e == data.id;
      });
      let resArr = obj.item ? obj.item : [];
         let newArr = resArr.filter(data=>{
            return "catalog" == data.fieldType
          })

      this.setState({ muluList: newArr }, () => {
        if (cb) cb();
      });
    }
  }

  onRow = (row) => {
    if (row.fieldType == "mould") {
      this.setState({ saveMoudleID: row.IEMRMoudleID }, () => {
        this.queryTemplateDetail();
      });
    }
  }
  render() {
    return (
      <div className="MedicalTemplate-wrapper">
        <Row>
          <Col span={8} >
            <Card title="病历模板列表" bordered={false}>
              <div className="wrapper-left">
                <div className="line-row line-algin">
                  <div className="line-padding">选择病历</div>
                  <div className="line-col chang-select">
                    <Select onChange={this.onSelectBingli} value={this.state.selectBingliID}>
                      {
                        this.state.bingliList.map((item, index) => {
                          return <Option value={item.IEMRTemplateID} key={index}>{item.IEMRTemplateDesc}</Option>
                        })
                      }
                    </Select>
                  </div>
                </div>
                <div className="line-row line-algin line-margin">
                  <div className="line-padding">查找模板</div>
                  <div className="line-col line-row line-algin">
                    <div className="line-col"><Input allowClear placeholder="输入模板名称回车查询" onPressEnter={this.onPressEnter} value={this.state.searchStr} onChange={(e) => this.setState({ searchStr: e.target.value })} /></div>
                    {/* <div className="line-padding"><Checkbox checked={this.state.isShow} onChange={this.onIsShowChange}>仅显示生效</Checkbox></div> */}
                    <div className="add-btns"><Button icon="plus" onClick={this.onOpenMuluModal}>病历目录</Button></div>
                    <div className="add-btn"><Button icon="plus" onClick={this.onOpenModal}>病历模板</Button></div>
                  </div>
                </div>
                <div className="line-margin">
                  {
                    this.state.tableArray.length > 0 ? <TemplateTable data={this.state.tableArray} editTemp={this.editTemp} onDelete={this.onDelete} onRow={this.onRow} /> : <Table columns={[{ title: "级别" }, { title: "分类" }, { title: "名称" }, { title: "状态" }, { title: "操作" }]} />
                  }
                  {/* <TemplateTable data={this.state.tableArray} editTemp={this.editTemp} onDelete={this.onDelete} onRow={this.onRow}/> */}
                </div>
              </div>
            </Card>
          </Col>
          <Col span={16} >
            <Card title="病历内容维护" bordered={false} >
              <div className="wrapper-right">
                {
                  this.state.elementList.length <= 0 || this.state.saveMoudleID == "" ? "请点击“+病历模板“，添加病历模板后，选择对应名称维护病历内容" : (
                    <>
                      <div className="line-row line-algin save-btn">
                        {this.state.bingliList.find((data) => data.IEMRTemplateID == this.state.selectBingliID)?.IEMRTemplateDesc}
                        <Button onClick={this.saveTempElement}>保存</Button>
                      </div>
                      {
                        this.state.elementList.map((item, index) => {
                          if (item.TempElementTypeCode == "Input" || item.TempElementTypeCode == "Labelarea") {
                            return (
                              <div className="line-row line-margin" key={"temp" + index}>
                                <div className="label-basis"> {item.IEMRTempElementDesc}</div>
                                <div className="input-basis"><TextArea rows={item.Height} value={item.IEMRMoudleElementData} onChange={(e) => this.onChangeValue(e, item.IEMRTempElementID)} /></div>
                              </div>
                            )
                          }
                        })
                      }
                    </>
                  )
                }
              </div>
            </Card>
          </Col>
        </Row>
        {/* 病历目录 */}
        <TemplateModalA
          ref="muluRef"
          visible={this.state.muluVisible}
          title={this.state.muluStatus == 1 ? "添加病目录历" : "编辑病历目录"}
          onOk={this.onMuluOk}
          onCancel={this.onMuluCancel}
          templateLevelList={this.state.templateLevelList}
        />
        {/* 病历模板 */}
        <TemplateModalB
          ref="bingliRef"
          visible={this.state.bingliVisible}
          title={this.state.bingliStatus == 1 ? "添加病历模板" : "编辑病历模板"}
          onOk={this.onBingliOk}
          onCancel={this.onBingliCancel}
          templateLevelList={this.state.templateLevelList}
          muluList={this.state.muluList}
          onLevelChange={(e) => this.onLevelChange(e)}
        />
      </div>
    )
  }
};
export default MedicalTemplate;