<template>
  <div class="main_right_height">
    <div class="smart_content">
      <div style="height: 30px">&nbsp;</div>

      <div class="chat-window" id="contant1" ref="scrollview" style="margin-top: 20px">
        <!-- <div class="chat-window" id="contant1" ref="scrollview" style="margin-top: 20px"> -->
        <div v-if="echoFlag" style="text-align: center">
          <i class="el-icon-loading"></i>
        </div>
        <div
          class="chat-msg-content"
          id="rongqi"
          v-for="(content, index) in chatContents"
          :key="content.index"
        >
          <div
            v-if="content.from == 1"
            :key="content.id"
            class="main_answer_right"
            style="margin-top: 10px; padding-left: 20px"
          >
            <div class="img-wrapper">
              <img width="60px" heigth="60px" class="img" :src="from1" />
            </div>
            <div class="message-wrapper message-wrapper-left">
              <!-- {{ content.question }} -->
              <div class="message" v-html="content.question"></div>
            </div>
          </div>
          <el-row v-else style="margin-top: 10px; padding-right: 20px">
            <el-col :span="10"> &nbsp; </el-col>
            <el-col :span="14" s>
              <div
                class="main_answer_left"
                style="float: right"
                v-show="content.type == 1"
              >
                <div class="message-wrapper message-wrapper-right">
                  <div class="message">{{ content.answer }}</div>
                </div>
                <div class="img-wrapper">
                  <img width="60px" heigth="60px" class="img" :src="from2" />
                </div>
              </div>
              <div
                class="main_answer_left"
                style="float: right"
                v-show="content.type == 3 && index == chatContents.length - 1"
              >
                <div class="smart_mul_form2">
                  <el-checkbox-group v-model="emotionMul" border class="check_column">
                    <el-checkbox
                      border
                      @change="mulItem(item.name)"
                      v-for="item in content.scale_MulItems"
                      :label="item.name"
                      :disabled="item.disable"
                      :key="item.name"
                      >{{ item.name }}</el-checkbox
                    >
                  </el-checkbox-group>
                  &nbsp;&nbsp;<el-button
                    @click="selectionComplete"
                    size="mini"
                    class="smart_mul_button_select"
                    :disabled="emotionMul.length == 0"
                    >确认选择</el-button
                  >
                </div>
                <div class="img-wrapper">
                  <img width="60px" heigth="60px" class="img" :src="from2" />
                </div>
              </div>
              <div
                class="main_answer_left"
                style="float: right"
                v-show="content.type == 2 && index == chatContents.length - 1"
              >
                <div class="smart_mul_form2">
                  <el-radio
                    border
                    class="smart_radio"
                    style="
                      margin-top: 10px;
                      margin-right: 30px;
                      width: 200px;
                      background: #ffffff;
                      margin-left: 0px;
                    "
                    v-for="(item, index) in content.scale_checkItems"
                    :key="index"
                    v-model="radio"
                    :label="item"
                    fill="#57ACBB"
                    @change="selectRadio(item, content.isScale)"
                    >{{ item }}</el-radio
                  >
                </div>
                <div class="img-wrapper">
                  <img width="60px" heigth="60px" class="img" :src="from2" />
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div class="smart_line_class"></div>
      <el-row v-show="inputFlag === 1" class="footSend">
        <!-- <el-col :span="1"> &nbsp; </el-col> -->
        <div style="flex: 1">
          <el-input
            class="xl_input"
            type="textarea"
            resize="none"
            placeholder="请输入内容"
            v-model="desc"
            show-word-limit
            @keyup.enter.native="sendMsg"
            clearable
          >
          </el-input>
        </div>
        <!-- <el-col :span="21">
          
        </el-col> -->
        <div class="send_buttom_style">
          <div style="flex: 1">&nbsp;</div>
          <el-button class="xl_d_send" @click="refreshFun">刷&nbsp;&nbsp;新</el-button>
        </div>
        <div class="send_buttom_style">
          <div style="flex: 1">&nbsp;</div>
          <el-button
            :disabled="desc.length == 0 || buttonFlag"
            class="xl_d_send"
            @click="sendMsg"
            >发&nbsp;&nbsp;送</el-button
          >
        </div>
        <!-- <el-col :span="3" class="send_buttom_style" style="">
          <div style="flex:1"> &nbsp;</div>
          <el-button :disabled="desc.length == 0 || buttonFlag" class="xl_d_send"
            @click="sendMsg">发&nbsp;&nbsp;送</el-button>
        </el-col> -->
      </el-row>
      <el-row v-show="inputFlag === 2" class="footSendSelect">
        <el-col :span="1"> &nbsp; </el-col>
        <el-col :span="22" style="margin-top: 20px; margin-bottom: 20px">
          <div>
            <el-radio
              style="margin-top: 10px"
              v-for="(item, index) in scale_checkItems"
              :key="index"
              v-model="radio"
              :label="item"
              fill="#57ACBB"
              @change="selectRadio(item)"
              >{{ item }}</el-radio
            >
          </div>
        </el-col>
        <el-col :span="1"> &nbsp; </el-col>
      </el-row>
      <el-row v-show="inputFlag === 3" class="footSendSelect">
        <el-col :span="1"> &nbsp; </el-col>
        <el-col :span="22" style="margin-top: 20px; margin-bottom: 20px">
          <div>
            <el-radio
              :disabled="!scaleSelectFlag"
              style="margin-top: 10px"
              v-for="(item, index) in scale_checkItems"
              :key="index"
              v-model="radio"
              :label="item"
              fill="#57ACBB"
              @change="choiceTriger(item)"
              >{{ item }}</el-radio
            >
          </div>
        </el-col>
        <el-col :span="1"> &nbsp; </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import HeadImg from "@/assets/lion.png";
