<template>
  <div class="emr">
    <div class="header flex flex-col-center flex-row-center">
      <span>{{temItem.templateName}}</span>
      <div class="button">
        <!--<el-button type="success" size="mini" @click="handleHisMsg()">回传HIS(JS通知)</el-button>-->
        <el-button v-if="load_SST" type="primary" size="mini" @click="showAiDialog = true">自然语言处理</el-button>
        <el-button type="primary" size="mini" @click="handleHis()">回传HIS</el-button>
        <el-button type="primary" size="mini" @click="submit()">保存病历</el-button>
      </div>
    </div>
    <div class="flex flex-col-top flex-row-left emr-main-body">
      <div class="emr-template">
        <div class="emr-template-header flex felx-col-center flex-row-left">
          <img src="~@/assets/book.png" alt />
          <div>电子病历模板</div>
        </div>
        <div v-for="(item,index) in templateList" :key="index">
          <div class="emr-tem-item title ellipsis-line1">{{item.name}}</div>
          <div
            class="emr-tem-item ftitle ellipsis-line1"
            @click="templateClick(item1)"
            v-for="(item1,index1) in item.temList"
            :key="index1"
          >{{item1.templateName}}</div>
        </div>
      </div>
      <div class="emr-form">
        <PriviewEdit ref="edit" :editListF="temItem.templateContent" v-model="previewPicture"></PriviewEdit>
      </div>
    </div>

    <el-dialog
      :title="priviewItem.templateName+'预览'"
      :visible.sync="dialogVisible"
      width="80%"
      top="5vh"
      :before-close="handleClose"
    >
      <div class="priview-body">
        <PriviewEdit :editListF="priviewItem.templateContent"></PriviewEdit>
        <div class="flex flex-row-center">
          <el-button size="small" @click="handleClose">取消</el-button>
          <el-button size="small" type="primary" @click="changeTemplate">切换模板</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog v-if="load_SST" class="ai-dialog-wrapper" title="自然语言处理" :visible.sync="showAiDialog" center :close-on-click-modal="false" :before-close="closeAiDialog">
      <div style="position: relative; height: 100%; overflow: hidden;">
        <el-input
            type="textarea" :readonly="aiLoading"
            :autosize="{ minRows: 4, maxRows: 8}"
            placeholder="请描述患者的病情"
            v-model="aiText">
        </el-input>
        <SoundRecorder style="position: absolute; right: 12px; bottom: 12px;"
                       :enabled="showAiDialog"
                       @begin="aiTextBackups = aiText;" @change="aiText = aiTextBackups + $event;" @finish="aiText = aiTextBackups + $event;"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="aiLoading" @click="closeAiDialog()">取 消</el-button>
        <el-button type="primary" :loading="aiLoading" :disabled="!load_NLP" @click="loadAi()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addEMR, getEmrShowMsg, editEMR, backToHis, getNLP_TemplateResult } from "@/api/diagnosis.js";

import { getTemplateList, getLastTemId, saveLastTemId } from "@/api/emr";
import { mapGetters, mapMutations } from "vuex";
import uploadFile from "@/components/UploadFile.vue";
import PriviewEdit from "../business/components/PriviewEdit.vue";

import {formatPicture, toPicture} from "@/utils/picture";
import SoundRecorder from '@/components/SoundRecorder.vue';
import {inform} from '@/utils/url';

