<template>
  <div class="emr">
    <div class="header flex flex-col-center flex-row-center">
      <span>通用模板</span>
      <div class="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"
            v-for="(item1,index1) in item.temList"
            :key="index1"
          >{{item1.name}}</div>
        </div>
      </div>
      <div class="emr-form">
        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span>*</span>
            <div>主诉：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入主诉" v-model="form.zhusu"></el-input>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>现病史：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入现病史" v-model="form.xian"></el-input>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>既往史：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入既往史" v-model="form.jiwang"></el-input>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>中医四诊：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入中医四诊" v-model="form.four"></el-input>
          </div>
        </div>

        <div class="form-item flex flex-row-left flex-col-top">
          <div class="item-left1 flex-vertical-center-l">
            <span></span>
            <div>舌象：</div>
          </div>
          <div class="item-right">
            <!-- <el-cascader :options="shexiangList" v-model="form.shexiang" :props="props" clearable
                            @change='shexiangChange'>
            </el-cascader>-->
            <div
              class="flex flex-col-top flex-row-left item-shexiang"
              v-for="(item,index) in shexiangList"
              :key="index"
            >
              <div class="item-shexiang-l">{{item.content}}：</div>
              <div class="item-shexiang-r">
                <!-- <el-checkbox-group v-model="form.shexiang" @change="shexiangChange"> -->
                <el-checkbox
                  @change="shexiangChange(index,index1)"
                  :label="item1.content"
                  v-model="item1.isChecked"
                  v-for="(item1,index1) in item.chlidren"
                  :key="index1"
                ></el-checkbox>
                <!-- </el-checkbox-group> -->
              </div>
            </div>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-top">
          <div class="item-left1 flex-vertical-center-l">
            <span></span>
            <div>脉象：</div>
          </div>
          <div class="item-right">
            <!-- <el-select v-model="form.maixiang" placeholder="请选择" multiple @change="maixiangChange">
                            <el-option :label="item.content" :value="item.id" v-for="(item,index) in maixiangList"
                                :key="index"></el-option>
            </el-select>-->
            <!-- <el-checkbox-group v-model="form.maixiang"> -->
            <el-checkbox
              :label="item1.content"
              v-model="item1.isChecked"
              @change="maixiangChange(index1)"
              v-for="(item1,index1) in maixiangList"
              :key="index1"
            ></el-checkbox>
            <!-- </el-checkbox-group> -->
          </div>
        </div>

        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>体格检查：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入体格检查" v-model="form.tige"></el-input>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-center">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>辅助检查：</div>
          </div>
          <div class="item-right">
            <el-input size="small" placeholder="请输入辅助检查" v-model="form.fuzhu"></el-input>
          </div>
        </div>
        <div class="form-item flex flex-row-left flex-col-top flex-wrap mr-t20">
          <div class="item-left flex-vertical-center-l">
            <span></span>
            <div>报告上传：</div>
          </div>
          <div class="item-right flex flex-col-top flex-row-left flex-wrap">
            <div class="img-body" v-for="(item,index) in form.imageUrls" :key="index">
              <!-- <img :src="item.imageUrl" alt="" class="show-img" @click="priviewImg(item.imageUrl)"> -->
              <el-image
                style="width: 66px; height: 66px"
                :src="item"
                :preview-src-list="form.imageUrls"
              ></el-image>
              <img src="../../assets/close-img.png" class="close-img" alt @click="deleteImg(index)" />
            </div>
            <uploadFile
              ref="upload"
              width="66px"
              height="66px"
              iconWidth="34px"
              @fileChange="upload"
            ></uploadFile>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getPulseSelect, getTongueSelect } from "@/api/knowledge.js";