import HeadImg1 from "@/assets/persion.png";
import axios from "axios";
const HTTP_AXIOS = axios.create();
export default {
  data() {
    return {
      identifier: "",
      //用户测试记录
      userName: "",
      //this.scale_checkItems = ["抑郁", "焦虑", "压力", "睡眠问题", "无"];
      emotionMul: [],
      //多选复制体
      emotionMulCopy: [],
      scale_MulItems: [
        { name: "抑郁", disable: false },
        { name: "焦虑", disable: false },
        { name: "应激", disable: false },
        { name: "睡眠问题", disable: false },
        { name: "无", disable: false },
      ],

      buttonFlag: false,
      pageNum: 1,
      pageSize: 10,
      tmpRadio: "",
      radio: "",
      inputFlag: 1,
      desc: "",
      from1: HeadImg,
      from2: HeadImg1,
      chatContents: [],
      //前三个问题
      preList: [],
      questionList: [{ index: 1, des: "能描述一下您最近训练的内容吗？", type: "1-2" }],
      //随机的4个数集合
      radomNumList: [],
      questionNum: 0,

      //随机4个问题的集合
      randomQuestion: [],
      //随机4个答案的集合
      randomAnswer: [],
      //全部题目
      scale_infos: [{ answer: "" }],
      //题目总数
      scale_all: 0,
      scale_checkItems: [],
      //进度参数
      scale_percent: [],
      //
      scale_index: 0,
      // 答案数据
      scale_result: [],

      //检测情绪前的发送数据条数
      threeAnswers: [],

      //负面情绪标志
      moonNegative: 0,
      scale_flag: "",
      pressure_flag: "",
      sendMsgFlag: true,
      scaleSelectFlag: true,

      flagTime: null,
      printIndex: 0,
      //当回显接口正在调用时为true
      echoFlag: false,
      //当前返回历史记录
      currenRecordTotol: 0,
      selectParams: "",
      //压力
      stress: "",
      //压力分
      stressScore: 0,
      //抑郁
      depressed: "",
      depressedScore: 0,
      //焦虑
      anxiety: "",
      anxietyScore: 0,
      //睡眠 的建议
      sleepZD: "",
      suggestion: "",
      ///总得分 焦虑抑郁应激总的分
      scoreJYY: 0,
      sleepScore: 0,
    };
  },
  created() {},

  mounted() {
    window.jumpPage = this.jumpPage;
    const scrollview = this.$refs["scrollview"];
    this.$root.smartNum = this.$root.smartNum + 1;
    this.init();
    //获取编号
    this.identifier = sessionStorage.getItem("num");
    this.userName = sessionStorage.getItem("name");
    // this.selectScale("20220805135201");
    scrollview.addEventListener("scroll", this.handleScroll, true);

    this.judgeModel();
    // /menu/evaluation
    // this.askEndMul(
    //   '	轻度：建议您使用系统中的虚拟现实、生物反馈训练<span onclick="jumpPage(1)" style="color:blue;cursor:pointer">（点击跳转）</span>、认知行为干预<span  onclick="jumpPage(2)" style="color:blue;cursor:pointer">（点击跳转--走出抑郁）</span>功能进行心理状态调'
    // );
  },
  beforeDestroy() {
    let that = this;
    const scrollview = this.$refs["scrollview"];
    scrollview.removeEventListener("scroll", that.handleScroll);
  },
  methods: {
    refreshFun() {
      console.log("1111111111");
      //重置聊天对话
      //将记录清空然后开始调用查询的返回的接口
      this.chatContents = [];
      this.moonNegative = 0;
      this.pageNum = 1;
      this.pageSize = 10;
      clearInterval(this.flagTime);
      this.buttonFlag = false;
      this.selectPage();
    },
    judgeModel() {
      const cmd = require("node-cmd");

      let syncData = cmd.runSync("netstat -ano|findstr 9999");
      //假如数据库正在运行不动数据库状态
      if (syncData.data == null) {
        // this.$message.info("情绪判别模型尚未启动");
        this.$message({
          message:'情绪判别模型尚未启动',
          type:'info',
          duration:1000
        })
      }
      // if (syncData.data.includes("RUNNING")) {
      // }else{
      //   this.$message.info('情绪判别模型尚未启动')
      // }

      let syncData1 = cmd.runSync("netstat -ano|findstr 9999");
      //假如数据库正在运行不动数据库状态
      if (syncData1.data == null) {
        // this.$message.info("对话模型尚未启动");
        this.$message({
          message:'对话模型尚未启动',
          type:'info',
          duration:1000
        })
      }
      // if (syncData1.data.includes("RUNNING")) {
      // }else{
      //   this.$message.info('对话模型尚未启动')
      // }
    },
    handleScroll() {
      let scrollview = this.$refs["scrollview"];
      console.log(scrollview.scrollTop);
      if (scrollview.scrollTop == 0) {
        //当前没有调接口的时候
        if (!this.echoFlag) {
          //判断上一次的页面是否足够10条如果不够就不查询了
          //页面页数加1
          if (this.currenRecordTotol == this.pageSize) {
            this.pageNum++;
            this.selectPage();
          }
        }
        //当等于0时需要调用加载上一页
      }
      // console.log("qlkhdeqj1");
      //滚动监听事件
    },
    //上来就监听数据变化 如果有变化就保存最后一条数据
    //如果保存保存后

    // choiceTriger(item) {
    //   let that = this;
    //   that.radioChange(item);
    // },
    // 选中选项
    radioChange(item) {
      this.tmpRadio = item;
      var scaleInfoTemp = Object.assign({}, this.scale_infos[this.scale_index]);
      this.radio = "";
      scaleInfoTemp.checkItems = item;
      this.scale_result.push(scaleInfoTemp);
      // bbc测试判断是否展示20~24题
      if (item != "是" && this.scale_flag == "20211101163739" && this.scale_index == 19) {
        this.scale_index = 24;
        for (let i = 20; i < 24; i++) {
          this.scale_result.push(this.scale_infos[i]);
        }
        this.scale_checkItems = this.scale_infos[this.scale_index].checkItems.split("；");
        this.chatContents.push({
          from: 2,
          answer: "",
          from1: HeadImg,
          isHistory: true,
          type: 2,
          scale_checkItems: this.scale_infos[this.scale_index].checkItems.split("；"),
          isScale: true,
        });
        return;
      }
      //如果是单选题

      if (scaleInfoTemp.questionType == "0") {
        if (this.scale_index <= this.scale_infos.length - 1) this.scale_index += 1;
        this.answerSelect(this.tmpRadio);
        //scale_index == 题目总数，表示结束
        if (this.scale_index == this.scale_infos.length) {
          this.scale_index -= 1;
          this.scaleSelectFlag = false;

          //发送测试结果给后台
          // this.$message({
          //   message: "测试完成，即将生成测试报告！",
          //   type: "success",
          // });

          // console.log("==--3--------->", this.testPlanId);
          console.log(
            "==---4-------->",
            sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f")
          );
          this.$http.post(
            `v1/result/${this.scale_flag}`,
            {
              scale_result: this.scale_result,

              identifier: sessionStorage.getItem("num"),
            },
            (res) => {
              this.next_and_last_button = false;

              if (res.data.code == 200) {
                this.resultJson = res.data.data;

                if (this.scale_flag == "20210725100704") {
                } else {
                  this.getAnswerQuestionPaymentSuccess(this.resultJson);
                }
              } else {
                this.$message.error("访问服务器失败！");
              }
            }
          );
        } else {
          // 我觉得很难让自己安静下来
          let a = this.scale_infos[this.scale_index].answer + "";
          // console.log(a);
          //this.askEnd(this.scale_infos[this.scale_index].answer);
          // setTimeout(() => {
          this.askEnd(a);
          // }, 20);

          this.scale_checkItems = this.scale_infos[this.scale_index].checkItems.split(
            "；"
          );
          this.chatContents.push({
            from: 2,
            answer: "",
            from1: HeadImg,
            isHistory: true,
            type: 2,
            scale_checkItems: this.scale_infos[this.scale_index].checkItems.split("；"),
            isScale: true,
          });
        }
      }
    },

    //判断如何显示
    showSuggetion() {
      console.log(this.depressed);
      console.log(this.anxiety);
      console.log(this.stress);
      //    //压力
      //    stress: "",
      // //压力分
      // stressScore: 0,
      // //抑郁
      // depressed: "",
      // depressedScore: 0,
      // //焦虑
      // anxiety: "",
      // anxietyScore: 0,
      // //睡眠 的建议
      // sleepZD: "",
      // suggestion: "",
      // ///总得分 焦虑抑郁应激总的分
      // scoreJYY: 0,
      // sleepScore: 0,
      // if (this.emotionMul.indexOf("抑郁") != -1) {
      //   this.emotionMulCopy.push("抑郁");
      // }
      //判断是否包含抑郁
      let sumStr = `建议您使用系统中的虚拟现实、生物反馈训练<span onclick="jumpPage(6)" style="color:blue;cursor:pointer">（点击跳转）</span>、认知行为干预`;
      let jumpStr = "";
      if (this.selectParams.indexOf("抑郁") != -1) {
        if (this.depressed != "") {
          this.askEndMul(this.depressed);
        }
        if (this.depressedScore >= 7 && this.depressedScore <= 13) {
          jumpStr += `<span  onclick="jumpPage(2)" style="color:blue;cursor:pointer">（点击跳转--走出抑郁）</span>、`;
        }
      }
      if (this.selectParams.indexOf("焦虑") != -1) {
        if (this.anxiety != "") {
          this.askEndMul(this.anxiety);
        }
        if (this.anxietyScore >= 7 && this.anxietyScore <= 13) {
          jumpStr += `<span  onclick="jumpPage(1)" style="color:blue;cursor:pointer">（点击跳转--战胜焦虑)</span>、`;
        }
        //如果包含的话
      }
      if (this.selectParams.indexOf("应激") != -1) {
        if (this.stress != "") {
          this.askEndMul(this.stress);
        }

        if (this.stressScore >= 7 && this.stressScore <= 13) {
          jumpStr += `<span  onclick="jumpPage(4)" style="color:blue;cursor:pointer">（点击跳转--克服应激)</span>、`;
        }
        //如果包含的话
      }
      if (this.selectParams.indexOf("睡眠问题") != -1) {
        debugger;
        //如果包含的话
        if (this.sleepZD != "") {
          this.askEndMul(this.sleepZD);
        }
        if (this.sleepScore >= 19 && this.sleepScore <= 34) {
          jumpStr += `<span  onclick="jumpPage(3)" style="color:blue;cursor:pointer">（点击跳转--远离失眠)</span>、`;
        }
      }
      let res = jumpStr.replace(/(.*)、/, "$1");
      debugger;
      // sumStr += `进行心理状态调试。`;
      sumStr = sumStr + res + `进行心理状态调适。`;
      //判断
      if (
        this.sleepScore >= 35 ||
        this.stressScore >= 14 ||
        this.anxietyScore >= 14 ||
        this.depressedScore >= 14 ||
        this.scoreJYY >= 42
      ) {
        sumStr = `您可能存在较为严重的心理健康问题，建议您尽快到医院进行专业诊断和治疗。`;
      }
      if (
        this.sleepScore < 19 &&
        this.depressedScore < 7 &&
        this.anxietyScore < 7 &&
        this.stressScore < 7
      ) {
        sumStr = `您心理健康状态良好，希望您继续保持。`;
      }
      this.askEndMul(sumStr);
      //判断焦虑抑郁量表的分数

      // if (this.scoreJYY > 0) {
      // }
      // //判断睡眠量表的分数

      // if (this.sleepScore) {
      // }
    },

    getAnswerQuestionPaymentSuccess(id) {
      // sessionStorage.setItem("back_page", "1");
      let _this = this;
      _this.$http.post(`v1/record/find/${id}`, {}, (res) => {
        _this.scaleSelectFlag = true;
        if (res.data.code == 200 && res.data.data) {
          _this.resultJsonParams = res.data.data;
          let testResult = JSON.parse(res.data.data.userRecordEntity.testResult)[0]
            .version;
          if (_this.scale_flag === "20210910163158") {
            let sleep = JSON.parse(_this.resultJsonParams.userRecordEntity.testResult);
            this.sleepScore = sleep[0].newTableContext.result[0].score;

            sleep = sleep[0].newTableContext.result[0].improvementSuggestions;

            this.sleepZD = sleep;
            // _this.askEndMul(sleep);
            if (_this.emotionMul.length == 0) {
              _this.showSuggetion();
            } else {
              _this.judgeNum();
            }
          } else if (_this.scale_flag === "20220805135201") {
            let sleep = JSON.parse(_this.resultJsonParams.userRecordEntity.testResult);
            sleep = sleep[0].tableContext;
            console.log(sleep);
            let str = "";
            for (let i = 0; i < sleep.length; i++) {
              //if (_this.pressure_flag === "压力") {
              // if(){}

              if (sleep[i].name === "压力指导语") {
                if (_this.emotionMulCopy.indexOf("应激") != -1) {
                  //str = "压力建议:" + sleep[i].value[0] + " ";
                  this.stress = sleep[i].value[0] + " ";
                  //压力得分
                  // _this.askEndMul("应激建议:" + sleep[i].value[0] + " ");
                }
              }
              if (sleep[i].name === "压力得分") {
                if (_this.emotionMulCopy.indexOf("应激") != -1) {
                  //str = "压力建议:" + sleep[i].value[0] + " ";
                  this.stressScore = Number(sleep[i].value[0]);
                  //压力得分
                  // _this.askEndMul("应激建议:" + sleep[i].value[0] + " ");
                }
              }
              //}
              // if (_this.pressure_flag === "焦虑") {
              if (sleep[i].name === "焦虑指导语") {
                if (_this.emotionMulCopy.indexOf("焦虑") != -1) {
                  // str = "焦虑建议:" + sleep[i].value[0] + " ";
                  this.anxiety = sleep[i].value[0] + " ";
                  // this.askEndMul("焦虑建议:" + sleep[i].value[0] + " ");
                }
              }

              if (sleep[i].name === "焦虑得分") {
                if (_this.emotionMulCopy.indexOf("焦虑") != -1) {
                  // str = "焦虑建议:" + sleep[i].value[0] + " ";
                  this.anxietyScore = Number(sleep[i].value[0]);
                  // this.askEndMul("焦虑建议:" + sleep[i].value[0] + " ");
                }
              }
              //}
              //if (_this.pressure_flag === "抑郁") {
              if (sleep[i].name === "抑郁指导语") {
                if (_this.emotionMulCopy.indexOf("抑郁") != -1) {
                  //str = "抑郁建议:" + sleep[i].value[0] + " ";
                  this.depressed = sleep[i].value[0] + " ";
                  // this.askEndMul("抑郁建议:" + sleep[i].value[0] + " ");
                }
              }
              if (sleep[i].name === "抑郁得分") {
                if (_this.emotionMulCopy.indexOf("抑郁") != -1) {
                  //str = "抑郁建议:" + sleep[i].value[0] + " ";
                  this.depressedScore = Number(sleep[i].value[0]);
                  // this.askEndMul("抑郁建议:" + sleep[i].value[0] + " ");
                }
              }
            }
            for (let i = 0; i < sleep.length; i++) {
              if (sleep[i].name === "总分") {
                let score = parseInt(sleep[i].value[0]);
                this.scoreJYY = score;
                // if (score >= 0 && score <= 20) {
                // this.askEndMul(
                //   '	轻度：建议您使用系统中的虚拟现实、生物反馈训练<span onclick="jumpPage(1)" style="color:blue;cursor:pointer">（点击跳转）</span>、认知行为干预<span  onclick="jumpPage(2)" style="color:blue;cursor:pointer">（点击跳转--走出抑郁）</span>功能进行心理状态调试。'
                // );
                // }
              }
            }
            console.log(sleep);
            // _this.askEnd(str);
            if (_this.emotionMul.length == 0) {
              _this.showSuggetion();
              //在此处输出总建议
            } else {
              _this.judgeNum();
            }
            // _this.askEnd("您还想跟我再聊一聊吗?");
            // this.scale_checkItems = ["是", "否"];
          }
          // let testResult = JSON.parse(
          //   res.data.data.userRecordEntity.testResult
          // )[0].version;

          // if (testResult == 2) {
          //   _this.$router.push({
          //     name: "scaleResultSCl",
          //     params: { tableData: _this.resultJsonParams }
          //   });
          // } else {
          //   _this.$router.push({
          //     name: "scaleResult",
          //     params: { tableData: _this.resultJsonParams }
          //   });
          // }
        }
      });
    },
    jumpPage(val) {
      let that = this;
      console.log(val);
      if (val == 6) {
        //跳转到生物反馈
        // this.$router.push(c)
        this.$router.push({ path: "/menu/animation" });
        this.$emit("updateProjectId", "swfk");
      } else {
        this.$router.push({ path: "/menu/treatDepression", query: { id: val } });
        this.$emit("updateProjectId", "rzgy");
      }
      // if (val == 2) {
      //   // this.$router.push({ path: "/menu/intervene/treatDepression", query: { id: 2 } });
      //   //  this.$router.push({ path: "/menu/intervene", query: { id: 2 } });
      //   // this.$router.push({ path: "/menu/intervene" });
      //   // this.$router.push({ path: "/menu/evaluation", query: { id: 2 } });

      //   //  that.$router.push({ path: "/menu/treatDepression", query: { id: 2 } });

      //   //  this.$router.push({ path: "/menu/animation" });

      //   //跳转到//认知干预
      // }
    },
    askEndMul(val) {
      this.chatContents.push({
        from: 1,
        question: val,
        from1: HeadImg,
        //类型 1 描述
        //类型 2 单选
        //类型 3 多选
        isHistory: true,
        type: 1,
      });
      let ob = {
        label: 0,
        content: val,
      };
      this.saveRecord(ob);
      this.downPage();
    },
    downPage() {
      let contant1 = document.getElementById("contant1");
      this.sleep(101).then(() => {
        contant1.scrollTop = contant1.scrollHeight;
      });
    },
    //获取量表问题
    selectScale(flag) {
      this.$http.get(`v1/scale/${flag}`, {}, (res) => {
        this.scale_index = 0;
        this.scale_result = [];
        this.scale_infos = res.data;
        this.scale_all = this.scale_infos.length;
        this.askEnd(this.scale_infos[this.scale_index].answer);
        this.scale_checkItems = this.scale_infos[this.scale_index].checkItems.split("；");

        //将数据放入数组
        this.chatContents.push({
          from: 2,
          answer: "",
          from1: HeadImg,
          type: 2,
          scale_checkItems: this.scale_infos[this.scale_index].checkItems.split("；"),
          isHistory: true,
          isScale: true,
        });
        this.scale_percent = parseInt((this.scale_index + 1) / this.scale_all);
        this.scale_percent = ((this.scale_index + 1) * 100) / this.scale_all;
      });
    },
    //点击用户选择完毕
    selectionComplete() {
      this.buttonFlag = false;
      //设置一个全局的变量  知道选择的是那个选项
      let val = this.emotionMul.toString();
      this.selectParams = val;
      this.answerSelect(val);
      //应该先判断是否包含 抑郁，焦虑，压力
      //如果包含的话，需要将其存进数组
      this.emotionMulCopy = [];
      if (this.emotionMul.indexOf("抑郁") != -1) {
        this.emotionMulCopy.push("抑郁");
      }
      if (this.emotionMul.indexOf("焦虑") != -1) {
        this.emotionMulCopy.push("焦虑");
      }
      if (this.emotionMul.indexOf("应激") != -1) {
        this.emotionMulCopy.push("应激");
      }
      console.log(this.emotionMulCopy);
      this.judgeNum();
      //假如选择了一个--不管是无，还是睡眠，还是焦虑
    },
    //点击进行选择
    judgeNum() {
      debugger;
      if (this.emotionMul.length == 1) {
        let a = this.emotionMul[0];
        this.selectRadio(a, false);
        //清空选项
        this.emotionMul = [];
      } else if (this.emotionMul.length > 1) {
        //判断是否含有睡眠字段
        //如果含有睡眠字段
        //且长度大于2时
        if (this.emotionMul.indexOf("睡眠问题") != -1) {
          if (this.emotionMul.length > 2) {
            this.emotionMul = ["抑郁", "睡眠问题"];
          }
        } else {
          this.emotionMul = ["抑郁"];
        }

        //选择的大于1
        //假如选了两个抑郁，焦虑
        let aLin = this.emotionMul[0];
        this.selectRadio(aLin, false);
        let a = [];
        for (let i = 0; i < this.emotionMul.length; i++) {
          if (i > 0) {
            a.push(this.emotionMul[i]);
          }
        }
        console.log(a);
        this.emotionMul = a;
      }
    },
    selectRadio(val, isScale) {
      //当是量表的时候需要执行量表的逻辑
      if (isScale) {
        this.radioChange(val);
      } else {
        //当不是量表的时候需要执行不是量表的逻辑
        if (val == "无") {
          // this.answerSelect("无");
        }

        if (val === "无") {
          this.askEnd("您可能存在心理健康方面问题，建议寻求专业人员的指导");

          //隐藏选项框和输入框进行提示
        } else if (val === "睡眠问题") {
          // this.inputFlag = 3;
          this.askEnd(
            "为了进一步判断您是否存在睡眠方面的问题,下面我会问您一些问题,请您选择作答"
          );
          // this.askEnd("睡眠问卷");
          // this.scale_checkItems = ["好的"];
          this.chatContents.push({
            from: 2,
            answer: "",
            from1: HeadImg,
            type: 2,
            scale_checkItems: ["好的"],
            isHistory: true,
            isScale: false,
          });
          // this.inputFlag = 2;
          this.scale_flag = "20210910163158";
          // this.selectScale(this.scale_flag);
          //调用接口睡眠量表
        } else if (val === "抑郁" || val === "焦虑" || val === "应激") {
          if (val === "抑郁") {
            this.pressure_flag = "抑郁";
          }
          if (val === "焦虑") {
            this.pressure_flag = "焦虑";
          }
          if (val === "应激") {
            this.pressure_flag = "应激";
          }
          // this.inputFlag = 3;
          this.askEnd(
            "为了进一步判断您是否存在心理健康方面的问题,下面我会问您一些问题,请您选择作答"
          );
          // this.askEnd("抑郁、焦虑、压力问卷");
          this.scale_checkItems = ["好的"];
          this.chatContents.push({
            from: 2,
            answer: "",
            from1: HeadImg,
            type: 2,
            scale_checkItems: ["好的"],
            isHistory: true,
            isScale: false,
          });
          //

          // this.inputFlag = 2;
          this.scale_flag = "20220805135201";
          // this.selectScale(this.scale_flag);
          //调用接口抑郁焦虑压力问卷
        } else if (val === "好的") {
          // this.inputFlag = 3;
          // if(this.scale_flag==='20210910163158'){

          // }
          this.answerSelect("好的");
          this.selectScale(this.scale_flag);
        } else if (val === "是") {
          //从头开始
          this.init("reStart");
          // this.inputFlag = 1;
        } else if (val === "否") {
          //结束测试
          // this.askEnd("对话结束");
          // this.inputFlag = 0;
        }
      }

      //应该是先判断是否有量表选择的

      // this.answerSelect(val);
      //如果是包含 抑郁 焦虑  压力 在这其中，则
      // if(this.emotionMulCopy.indexOf(val)!=-1){
      //    this.answerSelect(this.emotionMulCopy.toString());
      // }else{
      //    this.answerSelect(val);
      // }
    },
    mulItem(val) {
      console.log(this.emotionMul);
      //先判断是否是点击否，如果点击否
      //则需要判断里边是否存在否
      //如果里边不存在，选中后其他选项都置为空
      if (val == "无") {
        console.log(this.emotionMul.indexOf("无") == -1);
        if (this.emotionMul.indexOf("无") == -1) {
          //不存在
          for (let i = 0; i < this.scale_MulItems.length; i++) {
            this.scale_MulItems[i].disable = false;
          }
        } else {
          //存在
          this.emotionMul = ["无"];

          //scale_MulItems
          //循环问题
          for (let i = 0; i < this.scale_MulItems.length; i++) {
            if (this.scale_MulItems[i].name !== "无") {
              this.scale_MulItems[i].disable = true;
            }
          }
        }
      }
    },
    init() {
      //进入页面后先执行查询前50条数据的接口

      //查询前5条数据
      this.selectPage();
      let contant1 = document.getElementById("contant1");
      this.sleep(300).then(() => {
        contant1.scrollTop = contant1.scrollHeight;
      });
    },
    //查询记录的方法
    selectPage() {
      let that = this;
      that.echoFlag = true;
      this.$http.get(
        `/intelligent/dialogueRecords?identifier=${sessionStorage.getItem(
          "num"
        )}&pageNum=${that.pageNum}&pageSize=${that.pageSize}&type=0`,
        {},
        (res) => {
          if (res.code == 200) {
            that.echoFlag = false;
            //  res.data.

            if (res.data.intelligentDialogueEntities.content.length > 0) {
              that.currenRecordTotol =
                res.data.intelligentDialogueEntities.content.length;
              //判断当前是第几页
              //如果是第一个
              for (
                let i = 0;
                i < res.data.intelligentDialogueEntities.content.length;
                i++
              ) {
                if (res.data.intelligentDialogueEntities.content[i].label == "0") {
                  if (that.$root.smartNum == 1) {
                    this.chatContents.unshift({
                      from: 1,
                      question: res.data.intelligentDialogueEntities.content[i].content,
                      from1: HeadImg,
                      isHistory: true,
                      type: 1,
                    });
                  } else {
                    this.chatContents.unshift({
                      from: 1,
                      question: res.data.intelligentDialogueEntities.content[i].content,
                      from1: HeadImg,
                      isHistory: true,
                      type: 1,
                    });
                  }
                } else {
                  if (that.$root.smartNum == 1) {
                    this.chatContents.unshift({
                      from: 2,
                      answer: res.data.intelligentDialogueEntities.content[i].content,
                      from1: HeadImg,
                      isHistory: true,
                      type: 1,
                    });
                  } else {
                    this.chatContents.unshift({
                      from: 2,
                      answer: res.data.intelligentDialogueEntities.content[i].content,
                      from1: HeadImg,
                      isHistory: true,
                      type: 1,
                    });
                  }
                }
              }
              let contant1 = document.getElementById("contant1");
              this.sleep(300).then(() => {
                contant1.scrollTop = 2;
              });
            }
          } else {
          }
        }
      );
    },
    sleep(time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    },

    sendMsg() {
      //判断对话长度是否大于0
      //如果大于0  则取最后看最后一个是不是form等于2如果是2 类型是2或3时则不反应
      if (this.chatContents.length > 0) {
        if (this.chatContents[this.chatContents.length - 1].from !== 1) {
          if (
            this.chatContents[this.chatContents.length - 1].type == 2 ||
            this.chatContents[this.chatContents.length - 1].type == 3
          ) {
            return;
          }
        }
      }
      if (this.desc.length == 0 || this.buttonFlag) {
        return;
      }
      this.sendMsgFlag = false;
      let contant1 = document.getElementById("contant1");
      let tmp = {
        from: 2,
        answer: this.desc,
        from1: HeadImg,
        type: 1,
      };
      this.chatContents.push(tmp);

      this.getQuestion();
      //在调用一个方法，将这个值的情绪发送给另一个方法
      this.getMood(this.desc);
      //调用保存接口
      let ob = {
        label: 1,
        content: this.desc,
      };
      this.saveRecord(ob);
      // 让滚动条始终在最底部
      this.sleep(101).then(() => {
        contant1.scrollTop = contant1.scrollHeight;
      });
      this.desc = "";
      //立马调用
      //进行提问的接口
      //第一个问题出来后先对答案进行解析
    },
    getMood(val) {
      //代替对话
      this.moonNegative += 1;
      // http://127.0.0.1:9999/sentiment
      //http://127.0.0.1:9999
      //`http://127.0.0.1:9999/sentiment
      //http://aagvs5.natappfree.cc/sentiment
      //http://127.0.0.1:9999/sentiment
      //http://127.0.0.1:9999/sentiment
      //情绪判别
      // let that = this;
      // axios.post(`http://127.0.0.1:9999/sentiment`, { text: val }).then((res) => {
      //   console.log(res.data.sentiment);
      //   if (
      //     res.data.sentiment === "厌恶" ||
      //     res.data.sentiment === "恐惧" ||
      //     res.data.sentiment === "悲伤" ||
      //     res.data.sentiment === "愤怒"
      //   ) {
      //     this.moonNegative += 1;
      //   }

      //   //假如负面情绪大于5则需要调用量表方法

      //   // that.sendMsgFlag = true;
      //   // that.threeAnswers.push(res.data.sentiment);
      //   //如果是已婚人员则判断七个中是否存在4个负面情绪
      //   //0为已婚人员
      // });
    },
    //发送问题的接口

    //获取问题的接口//需要传输上下文关系，应该是需要上一个问题回答的是啥
    getQuestion() {
      let that = this;
      that.buttonFlag = true;

      //循环当前问题
      let list = [];

      //传输到后台的上下文.最大限制6条吧
      //当回显的条数小于6条时走下边的逻辑
      if (this.chatContents.length < 5) {
        for (let i = 0; i < this.chatContents.length; i++) {
          if (this.chatContents[i].from == 1) {
            console.log(this.chatContents[i].hasOwnProperty("isHistory"));
            if (!this.chatContents[i].hasOwnProperty("isHistory")) {
              list.push(this.chatContents[i].question);
            }
          } else {
            if (!this.chatContents[i].hasOwnProperty("isHistory")) {
              list.push(this.chatContents[i].answer);
            }
          }
        }
      } else {
        for (let i = 5; i > 0; i--) {
          if (this.chatContents[this.chatContents.length - i].from == 1) {
            if (
              !this.chatContents[this.chatContents.length - i].hasOwnProperty("isHistory")
            ) {
              list.push(this.chatContents[this.chatContents.length - i].question);
            }
          } else {
            if (
              !this.chatContents[this.chatContents.length - i].hasOwnProperty("isHistory")
            ) {
              list.push(this.chatContents[this.chatContents.length - i].answer);
            }
          }
          // list.push(chatContents.question);
        }
      }
      // 进入页面后调用加载中的方法
      //三个点轮询播放
      this.chatContents.push({
        from: 1,
        question: "",
        from1: HeadImg,
        type: 1,
      });
      this.pFun("......", false);
      //`http://127.0.0.1:9998/chat`
      //http://127.0.0.1:9998/chat
      //http://ray-thunder.natapp1.cc/chat

      //代替智能对话
      let contant1 = document.getElementById("contant1");
      this.sleep(101).then(() => {
        contant1.scrollTop = contant1.scrollHeight;
      });

      clearInterval(this.flagTime);
      this.pFun("我收到了", true);
      //先判断list是否是奇数  如果是奇数就没问题如果并不是奇数择传输少一位即可

      // if(list.length%2==0){
      //   list.shift()
      // }
      // console.log('list')
      // console.log(list)
      // HTTP_AXIOS({
      //   method: "post",
      //   url: `http://127.0.0.1:9998/chat`,
      //   data: { text: list },
      //   timeout: 300000,
      // })
      //   .then((res) => {
      //     if (res) {
      //       let contant1 = document.getElementById("contant1");
      //       this.sleep(101).then(() => {
      //         contant1.scrollTop = contant1.scrollHeight;
      //       });

      //       clearInterval(this.flagTime);
      //       this.pFun(res.data.response, true);
      //       //请求成功后返回的参数
      //       //console.log(res);
      //     }
      //   })
      //   .catch((error) => {
      //     if (error.config.timeout == 300000) {
      //       Message.error("请求超时，请检查网络");
      //     } else {
      //       console.log(error);
      //     }
      //   });
    },
    startScale() {
      // this.inputFlag = 4;
      //进行提问
      this.buttonFlag = true;
      this.chatContents.push({
        from: 1,
        question: "请问您近期是否存在以下方面的困扰(请选择)",
        from1: HeadImg,
        isHistory: true,
        type: 1,
      });
      let ob = {
        label: 0,
        content: "请问您近期是否存在以下方面的困扰(请选择)",
        type: 1,
      };
      this.saveRecord(ob);
      this.chatContents.push({
        from: 2,
        question: "",
        from1: HeadImg,
        isHistory: true,
        type: 3,
        scale_MulItems: [
          { name: "抑郁", disable: false },
          { name: "焦虑", disable: false },
          { name: "应激", disable: false },
          { name: "睡眠问题", disable: false },
          { name: "无", disable: false },
        ],
        isScale: false,
      });
      // this.scale_MulItems = [
      //   { name: "抑郁", disable: false },
      //   { name: "焦虑", disable: false },
      //   { name: "应激", disable: false },
      //   { name: "睡眠问题", disable: false },
      //   { name: "无", disable: false },
      // ];
    },
    pFun(val, flag) {
      let that = this;
      //3个循环播放
      this.chatContents[this.chatContents.length - 1].question = "";
      this.printIndex = 0;
      let a = val;
      clearInterval(this.flagTime);
      this.flagTime = setInterval(
        () => {
          if (this.printIndex < a.length) {
            this.chatContents[this.chatContents.length - 1].question += a.charAt(
              this.printIndex
            );
            this.printIndex++;
            if (flag) {
              let contant1 = document.getElementById("contant1");
              this.sleep(101).then(() => {
                contant1.scrollTop = contant1.scrollHeight;
              });
            }
          } else {
            if (flag) {
              that.buttonFlag = false;
              //清除定时器
              let contant1 = document.getElementById("contant1");
              this.sleep(101).then(() => {
                contant1.scrollTop = contant1.scrollHeight;
              });
              // this.saveRecord(this.chatContents[this.chatContents.length - 1].question)
              clearInterval(this.flagTime);
              let ob = {
                label: 0,
                content: this.chatContents[this.chatContents.length - 1].question,
              };
              this.saveRecord(ob);
              //在这判断负面情绪是否足够5个
              if (this.moonNegative == 5) {
                this.startScale();
              }
            } else {
              this.printIndex = 0;
              this.chatContents[this.chatContents.length - 1].question = ".";
            }
          }
        },
        flag ? 60 : 300
      );
    },

    //保存记录的接口
    saveRecord(val) {
      let data = {
        identifier: this.identifier,
        label: val.label,
        content: val.content,
        userName: this.userName,
        questionNo: "",
        type: "0",
      };
      console.log(data);
      // this.$message.success("保存成功");
      this.$http.post(`/intelligent/save`, data, (res) => {
        if (res.data.code == 200) {
          console.log(val.content);
        } else {
        }
      });
    },
    //调用接口查询情绪

    askEnd(val) {
      this.chatContents.push({
        from: 1,
        question: val,
        from1: HeadImg,
        isHistory: true,
        type: 1,
      });
      let ob = {
        label: 0,
        content: val,
      };

      let contant1 = document.getElementById("contant1");
      this.sleep(101).then(() => {
        this.saveRecord(ob);
        contant1.scrollTop = contant1.scrollHeight;
      });
    },
    answerSelect(val) {
      this.chatContents.push({
        from: 2,
        answer: val,
        from1: HeadImg,
        isHistory: true,
        type: 1,
      });
      let ob = {
        label: 1,
        content: val,
      };
      this.saveRecord(ob);
    },
    askQuestions() {
      this.chatContents.push({
        from: 1,
        question: this.preList[this.threeAnswers.length].des,
        from1: HeadImg,
        isHistory: true,
        type: 1,
      });
      let ob = {
        label: 0,
        content: val,
      };
      this.saveRecord(ob);
      this.questionNum++;
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>
<style scoped>
.mainTable-top {
  margin-top: 5%;
}

.mainTable-top-two {
  margin-top: 10%;
}

.mainTable-tab {
  cursor: pointer;
  margin-left: 100px;
  margin-right: 100px;
  border-radius: 5px;
  border: 1px solid #000000;
  text-align: center;
  height: 150px;
  margin-bottom: 100px;
}

.mainTable-tab-p {
  padding-top: 40px;
}

.musicTitle {
  display: block;
  font-size: 18px;
  color: #57acbb;
  margin-bottom: 5px;
}

.main_answer_left {
  display: flex;
  /* text-align: left; */
}

.main_answer_right {
  display: flex;
  /* text-align: right; */
}

.message-wrapper {
  background-color: #ffffff;
}

.message-wrapper-left {
  margin-left: 10px;
  /* border-radius: 0 1rem 1rem 1rem; */
  border-radius: 4px 4px 4px 4px;
  max-width: 20.86667rem;
  display: inline-table;
}

.message-wrapper-right {
  margin-right: 10px;
  border-radius: 4px 4px 4px 4px;
  max-width: 20.86667rem;
  display: inline-table;
  background-color: #1fd18e;
  color: #ffffff;
  /* margin-top: 25px; */
}

.message {
  word-break: break-all;
  padding: 18px;
  /* font-size: 20px; */
}

.xl_d_button {
  background: rgb(87, 172, 187);
  opacity: 1;
  border-radius: 50%;
  font-size: 20px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #ffffff;
  width: 40px;
  line-height: 40px;
  text-align: center;
}

.xl_d_button:hover {
  background: rgb(87, 172, 187);
  opacity: 1;
  /* border-radius: 18px; */
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #ffffff;
}

.xl_d_button:focus {
  background: rgb(87, 172, 187);
  opacity: 1;
  /* border-radius: 18px; */
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #ffffff;
}

.refrshSmart {
  float: right;
  cursor: pointer;
}

.xl_input >>> .el-input__inner {
  border: 0;
  border-radius: 4px;
  background-color: #f4f4f4;
  height: 120px;
}

.footSend {
  background: #ffffff;
  /* position: absolute; */
  height: 120px;
  margin-left: 2%;
  width: 96%;
  border-radius: 14px;
  margin-bottom: 35px;
  display: flex;
  flex-direction: row;

  /* bottom: 50px; */
}

.smart_line_class {
  /* background: #BBC5D4; */
  /* position: absolute; */
  height: 1px;
  margin-left: 2%;
  width: 96%;
  border-radius: 14px;
  bottom: 150px;
  border-bottom: 1px solid #bbc5d4;
  margin-bottom: 32px;
  margin-top: 10px;
}

.footSend >>> .el-textarea__inner {
  border: 0px solid #ffffff !important;
  border-radius: 14px !important;
  height: 100px !important;
}

.footSendSelect {
  background: #ffffff;
  /* padding-bottom: 40px; */
  position: absolute;
  margin-left: 2%;
  width: 90%;
  bottom: 40px;
}

.xl_d_send {
  margin-top: 18px;
  color: #087b50;
  background: #c6f0ed !important;
  opacity: 1;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  text-align: center;
  border: 0px;
  border-radius: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  width: 80px;
}

.xl_d_send:hover {
  margin-top: 18px;
  color: #087b50;
  background: #c6f0ed !important;
  opacity: 1;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  text-align: center;
  border-radius: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.xl_d_send:focus {
  margin-top: 18px;
  color: #087b50;
  background: #c6f0ed !important;
  opacity: 1;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  text-align: center;
  border-radius: 10px;
}

.xl_d_send.is-disabled,
.xl_d_send.is-disabled:hover,
.xl_d_send.is-disabled:focus {
  margin-top: 18px;
  color: #087b50;
  background: #c6f0ed !important;
  opacity: 1;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  text-align: center;
  border-radius: 10px;
}

.main_right_height {
  /* padding:40px; */
  height: 100vh !important;
  display: block !important;
  /* overflow-y: auto !important; */
  overflow-y: hidden !important;
  background-color: #ffffff;
}

.smart_content {
  height: 88%;
  /* height: 88%; */
  margin-top: 5%;
  width: 94%;
  margin-left: 3%;
  border-radius: 40px;
  background: #f6f6f6;

  display: flex;
  flex-direction: column;
}

.chat-window {
  overflow-y: scroll;
  /* height: 70vh; */
  flex: 1;
  overflow: auto;
  /* overflow-y:hidden; */
}

.smart_mul_button {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.smart_mid {
  flex: 1;
  overflow-y: auto;
}

.send_buttom_style {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.smart_mul_form2 {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.check_column {
  display: flex;
  flex-direction: column;
}
.check_column .check {
  /* margin-left: 30px; */
}

.check_column .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px !important;
  width: 120px;
}
.check_column .el-checkbox.is-bordered {
  margin-top: 2px;
  background-color: #ffffff;
}
.smart_radio .el-radio.is-bordered + .el-radio.is-bordered {
  margin-left: 0px !important;
}
.smart_mul_button_select {
  width: 120px;
  left: 0;
}

/* .contant1{
 height:70vh;
  overflow:auto;
} */
</style>
