<template>
  <div class="dialecticalq">
    <div class="flex flex-row-left flex-col-top top-questions">
      <div class="dialectical-left" v-if="!isShrink">
        <!-- 标题信息 -->
        <div class="pre-title">
          <div class="flex-vertical-center-l title-container">
            <span></span>
            <div>患者信息</div>
          </div>
        </div>
        <div class="patiens-msg" v-if="Object.keys(patiensMsg).length>0">
          <p v-if="patiensMsg.sex">患者性别：{{patiensMsg.sex}}</p>
          <p v-if="patiensMsg.age">患者年龄：{{patiensMsg.age}}</p>
          <p
              v-if="patiensMsg.isGravidity && patiensMsg.isGravidity=='2'"
          >是否怀孕：{{patiensMsg.isGravidity=='1'?'否':patiensMsg.isGravidity=='2'?'是':'无'}}</p>
          <p
              v-if="patiensMsg.isBreastFeeding && patiensMsg.isBreastFeeding==1"
          >是否哺乳：{{patiensMsg.isBreastFeeding==1?'是':patiensMsg.isBreastFeeding==2?'否':'无'}}</p>
        </div>
        <div class="pre-title mr-t10">
          <div class="flex-vertical-center-l title-container">
            <span></span>
            <div>中医电子病历</div>
          </div>
        </div>
        <div class="patiens-msg" v-if="patiensMsg.outpatientElectronicmedicalrecord">
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint">
            <span>主诉：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint}}
          </p>
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.historypresent">
            <span>现病史：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.historypresent}}
          </p>
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.pasthistory">
            <span>既往史：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.pasthistory}}
          </p>
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.fourmedicine">
            <span>中医四诊：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.fourmedicine}}
          </p>
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.physicalexamination">
            <span>体格检查：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.physicalexamination}}
          </p>
          <p v-if="patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination">
            <span>辅助检查：</span>
            {{patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination}}
          </p>
          <div v-if="patiensMsg.outpatientElectronicmedicalrecord.image1.length>0">
            <div style="margin: 4px 0 8px;">报告上传：</div>
            <el-image
                :preview-src-list="patiensMsg.outpatientElectronicmedicalrecord.image1"
                :src="item"
                :key="index"
                style="width:64px;height: 64px;margin-right: 10px;"
                alt
                v-for="(item,index) in patiensMsg.outpatientElectronicmedicalrecord.image1"
            />
          </div>
        </div>
      </div>
      <div class="dialectical-center">
        <div class="now-title">
          <!-- 扩展icon -->
          <div class="kz-icon" @click="setShrink">
            <i class="el-icon-d-arrow-right" v-if="!isShrink"></i>
            <i class="el-icon-d-arrow-left" v-if="isShrink"></i>
          </div>
          当前疾病：
          <span>{{info.groupname}}</span>
        </div>
        <div class="continue-time flex-vertical-center-l">
          <div class="time-left">
            <span>*</span>
            【{{info.groupname}}】持续时间
          </div>
          <div class="time-right flex-vertical-center-l">
            <div class="time-input">
              <el-input size="mini" v-model="year" placeholder></el-input>
            </div>
            <span>年</span>
            <div class="time-input">
              <el-input size="mini" v-model="month" placeholder></el-input>
            </div>
            <span>月</span>
            <div class="time-input">
              <el-input size="mini" v-model="day" placeholder></el-input>
            </div>
            <span>天</span>
            <div class="time-input">
              <el-input size="mini" v-model="hour" placeholder></el-input>
            </div>
            <span>小时</span>
          </div>
        </div>
        <!-- 问题列表 -->
        <div class="question-list">
          <div class="question-item" v-for="(item,index) in info.asks" :key="index">
            <div class="question-name">
              <!-- <span class="time-left1">*</span> -->
              {{index+1}}.{{item.askname}}
            </div>
            <div class="question-answer flex-vertical-center-l">
              <!-- <el-checkbox-group v-model="form.checkList"> -->
              <div class="flex-wrap flex-vertical-center-l">
                <div
                  v-for="item1 in item.answers"
                  :key="item1.answerseqn"
                  class="question-answer-item"
                >
                  <el-checkbox
                    @change="answerClick(item1,item)"
                    v-model="item1.checked"
                    :label="item1.answername"
                  ></el-checkbox>
                  <el-popover placement="top-start" trigger="click" width="250">
                    <img
                      src="../../assets/new-icon/wenhao.png"
                      slot="reference"
                      class="msg"
                      v-if="item1.pulseInfos || item1.tongueInfos"
                    />
                    <div class="popover">
                      <!-- 舌相 -->
                      <template v-if="item1.tongueInfos">
                        <div
                          class="popover-body"
                          v-for="(item2,index2) in item1.tongueInfos"
                          :key="index2"
                        >
                          <div class="popover-title">{{ item2.tongue_NAME }}</div>
                          <el-image
                            class="popover-img"
                            :src="item2.image_URL"
                            :preview-src-list="[item2.image_URL]"
                          ></el-image>
                          <div class="popover-content">
                            <div class="name">舌象特征:</div>
                            <div class="values">{{ item2.tongue_FEATURES }}</div>
                          </div>
                          <div class="popover-content">
                            <div class="name">临床意义:</div>
                            <div class="values">{{ item2.signality }}</div>
                          </div>
                        </div>
                      </template>
                      <!--脉相 -->
                      <template v-if="item1.pulseInfos">
                        <div
                          class="popover-body"
                          v-for="(item2,index2) in item1.pulseInfos"
                          :key="index2"
                        >
                          <div class="popover-title">{{ item2.pulse_NAME }}</div>
                          <el-image
                            class="popover-img"
                            :src="item2.image_URL"
                            :preview-src-list="[item2.image_URL]"
                          ></el-image>
                          <div class="popover-content">
                            <div class="name">脉象特征:</div>
                            <div class="values">{{ item2.pulse_FEATURE }}</div>
                          </div>
                          <div class="popover-content">
                            <div class="name">临床意义:</div>
                            <div class="values">{{ item2.signality }}</div>
                          </div>
                        </div>
                      </template>
                    </div>
                  </el-popover>
                </div>
              </div>

              <!-- </el-checkbox-group> -->
            </div>
          </div>

          <div class="question-item flex-vertical-center-l">
            <span>其他：</span>
            <div class="input">
              <el-input v-model="other" placeholder="请输入"></el-input>
            </div>
          </div>
        </div>
      </div>
      <div class="dialectical-right">
        <div class="title flex-vertical-center-l">
          <span></span>
          <div>症状采集</div>
        </div>
        <div class="list mr-t20 flex-vertical-between flex-wrap">
          <div class="item flex-center" v-for="(item,index) in form.checkList" :key="index">
            <div class="ellipsis-line2">{{item.answername}}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="mr-t20 bottom-btn">
      <el-button type="warning" @click="backPage" size="small">返回</el-button>
      <el-button type="primary" @click="submit" size="small" v-if="pageType!=3">推导</el-button>
      <el-button type="primary" @click="submit" size="small" v-if="pageType==3">自动生成病历</el-button>
    </div>

    <Emr ref="emr" v-if="hack__show_EMR" style="display: none"></Emr>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { getDialecticalq, submitDialetQ } from "@/api/knowledge.js";