import { addEMR, getEmrShowMsg, editEMR } from "@/api/diagnosis.js";
import { fileUpload } from "@/api/upload.js";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import uploadFile from "@/components/UploadFile.vue";
export default {
  components: {
    uploadFile
  },
  data() {
    return {
      isEdit: false, // 是否修改
      props: {
        multiple: true,
        value: "id",
        label: "content",
        children: "chlidren"
      },
      shexiangList: [], // 舌象列表
      maixiangList: [], //脉象列表
      form: {
        zhusu: "",
        maixiang: [],
        shexiang: [],
        xian: "",
        jiwang: "",
        four: "",
        tige: "",
        fuzhu: "",
        // photos: []
        imageUrls: [],
        uploadUrls: []
      },
      imageUrl: "",

      shexiangtext: "",
      maixiangtext: "",
      pid: "",

      templateList: [
        {
          name: "医共体",
          temList: [
            {
              name: "通用基础模板"
            }
          ]
        },
        {
          name: "全院",
          temList: [
            {
              name: "全院模板"
            },
            {
              name: "胃脘痛病模板(专)"
            }
          ]
        },
        {
          name: "全院",
          temList: [
            {
              name: "全院模板"
            },
            {
              name: "胃脘痛病模板(专)"
            }
          ]
        },
        {
          name: "科室",
          temList: [
            {
              name: "内科模板"
            },
            {
              name: "咳嗽病模板(专)"
            }
          ]
        },
        {
          name: "个人",
          temList: [
            {
              name: "个人模板"
            }
          ]
        }
      ]
    };
  },
  created() {
    this.getPulseSelect();
    this.getTongueSelect();

    setTimeout(() => {
      this.getEmrShowMsg();
    }, 500);
  },
  watch: {
    form: {
      deep: true,
      // immediate:true,
      handler: function() {
        this.isEdit = true;
      }
    }
  },

  beforeRouteLeave(to, from, next) {
    if (!this.isEdit) {
      next();
    } else {
      this.$confirm("当前修改内容尚未保存,是否要保存?", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "不保存",
        type: "warning"
      })
        .then(() => {
          this.submit();
        })
        .catch(() => {
          next();
        });
    }
  },
  methods: {
    submit() {
      if (this.form.zhusu == "") {
        this.$message({
          message: "请输入主诉信息",
          showClose: true,
          type: "error"
        });
        return;
      }
      if (this.pid) {
        this.editEMR();
        return;
      }
      this.addEMR();
    },
    maixiangChange1(e) {
      let arr = [];
      e.forEach(item => {
        this.maixiangList.forEach(item1 => {
          if (item1.id == item) {
            arr.push(item1.content);
          }
        });
      });
      this.maixiangtext =
        arr.length > 0 ? "脉象：" + arr.join("，") + "；" : "";
      let text = this.form.four.split("；");

      this.form.four =
        this.shexiangtext + this.maixiangtext + text[text.length - 1];
    },
    maixiangChange(index) {
      // console.log(e, '舌向改变')
      if (this.maixiangList[index].isChecked) {
        this.form.maixiang.push({
          id: this.maixiangList[index].id,
          content: this.maixiangList[index].content
        });
      } else {
        this.form.maixiang.forEach((item, current) => {
          if (item.id == this.maixiangList[index].id) {
            this.form.maixiang.splice(current, 1);
          }
        });
      }
      setTimeout(() => {
        this.form.four = this.dealFour();
      }, 100);
    },
    // 老版本
    shexiangChange1(e) {
      // console.log(e, 'ee');
      // console.log(this.form.shexiang, 's');
      let arr = [];
      e.forEach(item => {
        this.shexiangList.forEach(item1 => {
          item1.chlidren.forEach(item2 => {
            item2.chlidren.forEach(item3 => {
              if (item3.id == item[2]) {
                arr.push(item3.content);
              }
            });
          });
        });
      });

      this.shexiangtext =
        arr.length > 0 ? "舌象：" + arr.join("，") + "；" : "";
      let text = this.form.four.split("；");

      this.form.four =
        this.shexiangtext + this.maixiangtext + text[text.length - 1];
      return;
    },
    shexiangChange(index, index1) {
      // console.log(e, '舌向改变')
      if (this.shexiangList[index].chlidren[index1].isChecked) {
        this.form.shexiang.push({
          id: this.shexiangList[index].chlidren[index1].id,
          content: this.shexiangList[index].chlidren[index1].content
        });
      } else {
        this.form.shexiang.forEach((item, current) => {
          if (item.id == this.shexiangList[index].chlidren[index1].id) {
            this.form.shexiang.splice(current, 1);
          }
        });
      }
      setTimeout(() => {
        this.form.four = this.dealFour();
      }, 100);
    },

    // 处理中医四诊
    dealFour() {
      let four = this.form.four.split("；");
      let content = "";
      let sx = [];
      let mx = [];
      this.form.shexiang.forEach((item, index) => {
        sx.push(item.content);
      });

      this.form.maixiang.forEach((item, index) => {
        mx.push(item.content);
      });
      let sxText = sx.length > 0 ? "舌象：" + sx.join("，") + "；" : "";
      let mxText = mx.length > 0 ? "脉象：" + mx.join("，") + "；" : "";
      content = sxText + mxText + four[four.length - 1];

      return content;
    },
    // 删除当前图片
    deleteImg(index) {
      this.$confirm("确定要删除当前图片吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.form.imageUrls.splice(index, 1);
          this.form.uploadUrls.splice(index, 1);
        })
        .catch(() => {});
    },
    upload(e) {
      let files = e.target.files[0];
      if (this.form.imageUrls.length > 5) {
        this.$message({
          type: "error",
          message: "最多上传五张图片",
          showClose: true
        });
        return;
      }
      if (files.type.indexOf("image") == -1) {
        this.$message({
          type: "error",
          message: "文件格式选择有误",
          showClose: true
        });
        return;
      }

      let formData = new FormData();
      formData.append("file", files);
      this.fileUpload(formData);
    },
    // 获取 脉象
    async getPulseSelect() {
      let res = await getPulseSelect();
      if (res.code == 0) {
        res.data.pulse.forEach(item => {
          item.isChecked = false;
        });
        this.maixiangList = res.data.pulse;
      }
    },
    // 获取舌象
    async getTongueSelect() {
      let res = await getTongueSelect();
      if (res.code == 0) {
        res.data.tongue.forEach(item => {
          item.chlidren.forEach(item1 => {
            item1.isChecked = false;
          });
        });
        this.shexiangList = res.data.tongue;
      }
    },
    //上传 图片
    async fileUpload(data) {
      let res = await fileUpload(data);
      if (res.ResultCode == 0) {
        this.$message({
          type: "success",
          message: "上传成功",
          showClose: true
        });
        // this.form.imageUrls.push(res.url)
        // this.form.uploadUrls.push(res.fileName)

        this.form.imageUrls.push(
          process.env.VUE_APP_UPLOAD + "file/" + res.ResultInfo
        );
        this.form.uploadUrls.push(res.ResultInfo);
        this.$refs.upload.$refs.file.value = null;
      }
    },
    // 提交数据
    async addEMR() {
      let sxIds = [];
      this.form.shexiang.forEach(item => {
        sxIds.push(item.id);
      });

      let mxids = [];
      this.form.maixiang.forEach(item => {
        mxids.push(item.id);
      });

      let params = {
        chiefcomplaint: this.form.zhusu,
        fourmedicine: this.form.four,
        historypresent: this.form.xian,
        pasthistory: this.form.jiwang,
        physicalexamination: this.form.tige,
        supplementaryexamination: this.form.fuzhu,
        image1: this.form.uploadUrls.join(","),
        // 缺少id
        recordsid: this.getPatiensInfo.pid,
        // tongueIds: this.form.shexiang.join(','),
        // tongueIds: JSON.stringify(this.form.shexiang),
        tongueIds: JSON.stringify(sxIds),
        // pluseIds: this.form.maixiang.join(','),
        pluseIds: mxids.join(",")
      };
      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 (res.ResultCode == 0) {
        loading.close();

        this.$message({
          type: "success",
          message: "保存成功",
          showClose: true
        });
        this.isEdit = false;
        setTimeout(() => {
          this.$router.push({
            path: "/index/diagnosis"
          });
        }, 1500);
      }
    },
    // 回显展示
    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.form = {
          zhusu: res.Data[0].chiefcomplaint,
          xian: res.Data[0].historypresent,
          jiwang: res.Data[0].pasthistory,
          four: res.Data[0].fourmedicine,
          tige: res.Data[0].physicalexamination,
          fuzhu: res.Data[0].supplementaryexamination,
          imageUrls: [],
          uploadUrls: [],
          shexiang: [],
          maixiang: []
          // shexiang: res.Data[0].tongueIds ? res.Data[0].tongueIds.split(',') : [],
          // maixiang: res.Data[0].pluseIds ? res.Data[0].pluseIds.split(',') : [],
          // shexiang: res.Data[0].tongueIds ? JSON.parse(res.Data[0].tongueIds) : [],
          // shexiang: res.Data[0].tongueIds ? res.Data[0].tongueIds.split(',') : [],
        };
        // this.shexiangtext = res.Data[0].tongueIds ? res.Data[0].fourmedicine.split('；')[0] + '；' : ''
        // this.maixiangtext = res.Data[0].pluseIds ? res.Data[0].fourmedicine.split('；')[1] + '；' : ""
        this.pid = res.Data[0].pid;
        let xsIDS = res.Data[0].tongueIds
          ? JSON.parse(res.Data[0].tongueIds)
          : [];
        let mxIDS = res.Data[0].pluseIds ? res.Data[0].pluseIds.split(",") : [];

        this.shexiangList.forEach(item => {
          item.chlidren.forEach(item1 => {
            if (xsIDS.indexOf(item1.id) != -1) {
              item1.isChecked = true;
              _self.form.shexiang.push({
                content: item1.content,
                id: item1.id
              });
            }
          });
        });

        this.maixiangList.forEach(item => {
          if (mxIDS.indexOf(item.id) != -1) {
            item.isChecked = true;
            this.form.maixiang.push({
              content: item.content,
              id: item.id
            });
          }
        });

        this.form.four = this.dealFour();
        setTimeout(() => {
          this.isEdit = false;
        }, 100);

        if (res.Data[0].image1 == "") return;
        res.Data[0].image1 = res.Data[0].image1.split(",");

        res.Data[0].image1.forEach(item => {
          this.form.imageUrls.push(process.env.VUE_APP_UPLOAD + "file/" + item);
          this.form.uploadUrls.push(item);
        });
      }
    },
    // 修改 中医电子病历
    async editEMR() {
      let sxIds = [];
      this.form.shexiang.forEach(item => {
        sxIds.push(item.id);
      });

      let mxids = [];
      this.form.maixiang.forEach(item => {
        mxids.push(item.id);
      });
      let params = {
        chiefcomplaint: this.form.zhusu,
        fourmedicine: this.form.four,
        historypresent: this.form.xian,
        pasthistory: this.form.jiwang,
        physicalexamination: this.form.tige,
        supplementaryexamination: this.form.fuzhu,
        image1: this.form.uploadUrls.join(","),
        // 缺少id
        recordsid: this.getPatiensInfo.pid,
        pid: this.pid,
        // tongueIds: this.form.shexiang.join(','),
        // tongueIds: JSON.stringify(this.form.shexiang),
        tongueIds: JSON.stringify(sxIds),
        // pluseIds: this.form.maixiang.join(','),
        pluseIds: mxids.join(",")
      };
      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 (res.ResultCode == 0) {
        loading.close();

        this.$message({
          type: "success",
          message: "保存成功",
          showClose: true,
          duration: 1000
        });
        this.isEdit = false;
        this.$router.push({
          path: "/index/diagnosis"
        });
        // setTimeout(() => {

        // }, 2000);
      }
    }
  },

  computed: {
    ...mapGetters(["getPatiensInfo"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.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>
@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>