export default {
  components: {
    SoundRecorder,
    uploadFile,
    PriviewEdit
  },
  data() {
    return {
      load_SST: window.SIX_config.SST_TOKEN_URL,
      load_NLP: window.SIX_config.NLP_GET_URL,
      showAiDialog: false,
      aiLoading: false,
      aiText: '',
      aiTextBackups: '',
      isSkip: true,
      isEdit: false, // 是否修改
      activeId: "",
      pid: "",
      lastTemId: "",
      templateList: [
        {
          name: "医共体",
          temList: []
        },
        {
          name: "全院",
          temList: []
        },
        {
          name: "科室",
          temList: []
        },
        {
          name: "个人",
          temList: []
        }
        // {
        //   name: "专病",
        //   temList: []
        // }
      ],
      temItem: {},
      priviewItem: {},
      previewPicture: [],
      dialogVisible: false
    };
  },

  created() {
    this.activeId = this.getActiveID;
    this._getLastTemId();
    setTimeout(() => {
      this._getTemplateList();
    }, 200);
    if (this.$route.query.type == "trun") {
      setTimeout(() => {
        this.getEmrShowMsg();
        // this.assignToTem()
      }, 500);
    } else {
      setTimeout(() => {
        this.getEmrShowMsg();
      }, 500);
    }
  },
  watch: {
    temItem: {
      deep: true,
      // immediate:true,
      handler: function() {
        this.isEdit = true;
      }
    }
  },

  beforeRouteLeave(to, from, next) {
    this._saveLastTemId();
    if (!this.isEdit) {
      next();
    } else {
      this.$confirm("当前修改内容尚未保存,是否要保存?", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "不保存",
        type: "warning"
      })
        .then(() => {
          this.submit(next);
        })
        .catch(() => {
          next();
        });
    }
  },
  methods: {
    closeAiDialog(done) {
      if (this.aiLoading) return;
      if (done) done();
      this.showAiDialog = false;
      this.aiText = '';
    },
    async loadAi() {
      if (this.aiText && this.aiText.trim()) {
        this.aiLoading = true;
        try {
          const result = await getNLP_TemplateResult(this.aiText.trim());
          if (result) {
            this.showMsgToTem(result);
            this.aiText = ``;
          } else throw { message: `` }
        } catch (e) {
          if (e.message) this.$message.error(e.message);
          this.aiLoading = false;
          return;
        }
      }
      this.aiLoading = false;
      this.closeAiDialog();
    },
    // 关闭预览弹窗
    handleClose() {
      this.dialogVisible = false;
      this.priviewItem = {};
    },
    // 切换模板
    changeTemplate() {
      this.$confirm("是否清除当前模板内容？", "提示", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          this.temItem = {};
          this.temItem = this.priviewItem;
          this.temItem.templateContent = this.priviewItem.templateContent;
          this.handleClose();
        })
        .catch(() => {
          this.assignTemplate(this.$refs.edit.editList, this.priviewItem);
        });
    },
    //模板点击
    templateClick(item) {
      let tem = {};
      try {
        tem = JSON.parse(item.templateContent);
      } catch {
        tem = item.templateContent;
      }
      this.priviewItem = {};
      this.priviewItem = item;
      this.priviewItem.templateContent = tem;

      this.dialogVisible = true;
    },
    assignToTem() {
      let data = JSON.parse(this.getEmrDiagnosis);
      let tem = this.$refs.edit.editList;
      tem.forEach(item => {
        if (
          item.level == 1 &&
          (item.selectValue == "textarea" || item.selectValue == "input")
        ) {
          if (item.label == "主诉") {
            item.inputDefaultValue = data.chiefcomplaint;
          }
          if (item.label == "现病史") {
            item.inputDefaultValue = data.historypresent;
          }
          if (item.label == "既往史") {
            item.inputDefaultValue = data.pasthistory;
          }
          if (item.label == "中医四诊") {
            item.inputDefaultValue = data.fourmedicine;
          }
          if (item.label == "体格检查") {
            item.inputDefaultValue = data.physicalexamination;
          }
          if (item.label == "辅助检查") {
            item.inputDefaultValue = data.supplementaryexamination;
          }
        }
      });
      this.temItem = {};

      this.temItem.templateContent = tem;
    },
    // 模板赋值
    assignTemplate(tem1, itemF) {
      /*
              tem1 已经再页面中的模板
              tem2 要赋值进去的模板
            */
      let tem2 = "";
      try {
        tem2 = JSON.parse(itemF.templateContent);
      } catch {
        tem2 = itemF.templateContent;
      }

      // 赋值
      tem1.forEach(item => {
        tem2.forEach(item1 => {
          if (
            item.level == 1 &&
            (item.selectValue == "textarea" || item.selectValue == "input")
          ) {
            let value = item.inputDefaultValue;

            if (
              item1.level == 1 &&
              item.id == item1.id &&
              (item1.selectValue == "textarea" || item1.selectValue == "input")
            ) {
              item1.inputDefaultValue = value;
            }
          }

          if (
            item.level != 1 &&
            item1.level != 1 &&
            item.inputValue == item1.inputValue &&
            item.selectValue == "fill" &&
            item1.selectValue == "fill"
          ) {
            item1.fillValues = item.fillValues;
            item1.radioList.forEach(item2 => {
              if (item1.fillValues.includes(item2.label)) {
                item2.radioDefault = true;
              }
            });
          }
        });
      });

      this.temItem = {};
      this.temItem = itemF;
      this.temItem.templateContent = tem2;
      this.handleClose();
    },
    // 数据提交
    submit(next = null) {
      let dataList = this.$refs.edit.editList;
      let isReq = false; // 必填项是否填完
      dataList.forEach(item => {
        if (item.isReq) {
          if (item.selectValue == "input" && !item.inputDefaultValue) {
            isReq = true;
          }
          if (item.selectValue == "textarea" && !item.inputDefaultValue) {
            isReq = true;
          }
          if (item.selectValue == "radio" && !item.radioListValue) {
            isReq = true;
          }
          if (item.selectValue == "checkbox") {
            let isCheck = false;
            item.radioList.map(item1 => {
              if (item1.radioDefault) {
                isCheck = true;
              }
            });
            if (!isCheck) {
              isReq = true;
            }
          }
          if (item.selectValue == "fill" && item.fillValues.length == 0) {
            isReq = true;
          }
        }
      });
      if (isReq) {
        this.$message.warning("请完成必填项填写");
        this.setActiveID(this.activeId);
        return;
      }
      if (this.pid) {
        this.editEMR(next);
        return;
      }
      this.addEMR(next);
    },
    handleHisMsg() {
      let msg = {
        origin: "EMR",
        msg: "刷新数据"
      };
      inform(msg);
      console.log(window.parent, "打印父级页面");
      console.log("---执行了发送消息的代码----");
    },
    // 回传his
    handleHis() {
      let dataList = this.$refs.edit.editList;
      let isReq = false; // 必填项是否填完
      dataList.forEach(item => {
        if (item.isReq) {
          if (item.selectValue == "input" && !item.inputDefaultValue) {
            isReq = true;
          }
          if (item.selectValue == "textarea" && !item.inputDefaultValue) {
            isReq = true;
          }
          if (item.selectValue == "radio" && !item.radioListValue) {
            isReq = true;
          }
          if (item.selectValue == "checkbox") {
            let isCheck = false;
            item.radioList.map(item1 => {
              if (item1.radioDefault) {
                isCheck = true;
              }
            });
            if (!isCheck) {
              isReq = true;
            }
          }
          if (item.selectValue == "fill" && item.fillValues.length == 0) {
            isReq = true;
          }
        }
      });

      if (isReq) {
        this.$message.warning("请完成必填项填写");
        this.setActiveID(this.activeId);
        return;
      }

      this.setDataToHis();
    },

    // 合并 编辑器内 非一级数据
    flat(list) {
      const idMap = new Map();
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        item.children = [];
        idMap.set(item.id, item);
      }

      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const parent = idMap.get(item.father);
        if (!parent) continue;

        parent.children.push(item);
      }
      return list;
    },
    // 合并值
    joinList(list) {
      const joinChildren = childrenList => {
        const resultList = [];
        for (let i = 0; i < childrenList.length; i++) {
          const item = childrenList[i];

          resultList.push(item);

          if (item.children) {
            resultList.push(...joinChildren(item.children));
          }
        }

        return resultList;
      };

      const result = [];
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (item.level === 1) {
          result.push(item);
        }
      }

      for (let i = 0; i < result.length; i++) {
        const item = result[i];

        item.flatChildren = joinChildren(item.children);
      }

      return result;
    },
    // 返回要上传的数据
    backUploadData() {
      let sourceData = JSON.parse(JSON.stringify(this.$refs.edit.editList));
      let list = this.flat(sourceData);

      let joinArr = this.joinList(list);

      const paramsData = {
        chiefcomplaint: "", // 主诉
        fourmedicine: "", // 中医四诊
        historypresent: "", // 现病史
        pasthistory: "", // 既往史
        physicalexamination: "", // 体格检查
        supplementaryexamination: "" // 辅助检查
      };
      joinArr.forEach(item => {
        item.joinStr = "";
        if (item.selectValue == "input" && item.inputDefaultValue) {
          item.joinStr = item.inputDefaultValue + ";";
        }
        if (item.selectValue == "textarea" && item.inputDefaultValue) {
          item.joinStr = item.inputDefaultValue + ";";
        }
        if (item.selectValue == "radio" && item.radioListValue) {
          item.joinStr = item.radioListValue;
        }
        if (item.selectValue == "checkbox") {
          let arr = item.radioList.map(item1 => {
            if (item1.radioDefault) {
              return item1.label;
            }
          });
          item.joinStr = arr.join(",") + ";";
        }
        if (item.selectValue == "fill") {
          item.joinStr = item.fillValues.join(",") + ";";
        }

        item.flatChildren.forEach(item1 => {
          if (item1.selectValue == "input" && item1.inputDefaultValue) {
            item.joinStr += item1.inputDefaultValue + ";";
          }
          if (item1.selectValue == "textarea" && item1.inputDefaultValue) {
            item.joinStr += item1.inputDefaultValue + ";";
          }
          if (item1.selectValue == "radio" && item1.radioListValue) {
            item.joinStr += item1.radioListValue;
          }
          if (item1.selectValue == "checkbox") {
            let arr = [];
            item1.radioList.forEach(item2 => {
              if (item2.radioDefault) {
                arr.push(item2.label);
              }
            });

            item.joinStr += arr.join(",") + ";";
          }
          if (item1.selectValue == "fill") {
            item.joinStr += item1.fillValues.join(",") + ";";
          }
        });

        if (item.id == 1) {
          paramsData.chiefcomplaint = item.joinStr;
        }
        if (item.id == 2) {
          paramsData.historypresent = item.joinStr;
        }
        if (item.id == 3) {
          paramsData.pasthistory = item.joinStr;
        }
        if (item.id == 4) {
          paramsData.fourmedicine = item.joinStr;
        }
        if (item.id == 5) {
          paramsData.physicalexamination = item.joinStr;
        }
        if (item.id == 6) {
          paramsData.supplementaryexamination = item.joinStr;
        }
      });

      return paramsData;
    },
    // 获取与目标数组中不同的部分
    findDifferences(arr1, arr2) {
      return arr2.filter(value => !arr1.includes(value));
    },
    // 获取与目标数组中相同的部分
    findSame(arr1, arr2) {
      return arr2.filter(value => arr1.includes(value));
    },
    // 去重
    removeRepate(arr) {
      let arr1 = new Set(arr);
      return Array.from(arr1);
    },
    // 回显的值 赋值给模板
    showMsgToTem(data) {
      let _this = this;
      const paramsData = {
        chiefcomplaint: data.chiefcomplaint, // 主诉
        // fourmedicine: data.fourmedicine, // 中医四诊
        fourmedicine: "",
        historypresent: data.historypresent, // 现病史
        pasthistory: data.pasthistory, // 既往史
        physicalexamination: data.physicalexamination, // 体格检查
        supplementaryexamination: data.supplementaryexamination, // 辅助检查
        echoData: JSON.parse(data.echoData)
      };
      let tem = this.$refs.edit.editList;

      tem.forEach(item => {
        if (
          item.id == 1 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 主诉赋值
          item.inputDefaultValue = paramsData.chiefcomplaint;
        }
        if (
          item.id == 2 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 现病史赋值
          item.inputDefaultValue = paramsData.historypresent;
        }

        if (
          item.id == 3 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 既往史赋值
          item.inputDefaultValue = paramsData.pasthistory;
        }

        if (
          item.id == 4 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 中医四诊赋值
          item.inputDefaultValue = paramsData.fourmedicine;
        }
        if (
          item.id == 5 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 体格检查赋值
          item.inputDefaultValue = paramsData.physicalexamination;
        }
        if (
          item.id == 6 &&
          item.level == 1 &&
          (item.selectValue == "input" || item.selectValue == "textarea")
        ) {
          // 辅助检查赋值
          item.inputDefaultValue = paramsData.supplementaryexamination;
        }
      });
      console.log(paramsData.echoData);
      //console.log(tem);
      if (!data.updateTime) {
        for (let i in paramsData.echoData) {
          let labelKey = i.split("-")[1];
          let flabelKey = i.split("-")[0];
          let echoItem = paramsData.echoData[i];
          let otherStr = ""; // 其他选项
          let isFind = false; // 是否查找到了
          tem.forEach(item => {
            // if (labelKey == item.inputValue && item.selectValue == "fill") {

            if (i == flabelKey + "-" + item.inputValue) {
              if (item.selectValue == "fill") {
                isFind = true;
                let radioLabels = item.radioList.map(item1 => item1.label);
                let diffValues = _this.findDifferences(radioLabels, echoItem);

                otherStr = diffValues.join(";");
                item.fillValues = [
                  ...item.fillValues,
                  ..._this.findSame(radioLabels, echoItem)
                ];

                item.fillValues = _this.removeRepate(item.fillValues);

                item.radioList.forEach(item1 => {
                  if (echoItem.includes(item1.label)) {
                    item1.radioDefault = true;
                  }
                });
              }
            } else {
              if (!isFind) {
                otherStr = echoItem.join(";");
              }
            }

            if (item.inputValue == flabelKey + "—其他") {
              if (otherStr) {
                if (item.inputDefaultValue) {
                  item.inputDefaultValue =
                    item.inputDefaultValue + ";" + otherStr;
                } else {
                  item.inputDefaultValue = otherStr;
                }
              }
            }
          });
        }
      }

      this.temItem.templateContent = [];
      this.temItem.templateContent = tem;
    },
    // 获取所有电子病历模板
    async _getTemplateList() {
      let res = await getTemplateList();
      if (res.ResultCode == 0) {
        this.templateList[0].temList = res.Data.currency;
        this.templateList[1].temList = res.Data.theWholeHospital;
        this.templateList[2].temList = res.Data.department;
        this.templateList[3].temList = res.Data.personal;
        // this.templateList[4].temList = res.Data.specialDisease

        if (this.lastTemId) {
          try {
            this.templateList.forEach(item => {
              item.temList.forEach(item1 => {
                if (item1.pid === this.lastTemId) {
                  this.temItem = item1;
                  this.temItem.templateContent = JSON.parse(
                    item1.templateContent
                  );
                  throw Error();
                }
              });
            });
          } catch {}
        } else {
          try {
            this.templateList.forEach(item => {
              item.temList.forEach(item1 => {
                if (item1.isDefault === "0") {
                  this.temItem = item1;
                  this.temItem.templateContent = JSON.parse(
                    item1.templateContent
                  );
                  throw Error();
                }
              });
            });
          } catch {}
        }

        if (Object.keys(this.temItem).length == 0) {
          this.templateList.forEach(item => {
            item.temList.forEach(item1 => {
              if (item1.templateType === "-1") {
                this.temItem = item1;
                this.temItem.templateContent = JSON.parse(
                  item1.templateContent
                );
                throw Error();
              }
            });
          });
        }

        setTimeout(() => {
          this.isEdit = false;
        }, 1000);
      }
    },
    // 提交数据
    async addEMR(next = null) {
      let paramsData = this.backUploadData();
      let images = this.$refs.edit.imageUrl;

      let params = {
        image1: toPicture(images), // 报告上传
        // 患者id
        recordsid: this.getPatiensInfo.pid,
        templateId: this.temItem.pid,
        templateContent: JSON.stringify(this.$refs.edit.editList)
      };
      Object.assign(params, paramsData);
      const loading = this.$loading({
        lock: true,
        text: "正在保存",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let res = await addEMR(params).catch(err => {});
      loading.close();
      if (!this.isSkip) return this.$emit("hack_save", res);
      if (res.ResultCode == 0) {
        this.$message({
          type: "success",
          message: "保存成功",
          showClose: true
        });
        this.isEdit = false;
        if (next) {
          if (next == "none") {
            let msg = {
              origin: "EMR",
              msg: "刷新数据"
            };
            inform(msg);
            return;
          }
          next();
        } else {
          setTimeout(() => {
            this.$router.push({
              //path: "/index/diagnosis"
              path: "/index/prescribing"
            });
          }, 1500);
        }
      }
    },
    // 回传his 接口
    async setDataToHis() {
      let paramsData = this.backUploadData();
      let images = this.$refs.edit.imageUrl;

      let params = {
        image1: toPicture(images), // 报告上传
        // 患者id
        recordsid: this.getPatiensInfo.pid,
        templateId: this.temItem.pid,
        templateContent: JSON.stringify(this.$refs.edit.editList)
      };
      Object.assign(params, paramsData);
      const loading = this.$loading({
        lock: true,
        text: "正在保存",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let res = await backToHis(params).catch(err => {
        loading.close();
      });

      if (res.ResultCode == 0) {
        loading.close();

        this.$message({
          type: "success",
          message: "保存成功",
          showClose: true
        });
        // this.isEdit = false;
        if (this.pid) {
          this.editEMR("none");
          return;
        }
        this.addEMR("none");

        // console.log("消息发送成功");
      }
    },
    // 回显展示
    async getEmrShowMsg() {
      let _self = this;
      let params = {
        recordsId: this.getPatiensInfo.pid
      };
      let res = await getEmrShowMsg(params);
      if (res.ResultCode == 0) {
        if (res.Data.length == 0) return;
        this.pid = res.Data[0].pid;

        if (res.Data[0].templateId) {
          let hasId = false;
          // 有模板id的情况
          try {
            this.templateList.forEach(item => {
              item.temList.forEach(item1 => {
                if (item1.pid === res.Data[0].templateId) {
                  hasId = true;
                  this.temItem = {};
                  this.temItem = item1;
                  this.temItem.templateContent = JSON.parse(
                    res.Data[0].templateContent
                  );

                  //
                  let tem = this.$refs.edit.editList;
                  setTimeout(() => {
                    this.showMsgToTem(res.Data[0]);
                  }, 1000);

                  throw Error();
                }
              });
            });
          } catch {}
          if (!hasId) {
            this.showMsgToTem(res.Data[0]);
          }
        } else {
          this.showMsgToTem(res.Data[0]);
        }
        this.previewPicture = res.Data[0].image1 = formatPicture(res.Data[0].image1);

        setTimeout(() => {
          this.isEdit = false;
          console.log(this.$refs.edit.imageUrl, "图片地址");
        }, 1000);
      }

      this.$emit('hack_loaded')
    },
    // 修改 中医电子病历
    async editEMR(next = null) {
      let paramsData = this.backUploadData();
      let images = this.$refs.edit.imageUrl;

      let params = {
        image1: toPicture(images), // 报告上传
        // 患者id
        recordsid: this.getPatiensInfo.pid,
        pid: this.pid,
        templateId: this.temItem.pid,
        templateContent: JSON.stringify(this.$refs.edit.editList)
      };
      Object.assign(params, paramsData);
      const loading = this.$loading({
        lock: true,
        text: "正在保存",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await editEMR(params).catch(err => {});
      loading.close();
      if (!this.isSkip) return this.$emit("hack_save", res);

      if (res.ResultCode == 0) {
        this.$message({
          type: "success",
          message: "保存成功",
          showClose: true,
          duration: 1000
        });
        this.isEdit = false;
        if (next) {
          if (next == "none") {
            let msg = {
              origin: "EMR",
              msg: "刷新数据"
            };
            inform(msg);
            return;
          }
          next();
        } else {
          setTimeout(() => {
            this.$router.push({
              //path: "/index/diagnosis"
              path: "/index/prescribing"
            });
          }, 1500);
        }
      }
    },
    // 存储最后一次使用的模板id
    async _saveLastTemId() {
      let res = await saveLastTemId({
        templateId: this.temItem.pid
      });
    },
    async _getLastTemId() {
      let res = await getLastTemId();
      if (res.ResultCode == 0) {
        this.lastTemId = res.Data.templateId;
      }
    },
    ...mapMutations({
      setActiveID: "nav/setActiveID"
    })
  },

  computed: {
    ...mapGetters(["getPatiensInfo", "getActiveID", "getEmrDiagnosis"])
  }
};
</script>
<style lang="scss" scoped>
.emr-main-body {
  height: 73vh;
}

.emr {
  // background: #FFFFFF;
  border-radius: 5px;
  padding: 0px 0px;

  .header {
    background: #fff;
    height: 40px;
    position: relative;
    margin-bottom: 5px;

    span {
      font-size: 20px;
      font-weight: bold;
      color: #000;
    }

    .button {
      position: absolute;
      top: 6px;
      right: 16px;
    }
  }

  .emr-title {
    span {
      width: 3px;
      height: 14px;
      background: #5386f6;

      border-radius: 1px;
      display: inline-block;
    }

    div {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #5386f6;
      margin-left: 9px;
    }
  }

  .emr-template {
    width: 260px;
    margin-right: 8px;
    height: 100%;
    min-height: 430px;
    background: #fff;
    box-sizing: border-box;
    padding: 8px 0;
    overflow-y: auto;

    .emr-template-header {
      padding: 0 8px 8px;
      border-bottom: 1px solid #f4f7f9;

      img {
        width: 30px;
      }

      div {
        color: #000;
        font-size: 16px;
        font-weight: 600;
        margin-left: 5px;
      }
    }

    .emr-tem-item {
      padding: 8px;
      border-bottom: 1px solid #f4f7f9;
      cursor: pointer;
    }

    .title {
      color: #000;
      font-size: 16px;
      font-weight: 600;
      // margin-left: 5px;
    }

    .ftitle {
      color: #000;
      font-size: 14px;
    }
  }

  .emr-form {
    flex: 1;
    // margin-top: 20px;
    height: 100%;
    min-height: 430px;
    overflow-y: auto;
    background: #fff;
    box-sizing: border-box;
    padding: 8px;

    .form-item {
      margin-bottom: 10px;
    }

    .item-left {
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #333333;
      // margin-bottom: 12px;
      width: 100px;
      text-align: right;
      justify-content: flex-end;

      span {
        color: #ff3a3a;
      }
    }

    .item-left1 {
      width: 100px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #333333;
      text-align: right;
      justify-content: flex-end;

      span {
        color: #ff3a3a;
      }
    }

    .item-right {
      flex: 1;
      margin-left: 10px;
    }

    .item-shexiang {
      margin-bottom: 10px;

      .item-shexiang-l {
        width: 70px;
        font-size: 14px;
        text-align: right;
      }

      .item-shexiang-r {
        flex: 1;
        margin-left: 10px;
      }
    }
  }

  .submit {
    width: 101px;
    height: 46px;
    background: #5386f6;
    border-radius: 4px;
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #ffffff;
    cursor: pointer;
  }
}

.item-right::v-deep .el-select {
  width: 100%;
}

.avatar-uploader::v-deep .el-upload {
  width: 88px;
  height: 88px;
  border: 1px solid #d8d8d8;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.icon {
  width: 34px;
}

.text {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #b1b1b1;
  margin-top: 11px;
}

.avatar-uploader::v-deep .el-upload:hover {
  border-color: #5386f6;
}

.img-body {
  width: 66px;
  height: 66px;
  margin-right: 20px;
  position: relative;
  // margin-left: 10px;

  .show-img {
    width: 100%;
    height: 100%;
  }

  .close-img {
    width: 20px;
    position: absolute;
    top: -10px;
    right: -10px;
  }
}

.item-right ::v-deep .el-cascader {
  width: 100%;
}

.item-right::v-deep .el-checkbox {
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>
.priview-body {
  height: 700px;
  overflow: auto;
}

.emr ::v-deep .el-dialog {
  margin: 0 auto;
  height: 90vh;
  overflow: auto;
}

.emr ::v-deep .el-dialog__header {
  padding: 10px;
}

.emr ::v-deep .el-dialog__body {
  padding: 10px 10px;

  height: 90%;
  overflow: auto;
  box-sizing: border-box;
}
</style>
<style lang="scss" scoped>
@media screen and(min-width: 1681px) and(max-width: 1920px) {
  .emr-main-body {
    height: 84vh;
  }
}

@media screen and(min-width: 1601px) and(max-width: 1680px) {
  .emr-main-body {
    height: 83vh;
  }
}

@media screen and(min-width: 1440px) and(max-width: 1600px) {
  .emr-main-body {
    height: 80vh;
  }
}

@media screen and(min-width: 1360px) and(max-width: 1439px) {
  .emr-main-body {
    height: 76vh;
  }
}
</style>
<style lang="scss" scoped>
.ai-dialog-wrapper {
  ::v-deep {
    .el-dialog, .el-dialog__body {
      height: auto;
      overflow: hidden;
    }
    .el-dialog__body {
      max-height: 50vh;
    }
  }
  .el-textarea, ::v-deep textarea {
    max-height: 45vh;
  }
  ::v-deep textarea {
    padding-bottom: 24px;
  }
}

</style>