import {
  getPatiensBasisM,
  addDiagnosisData,
  znQuestionSave,
  znQusetionShow
} from "@/api/diagnosis.js";
import { addRecipeFrom } from "@/api/dataAnalysis.js";
import { setTimeout } from "timers";
import Emr from "@/views/diagnosis/Emr.vue";
import {formatPicture} from "@/utils/picture";
export default {
  components: {Emr},
  data() {
    return {
      hack__show_EMR: false,
      isShrink: false, // 是否是收缩状态
      patiensMsg: {}, // 患者信息
      year: "",
      month: "",
      day: "",
      hour: "",
      other: "",
      form: {
        checkList: [],
        checkList1: []
      },
      info: {},
      isEdit: false, // 是否编辑,
      pageType: 1
    };
  },
  watch: {
    year() {
      this.isEdit = true;
    },
    month() {
      this.isEdit = true;
    },
    day() {
      this.isEdit = true;
    },
    hour() {
      this.isEdit = true;
    },
    form: {
      deep: true,
      handler: function() {
        this.isEdit = true;
      }
    }
  },
  created() {
    this.pageType = this.$route.query.type;
    this.loaded();
    if (this.getPatiensInfo.pid) this.getPatiensBasisM();
  },
  mounted() {
    this.isShrink = window.sessionStorage.getItem('dia_isShrink') == 1
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      this.$confirm("当前操作尚未保存,是否保存", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "不保存",
        type: "warning"
      })
        .then(() => {
          this._znQuestionSave(next);
        })
        .catch(() => {
          next();
        });
    } else {
      next();
    }
  },
  methods: {
    async loaded() {
      await this.getDialecticalq();
      if (+this.pageType === 2) await this._znQusetionShow();
    },
    // 设置收缩模式
    setShrink() {
      this.isShrink = !this.isShrink
      window.sessionStorage.setItem('dia_isShrink', this.isShrink ? 1 : 0)
    },
    // 获取病人 左侧信息
    async getPatiensBasisM() {
      let res = await getPatiensBasisM({
        patientId: this.getPatiensInfo.pid
      });
      if (res.ResultCode == 0) {
        this.agree_key1 = res.Data.maindiagnosis
          ? res.Data.maindiagnosis.namemedicine
            ? res.Data.maindiagnosis.namemedicine
            : ""
          : "";
        res.Data.secondarydiagnosis = res.Data.secondarydiagnosis
          ? res.Data.secondarydiagnosis
          : [];
        this.patiensMsg = res.Data;

        this.patiensMsg.outpatientElectronicmedicalrecord.image1 = formatPicture(this.patiensMsg.outpatientElectronicmedicalrecord.image1);
      }
    },
    // 返回
    backPage() {
      // this.$router.go(-1)
      this.$router.replace("/index/dialectical");
    },
    //
    submit() {
      if (
        this.year == "" &&
        this.month == "" &&
        this.day == "" &&
        this.hour == ""
      ) {
        this.$message({
          message: "病状持续时间不能为空",
          showClose: true,
          type: "error"
        });
        return;
      }
      // if (this.month == '') {
      //     this.$message({
      //         message: '月份不能为空',
      //         showClose: true,
      //         type: 'error'
      //     })
      //     return
      // }
      // if (this.day == '') {
      //     this.$message({
      //         message: '日不能为空',
      //         showClose: true,
      //         type: 'error'
      //     })
      //     return
      // }
      // if (this.hour == '') {
      //     this.$message({
      //         message: '小时不能为空',
      //         showClose: true,
      //         type: 'error'
      //     })
      //     return
      // }
      if (this.form.checkList1.length == 0) {
        this.$message({
          message: "请至少填写一条问题",
          showClose: true,
          type: "error"
        });
        return;
      }

      this.submitDialetQ();
    },
    // 问卷答案选择
    answerClick(item, fitem) {
      let arr = [];
      let arr1 = [];

      try {
        this.info.asks.forEach(item1 => {
          item1.answers.forEach(item2 => {
            if (item2.checked) {
              arr.push(item2);
              arr1.push(item1.askname);
            }
          });
        });
      } catch (e) {}
      let set = new Set(arr1);

      let arr2 = Array.from(set);

      // return
      this.form.checkList = arr;
      this.form.checkList1 = arr2;
    },
    // 获取问卷
    async getDialecticalq() {
      let res = await getDialecticalq({
        groupid: this.$route.query.id,
        // groupid: 35,
        asktype: 1
      });
      if (res.ResultCode == 0) {
        res.Data.asks.forEach(item => {
          item.answers.forEach(item1 => {
            item1.checked = false;
          });
        });
        if (!res.Data.groupname) res.Data.groupname = this.$route.query.name;
        this.info = res.Data;
      }
    },
    // 提交问卷
    async submitDialetQ() {
      let ids = [];
      this.form.checkList.forEach(item => {
        ids.push(item.answered);
      });
      let duration = "";
      if (this.year) {
        duration = duration + this.year + "年";
      }
      if (this.month) {
        duration = duration + this.month + "月";
      }

      if (this.day) {
        duration = duration + this.day + "天";
      }

      if (this.hour) {
        duration = duration + this.hour + "小时";
      }

      let params = {
        groupid: this.info.groupid,
        groupname: this.info.groupname,
        itemids: ids.join(","),
        duration,
        tcmElectronicMedicalRecordId: this.getPatiensInfo.pid,
        other: this.other
      };
      const loading = this.$loading({
        lock: true,
        text: this.pageType == 3 ? "正在保存" : "正在推导",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await submitDialetQ(params).catch(err => {});
      if (res && res.ResultCode == 0) {
        this.addRecipeFrom();
        if (this.pageType != 3) {
          await this.hackLoadEMR();
          this.addDiagnosisData(res.Data, loading);
          this._znQuestionSave(null);
        } else {
          this.isEdit = false;
          loading.close();
          setTimeout(() => {
            this.$router.push({
              path: "/index/emr"
              // path: '/index/diagnosis'
            });
          }, 1000);
          return;
        }
      }
      loading.close();
    },
    // 提交中医诊断
    async addDiagnosisData(obj, loading) {
      let params = {
        mainDiagnosis: {
          maindiagnosis: "0",
          disCode: obj.disCode,
          symptomCode: obj.synSymCode,
          therapyCode: obj.therapyCode,
          disid: obj.disId,
          symptomid: obj.synSymCode || obj.symId,
          treatment: obj.threapy,
          recordsid: this.getPatiensInfo.pid,
          namemedicine: obj.disname,
          syndrometypes: obj.symName
        }
      };
      let res = await addDiagnosisData(params).catch(err => {
        loading.close();
      });

      if (res.ResultCode == 0) {
        loading.close();
        this.$message.success("提交成功");
        this.isEdit = false;
        if (this.pageType == 3) {
          setTimeout(() => {
            this.$router.push({
              path: "/index/emr"
              // path: '/index/diagnosis'
            });
          }, 3000);
          return;
        }
        setTimeout(() => {
          this.$router.push({
            path: "/index/prescribing?type=tuidao"
            // path: '/index/diagnosis'
          });
        }, 3000);
      } else {
        loading.close();
        this.$message.error(res.ResultInfo);
      }
    },
    // 添加 处方来源
    async addRecipeFrom() {
      let res = await addRecipeFrom({
        type: "0"
      });
    },
    // 问卷临时存储
    async _znQuestionSave(next) {
      let ids = [];
      this.form.checkList.forEach(item => {
        ids.push(item.answered);
      });

      let params = {
        recordId: this.getPatiensInfo.pid,
        itemids: ids.join(","),
        groupids: this.info.groupid,
        year: this.year,
        month: this.month,
        day: this.day,
        hour: this.hour
      };

      let res = await znQuestionSave(params);

      if (res.ResultCode == 0) {
        this.isEdit = false;
        if (next) {
          next();
        }
      } else {
        if (next) {
          next();
        }
      }
    },
    // 获取回显数据
    async _znQusetionShow() {
      let res = await znQusetionShow({
        recordId: this.getPatiensInfo.pid
      }).catch(errr => {});
      if (res.ResultCode == 0) {
        this.year = res.Data.year;
        this.month = res.Data.month;
        this.day = res.Data.day;
        this.hour = res.Data.hour;

        // this.form.checkList1 = res.Data.itemids.split(',')
        let ids = res.Data.itemids.split(",");
        try {
          this.info.asks.forEach(item1 => {
            item1.answers.forEach(item2 => {
              if (ids.indexOf(item2.answered) != -1) {
                item2.checked = true;
              }
            });
          });
        } catch (e) { }

        this.answerClick();
        setTimeout(() => {
          this.isEdit = false;
        }, 300);
      } else {
        this.$message.error(res.ResultInfo);
      }
    },

    async hackLoadEMR() {
      this.hack__show_EMR = true;
      const event = (type) => new Promise((resolve) => this.$nextTick(() => {
        this.$refs.emr.$on(type, (payload) => resolve({ref: this.$refs.emr, payload}));
      }))

      let { ref } = await event('hack_loaded');
      ref.isSkip = false;
      ref.submit(null);
      await event('hack_save');
      this.hack__show_EMR = false;
    }
  },
  computed: {
    ...mapGetters(["getPatiensInfo"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.top-questions {
  height: 72vh;
}

.dialecticalq {
  height: 100%;

  .dialectical-center {
    flex: 1;
    height: 100%;
    min-height: 420px;
    overflow-y: auto;
    padding: 10px 10px;
    background: #fff;
    border-radius: 5px;
    box-sizing: border-box;

    .now-title {
      display: flex;
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;
      margin-bottom: 18px;

      span {
        color: #5386f6;
      }
    }

    .continue-time {
      .time-left {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333;

        span {
          color: #ff3a3a;
        }
      }

      .time-right {
        margin-left: 15px;

        .time-input {
          width: 28px;
        }

        span {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;
          margin-left: 7px;
          margin-right: 15px;
        }
      }
    }

    .question-list {
      .question-item {
        margin-top: 22px;

        span {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;
        }

        .input {
          flex: 1;
        }

        .question-name {
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;
          margin-bottom: 20px;

          .time-left1 {
            color: #ff3a3a;
          }
        }

        .question-answer {
          &-item {
            margin-bottom: 10px;
            margin-right: 20px;
            display: flex;
            align-items: center;
          }
          .msg {
            margin-left: 5px;
            width: 18px;
            cursor: pointer;
          }
        }
      }
    }

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

  .kz-icon {
    margin-right: 8px;
  }

  .dialectical-left {
    height: 100%;
    width: 200px;
    padding: 10px 12px;
    background: #fff;
    box-sizing: border-box;
    margin-right: 20px;
    overflow-y: auto;

    .patiens-msg {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;

      h4 {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
        margin-bottom: 5px;
      }

      p {
        span {
          display: inline-block;
          width: 70px;
          text-align: right;
        }

        margin-bottom: 5px;
      }
    }

    .pre-steps {
      .find-more {
        cursor: pointer;

        img {
          width: 12px;
        }

        span {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #ffae45;
          margin-left: 7px;
        }
      }

      .icon {
        width: 22px;
      }

      .step-body:hover {
        background: #d8d8d8;
      }

      .step-name {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        cursor: pointer;
      }
    }

    .pre-title {
      margin-bottom: 10px;

      .title-container {
        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;
        }
      }

      .patiens-msg {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;

        .p {
          margin-bottom: 5px;
          cursor: default;

          .patiens-name {
            color: #5386f6;
            font-weight: bold;
            font-size: 16px;
          }

          .patiens-desc {
            display: inline-block;

            .matname {
              color: #5386f6;
            }
          }

          .patiens-cate {
            font-weight: bold;
          }
        }
      }
    }
  }

  .dialectical-right {
    height: 100%;
    min-height: 420px;
    width: 230px;
    box-sizing: border-box;
    padding: 29px 10px;
    background: #ffffff;
    border-radius: 5px;
    margin-left: 20px;
    overflow: auto;

    .title {
      span {
        width: 3px;
        height: 14px;
        background: #5386f6;
        border-radius: 1px;
        margin-right: 5px;
      }

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

    .list {
      .item {
        width: 92px;
        height: 46px;

        background: #f5f5f5;
        border-radius: 4px;
        // font-size: 16px;
        font-size: 14px;

        font-weight: 400;
        color: #333333;
        box-sizing: border-box;
        padding: 8px 10px;
        cursor: pointer;
        margin-bottom: 10px;
        background: url("../../assets/bg-kuang.png") no-repeat;
        background-position: center;
        background-size: 100% 100%;

        div {
          text-align: center;
        }
      }
    }
  }
}

.popover {
  max-height: 200px;
  overflow: auto;

  &-title {
    font-size: 14px;
    text-align: center;
  }

  .popover-img {
    max-width: 100%;
    width: auto;
    display: block;
    margin: 5px auto;
  }

  &-content {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    .name {
      font-weight: 600;
      width: 70px;
    }

    .values {
      flex: 1;
    }
  }
}

.bottom-btn {
  background: #fff;
  padding: 10px;
  margin-top: 10px;
}

.time-input::v-deep .el-input__inner {
  padding: 0 0;
  text-align: center;
}
</style>
<style lang="scss" scoped>
@media screen and(min-width: 1681px) and(max-width: 1920px) {
  .top-questions {
    height: 82vh;
  }
}

@media screen and(min-width: 1601px) and(max-width: 1680px) {
  .top-questions {
    height: 82vh;
  }
}

@media screen and(min-width: 1440px) and(max-width: 1600px) {
  .top-questions {
    height: 78vh;
  }
}

@media screen and(min-width: 1360px) and(max-width: 1439px) {
  .top-questions {
    height: 74vh;
  }
}
</style>