<template>
  <div class="questionResult">
    <div class="header flex flex-row-between flex-col-center">
      <div>
        <el-button type="warning" size="mini" @click="$router.back()">返回</el-button>
      </div>
      <div class="header-title">个性化调体方案</div>
      <div>
        <el-button type="primary" size="mini" @click="_submitDoctorGy" v-if="type=='edit'">保存</el-button>
        <div v-if="type=='find'">
          <!-- v-print="'#printTest'" -->
          <el-button v-if="showPrint" type="warning" size="mini" @click="printTest">打印</el-button>
        </div>
      </div>
    </div>
    <div class="footer flex flex-col-top flex-row-left" id="printTest">
      <div class="left">
        <div class="left-top">
          <div class="echarts-top flex-vertical-center-l">
            <span>体质得分</span>
          </div>
          <div class="echarts-body flex-plane-center-l">
            <div id="echarts" style="width:100%;height:100%;"></div>
          </div>
        </div>
        <div class="left-top">
          <div class="echarts-top flex-vertical-center-l">
            <span>体质辨识结果</span>
          </div>
          <div class="echarts-result">
            <span
              v-for="(item,index) in e_result"
              :key="index"
            >{{item.name}}{{index==e_result.length-1?'':'、'}}</span>
          </div>
        </div>

        <div class="left-top" style="margin-top:20px;">
          <div class="echarts-top flex-vertical-center-l">
            <span>体质介绍</span>
          </div>
          <div class="left-bottom flex-plane-center-top flex-column">
            <div v-for="(item,index) in e_result" :key="index" class="flex-plane-center-l">
              <span style="width:80px">{{item.name}}:</span>
              <span style="flex:1;">{{item.description}}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="right" v-if="e_titles.length>0">
        <div class="right-top flex-plane-center-top flex-column">
          <!-- {{item.title}}:{{item.desc}} -->
          <!-- <div v-for="(item,index) in e_types" :key="index" class="flex-plane-center-l ">
                        <span style='width:80px;'>{{item.title}}:</span><span style="flex:1;">{{item.desc}}</span>
          </div>-->
          <div class="flex flex-row-left flex-col-top">
            <span>体质类型：</span>
            <div class="input" style="width:200px;flex: none;">
              <el-select
                :disabled="type=='find'"
                placeholder="请选择"
                v-model="e_id"
                @change="handleChange"
              >
                <el-option
                  :label="item.name"
                  v-for="(item,index) in e_titles"
                  :value="item.pid"
                  :key="index"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>调体法则：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].tt_RULE"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>调体要点：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].tt_POINT"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>调体方药：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].tt_PRESCRIPTION"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>情志调摄：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].emotional_ADJUSTMENT"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>饮食调养：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].diet_RECUPERATION"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>起居调摄：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].daily_LIFE_ADJUSTMENT"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>运动保健：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].sports"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>穴位保健：</span>
            <div class="input">
              <!--  -->
              <el-select
                v-if="type=='edit'"
                filterable
                placeholder="选择穴位(可多选)"
                multiple
                v-model="acupointIds"
                @change="acupointChange"
              >
                <el-option
                  v-for="(item,index) in xueweiList"
                  :key="index"
                  :label="item.acuname"
                  :value="item.acuid"
                ></el-option>
              </el-select>
              <div v-else class="point flex flex-row-left flex-col-center">
                <div
                  @click="openViewer(item)"
                  class="point-item"
                  v-for="(item,index) in acupointNames"
                  :key="index"
                >{{item.pointName || item.acuname }}</div>
              </div>
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].acupoint_HEALTH_CARE"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>养生建议：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].vegetables"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>推荐药膳：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].medicated_DIET"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>推荐花茶：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].flower_TEA"
              ></el-input>
            </div>
          </div>
          <div class="flex-plane-center-top">
            <span>其他：</span>
            <div class="input">
              <el-input
                :disabled="type=='find'"
                :autosize="{ minRows: 1, maxRows: 100}"
                size="mini"
                type="textarea"
                placeholder="请输入内容"
                v-model="e_titles[e_index].ysjy"
              ></el-input>
            </div>
          </div>
        </div>
        <!-- <div class='flex-plane-center-l'>
                    <div class="submit flex-center" @click="submitDoctorjy">提交</div>
                    <div class="submit1 flex-center" v-print="'#printTest'">打印</div>
        </div>-->
        <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="[pointUrl]" />
      </div>
    </div>
  </div>
</template>
<script>
import {
  getPhysicalDetail,
  submitDoctorjy,
  submitDoctorGy,
  getPhysicalDetailGy,
  createPdf,
  findIsHealthGY
} from "@/api/diagnosis.js";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { fileUpload } from "@/api/upload.js";
import { getAcupoint } from "@/api/knowledge.js";
export default {
  components: {},
  data() {
    return {
      showReport: true,
      textarea: "",
      e_result: [],
      e_titles: [],
      e_values: [],

      e_index: 0,
      e_id: "",
      type: "find",
      myCanvas: null,
      uploadImg: null,
      xueweiList: [],
      acupointIds: [],
      acupointNames: [],
      showPrint: false, // 显示打印按钮
      showViewer: false, // 显示预览
      pointUrl: "",
      loading: null
    };
  },
  components: {
    ElImageViewer
  },
  mounted() {
    if (this.$route.query.type) {
      this.type = this.$route.query.type;
    }

    this._findIsHealthGY();
    this._getAcupoint();

    // this.getPhysicalDetail();
    // setTimeout(() => {
    //   this._getPhysicalDetailGy()
    // }, 50)
  },
  methods: {
    acupointChange(e) {
      this.acupointNames = [];
      this.xueweiList.forEach(item => {
        this.acupointIds.forEach(item1 => {
          if (item.acuid == item1) {
            this.acupointNames.push(item);
          }
        });
      });
    },
    openViewer(item) {
      let url = item.acuimg || item.image;
      this.pointUrl = process.env.VUE_APP_XUEWEI + url;
      this.showViewer = true;
    },
    closeViewer() {
      this.showViewer = false;
      this.pointUrl = "";
    },
    // 打印
    printTest() {
      this._createPdf();
    },
    // 体质得分
    _initCharts(data) {
      let charts = this.$echarts.init(document.getElementById("echarts"));
      let names = [];
      let values = [];
      data.forEach(item => {
        names.push(item.name);
        values.push(item.score);
      });
      let option = {
        color: ["#5386F6"],
        xAxis: {
          type: "category",
          data: names
        },
        grid: {
          top: 20,
          bottom: 20,
          left: "10%",
          right: 10
        },
        // tooltip: {},
        yAxis: {
          min: 0,
          max: 100,
          splitLine: {
            // 隐藏分割线
            show: false
          },
          axisLabel: {
            // 隐藏刻度
            show: false
          },
          axisTick: {
            // 隐藏小刻度线
            show: false
          }
        },

        series: [
          {
            data: values,
            type: "bar",
            zlevel: 9,
            barWidth: 20,
            label: {
              show: true,
              position: "top"
            },
            markLine: {
              silent: false,
              // 设置 标线 标题样式
              label: {
                position: "start",
                color: "#333",
                formatter: function(event) {
                  if (event.value == 30) {
                    return "微小30";
                  }

                  if (event.value == 40) {
                    return "轻微40";
                  }

                  if (event.value == 60) {
                    return "明显60";
                  }

                  if (event.value == 100) {
                    return "严重100";
                  }
                }
              },
              symbol: "none",
              // 设置标线样式
              lineStyle: {
                color: "#999",
                type: "solid"
              },
              disabled: {
                disabled: true
              },
              data: [
                {
                  yAxis: 30
                },
                {
                  yAxis: 40
                },
                {
                  yAxis: 60
                },
                {
                  yAxis: 100
                }
              ]
            }
          }
        ]
      };
      charts.setOption(option);
      this.myCanvas = charts;
      setTimeout(() => {
        this.createImg();
      }, 1500);
    },
    // 创建图片
    createImg() {
      var img = new Image();
      img.src = this.myCanvas.getDataURL({
        type: "png",
        pixelRatio: 2, //放大2倍
        backgroundColor: "#fff"
      });
      let _this = this;
      img.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL("image/png"); //base64编码图片

        _this.uploadImg = dataURL;
        // _this.UpBase64Img(dataURL);
      };
    },
    //base64编码图片转换成file对象
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      //转换成file对象
      return new File([u8arr], filename, {
        type: mime
      });
    },
    // 上传文件获取 文件地址
    UpBase64Img(dataurl) {
      let _this = this;
      var filename = "";
      var formData = new FormData();
      formData.append(
        "file",
        _this.dataURLtoFile(dataurl, new Date().getTime() + ".png")
      );
      this.fileUpload(formData);
    },
    // 获取穴位
    async _getAcupoint() {
      let params = {
        merid: "",
        pageid: 1,
        pagesize: 999
      };
      let res = await getAcupoint(params);
      if (res.code == 0) {
        this.xueweiList = res.data.acupoints;
      }
    },
    async fileUpload(data) {
      let res = await fileUpload(data);
      if (res.ResultCode == 0) {
        this.uploadImg = res.ResultInfo;
      }
    },
    // 生成PDF报告
    async _createPdf() {
      let params = {
        base64: this.uploadImg,
        dentificationId: this.$route.query.pid
      };
      let res = await createPdf(params);
      if (res.ResultCode == 0) {
        window.open(res.Data.pdfFilePath);
      }
    },

    // 体值类型改变
    handleChange(e) {
      this.e_titles.forEach((item, index) => {
        if (item.pid == e) {
          this.e_id = e;
          this.e_index = index;
        }
      });
    },
    // 获取详情信息
    async getPhysicalDetail(flag) {
      let res = await getPhysicalDetail({
        identid: this.$route.query.pid
      });
      if (res.ResultCode == 0) {
        this._initCharts(res.Data);
        // 排序分值最高的
        res.Data.sort((a, b) => b.score - a.score);
        this.e_result = res.Data.filter(data => data.type !== '0');
        this.e_id = res.Data[this.e_index].pid;

        if (flag == 1) {
          this._getPhysicalDetailGy(res.Data);
          return;
        }
        this.loading.close();
        this.e_values = res.Data;
        this.e_titles = res.Data;
        // this.e_index = 0

        // this._getPhysicalDetailGy();
      }
    },
    async _getPhysicalDetailGy(list) {
      let res = await getPhysicalDetailGy({
        dentificationId: this.$route.query.pid
      });
      if (res.ResultCode == 0) {
        if (!res.Data) {
          this.showPrint = false;
          return;
        } else {
          this.showPrint = true;
        }
        if (res.Data.acupointVOList) {
          res.Data.acupointVOList.forEach(item => {
            this.acupointIds.push(item.pid);
            this.acupointNames.push(item);
          });
        }
        // res.Data.forEach((item, index) => {
        //   item.width =
        //     Number(item.score) / 25 >= 1 ?
        //     "100%" :
        //     (Number(item.score) / 25) * 100 + "%";
        //   item.other_RMK = "";
        // });
        // this.e_values = res.Data;
        this.e_values = [];
        this.e_values.push(res.Data);
        // this.e_titles = res.Data;
        let dataIndex = 0;
        list.forEach((item, index) => {
          if (item.name == res.Data.physicalType) {
            dataIndex = index;
            item.tt_RULE = res.Data.bodyTuneRule;
            item.name = res.Data.physicalType;
            item.tt_POINT = res.Data.bodyTuningPoints;
            item.tt_PRESCRIPTION = res.Data.bodyConditioningPrescription;
            item.emotional_ADJUSTMENT = res.Data.emotionalPhotoshoot;
            item.diet_RECUPERATION = res.Data.dietRecuperation;
            item.daily_LIFE_ADJUSTMENT = res.Data.dailyLife;
            item.sports = res.Data.sportsHealth;
            item.acupoint_HEALTH_CARE = res.Data.acupointHealthCare;
            item.vegetables = res.Data.healthAdvice;
            item.medicated_DIET = res.Data.recommendedMedicatedDiet;
            item.flower_TEA = res.Data.recommendedScentedTea;
            item.ysjy = res.Data.other;
            // this.acupointIds = res.Data.acupointVOList ? res.Data.split(',') : []
            this.acupointIds = res.Data.acupointVOList;
          }
        });
        this.e_titles = [list[dataIndex]];
        // this._initCharts(res.Data);
        this.e_id = list[dataIndex].pid;
        if (res.Data.length > 0) {
          // this.e_index = 0
        }
        this.loading.close();
      }
    },
    // 查询啊是否健康干预胡俄国
    async _findIsHealthGY() {
      this.loading = this.$loading({
        lock: true,
        text: "正在获取体制辨识结果",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await findIsHealthGY({
        identid: this.$route.query.pid
      });
      if (res.ResultCode == 0) {
        if (res.Data.flag == 1) {
          this.getPhysicalDetail(res.Data.flag);
          // setTimeout(() => {
          //   this._getPhysicalDetailGy()
          // }, 50)
        } else {
          this.getPhysicalDetail();
        }
      }
    },
    // 提交
    async submitDoctorjy() {
      // if (!this.textarea) {
      //     this.$message({
      //         type: 'error',
      //         message: '请输入医生建议',
      //         showClose: true
      //     })
      //     return
      // }
      const loading = this.$loading({
        lock: true,
        text: "正在保存",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await submitDoctorjy({
        pid: this.e_values[0].pid,
        ysjy: this.textarea
      }).catch(err => {
        loading.close();
      });

      if (res.ResultCode == 0) {
        loading.close();
        this.$message({
          type: "success",
          message: "提交成功",
          showClose: true
        });
        setTimeout(() => {
          this.$router.back();
        }, 2000);
      }
    },
    // 保存健康干预
    async _submitDoctorGy() {
      const loading = this.$loading({
        lock: true,
        text: "正在保存",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let params = {
        dentificationId: this.$route.query.pid,
        bodyTuneRule: this.e_titles[this.e_index].tt_RULE,
        physicalType: this.e_titles[this.e_index].name,
        bodyTuningPoints: this.e_titles[this.e_index].tt_POINT,
        bodyConditioningPrescription: this.e_titles[this.e_index]
          .tt_PRESCRIPTION,
        emotionalPhotoshoot: this.e_titles[this.e_index].emotional_ADJUSTMENT,
        dietRecuperation: this.e_titles[this.e_index].diet_RECUPERATION,
        dailyLife: this.e_titles[this.e_index].daily_LIFE_ADJUSTMENT,
        sportsHealth: this.e_titles[this.e_index].sports,
        acupointHealthCare: this.e_titles[this.e_index].acupoint_HEALTH_CARE,
        healthAdvice: this.e_titles[this.e_index].vegetables,
        recommendedMedicatedDiet: this.e_titles[this.e_index].medicated_DIET,
        recommendedScentedTea: this.e_titles[this.e_index].flower_TEA,
        other: this.e_titles[this.e_index].ysjy,
        acupuncturePoint: this.acupointIds.join(",")
      };

      let res = await submitDoctorGy(params).catch(err => {
        loading.close();
      });
      if (res.ResultCode == 0) {
        this.$message.success("提交成功");
        loading.close();
        this.type = "find";
        this.showPrint = true;
      } else {
        this.$message.error(res.ResultInfo);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.questionResult {
  margin-top: 0px;

  .header {
    background: #fff;
    padding: 5px;
    border-radius: 5px;
    margin-bottom: 5px;

    .header-title {
      font-weight: 600;
      color: #000;
      font-size: 16px;
    }
  }

  .footer {
    height: 74vh;
  }

  .left {
    width: 668px;
    margin-right: 10px;
    height: 100%;
    overflow: auto;
    background: #fff;
    padding: 5px 5px 30px;
    box-sizing: border-box;
    border-radius: 5px;

    .left-top {
      margin-bottom: 10px;

      .echarts-top {
        span {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 600;
          color: #333333;
          margin-right: 25px;
        }
      }

      .echarts-result {
        margin-top: 10px;
        // font-size: 14px;
      }

      .echarts-body {
        margin-top: 10px;
        width: 100%;
        height: 270px;
      }
    }

    .left-bottom {
      padding: 0px 0px;
      border-radius: 5px;
      background: #fff;
      margin-top: 20px;

      div {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        margin-bottom: 20px;
      }
    }
  }

  .right {
    flex: 1;
    background: #fff;
    padding: 5px 5px 40px;
    box-sizing: border-box;
    border-radius: 5px;
    height: 100%;
    overflow: auto;

    .right-top {
      div {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        margin-bottom: 10px;
        width: 100%;

        span {
          width: 80px;
          text-align: right;
          font-weight: 600;
          margin-top: 6px;
        }

        .input {
          // width: 300px;
          flex: 1;
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #999999;
          margin-bottom: 0;
        }
      }
    }

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

    .submit1 {
      margin-left: 20px;
      width: 100px;
      height: 46px;
      background: #ffae45;
      border-radius: 4px;
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
      cursor: pointer;
    }
  }
}

.input ::v-deep .el-input {
  width: 100%;
}

.input ::v-deep .el-textarea.is-disabled .el-textarea__inner {
  border-color: #fff;
  background-color: #fff;
  color: #000;
  cursor: default;
}

.input ::v-deep .el-textarea.is-disabled .el-textarea__inner::placeholder {
  color: #fff;
}

.input ::v-deep .is-disabled .el-input__suffix {
  display: none;
}

.input ::v-deep .el-input.is-disabled .el-input__inner {
  border-color: #fff;
  background-color: #fff;
  color: #000;
  cursor: default;
}

.point {
  width: 100%;

  &-item {
    cursor: pointer;
    width: auto !important;
    background: #5386f6;
    padding: 6px 8px;
    font-size: 12px !important;
    color: #fff !important;
    border-radius: 4px;
    // color: ;
    margin-right: 5px;
    margin-bottom: 5px;
  }
}
</style>

<style lang="scss" scoped>
@media screen and (min-width: 1681px) and (max-width: 1920px) {
  .questionResult {
    .footer {
      height: 84vh;
    }
  }
}

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

@media screen and (min-width: 1361px) and (max-width: 1600px) {
  .questionResult {
    .footer {
      height: 76vh;
    }
  }
}

@media screen and(min-width:1281px) and (max-width: 1360px) {
  .questionResult {
    .footer {
      height: 76vh;
    }
  }
}
</style>