
<template>
  <div>
    <div class="desc_wrap" v-if="testFlag">
      <div style="
          width: 70%;
          height: 100%;
          background: rgb(248, 248, 248);
          opacity: 1;
          border-radius: 12px;
          margin: 0 auto;
        ">
        <div class="left_part">
          <div id="left_top">
            <div>
              <div id="setting">
                <img src="../../assets/9551.png" alt="" />
              </div>
              <div id="text">
                <span>操作提示：</span>
              </div>
            </div>
          </div>
          <div style="margin: 100px auto; width: 80%; text-align: justify;text-justify: distribute-all-lines;">
            <p v-show="testTypeCode == 0" v-html="subjectInfo.testDescription"></p>
            <p v-show="testTypeCode == 1">
              “欢迎来到测试阶段！
              <br><br>
              在测试阶段将没有答案提示，请你选择正确的情绪类别。此阶段共测试35张图片，当您的正确率达到80%以上，即可进入正式评价阶段。”
            </p>
            <p v-show="testTypeCode == 2">
              “欢迎来到正式测试阶段!<br><br>
              正式测试过程中，需要对出现的表情图片进行吸引力、愉悦度、唤醒度，优势度的评价。评价方式采用九点评分的方式。<br><br>
              吸引力:面孔吸引力，即面孔的美感，对她/他的喜欢程度以及你预期和她/他交流的愉快程度。<br><br>
              吸引力越大，评分越接近9；吸引力越小，评分越接近 0 。<br><br>
              愉悦度:愉快或不愉快的情绪体验（非常积极、愉快--非常消极、忧伤）。<br><br>
              愉悦度越高，评分越接近9，愉悦度越低，评分越接近 0 ；<br><br>
              唤醒度:情绪引起内心的激动程度或者情绪引起身体的激动反应（非常激动--非常平静）。<br><br>
              唤醒度越高，评分越接近9，唤醒度越低，评分越接近0；<br><br>
              优势度:优势度衡量的是“受控——支配”的程度（最受控制、弱小--最可支配、强大有力）。低优势度代表感到完全受控制、影响，是弱小顺从、被引导、受约束、受操纵、屈服的、处于劣势；高优势度表示自己处于支配地位、感到自信、强大、有力量，具有充分的支配权和控制度、完全能制约、操纵、有影响力的、居优势地位的。<br><br>
              优势度越高，评分越接近9，优势度越低，评分越接近0<br><br>
              （后面的测试页面可随时查看各个维度的定义）。”
            </p>
            <!-- <p>{{subjectInfo.description}}</p> -->
          </div>
        </div>
        <div class="right_part" :style="{
            background:
              'url(' + require('../../assets/page' + taskId + '.png') + ')',
            'background-size': '100% 100%',
          }">
          <div id="title">
            <span>{{ subjectInfo.name }}</span>
          </div>
          <div style="position: absolute; bottom: 30px; right: 40%">
            <el-button v-if="buttonShow" class="start" @click="startTest()">{{
              buttonName
            }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!testFlag" class="activeTask">
      <img @click="screen()" src="../../assets/small-big.png" alt="" style="
          height: 48px;
          width: 48px;
          position: fixed;
          top: 24px;
          right: 22px;
          cursor: pointer;
        " />
      <div style="width: 50%; margin-left: 10%; margin-top: 24px; z-index: 10">
        <el-progress class="main_progress" :text-inside="true" :format="format" :stroke-width="24"
          :percentage="((cumulation + 1) / testList.length) * 100"></el-progress>
      </div>
      <p v-if="timingShow" class="timingBox">{{ countDownStr }}</p>
      <div class="shape_glass">
        <img v-show="!crossShow" class="active-img addImg" :src="testList[cumulation].imgUrl" alt="" />
      </div>
      <div class="btn-content" v-if="!crossShow">
        <el-button v-if="testTypeCode == 2" class="butt" @click="prevHandle" :disabled="isLoading">
          上一题
        </el-button>
        <el-button v-for="item in testList[cumulation].buttonList" :key="item.val" class="butt" :class="{
            active: item.val == testList[cumulation].emoType && showGuider,
            choose: item.val == testList[cumulation].userResponse,
          }" @click="userClick(item.val)">
          {{ item.name }}
        </el-button>
        <el-button v-if="testTypeCode == 2" class="butt" @click="nextHandle" :disabled="isLoading">
          下一题
        </el-button>
      </div>
      <div v-if="testTypeCode == 2 && !crossShow" class="block">
        <div class="slider">
          <el-tooltip placement="top">
            <div slot="content">
              面孔吸引力，即面孔的美感，对她/他的喜欢程度以及你预期和她/他交流的愉快程度。<br />吸引力越大，进度条越靠近右侧，越接近
              9；吸引力越小，进度条越靠近左侧，评分越接近 0 。
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
          <span>吸引度</span>
          <el-rate v-model="testList[cumulation].xiyin" :max="9" void-color="#999999" show-score text-color="#ff9900"
            score-template="评分{value}">
          </el-rate>
        </div>
        <div class="slider">
          <el-tooltip placement="top">
            <div slot="content">
              愉快或不愉快的情绪体验（非常积极、愉快--非常消极、忧伤）。<br />愉悦度越高，评分越接近
              9，愉悦度越低，评分越接近 0 分；
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
          <span>愉悦度</span>
          <el-rate v-model="testList[cumulation].yuyue" :max="9" void-color="#999999" show-score text-color="#ff9900"
            score-template="评分{value}">
          </el-rate>
        </div>
        <div class="slider">
          <el-tooltip placement="top">
            <div slot="content">
              情绪的生理唤醒程度。情绪引起内心的的激动程度或者情绪引起身体的激动反应（非常激动--非常平静）。<br />唤醒度越高，评分越接近
              9，唤醒度越低，评分越接近0；
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
          <span>唤醒度</span>
          <el-rate v-model="testList[cumulation].huanxing" :max="9" void-color="#999999" show-score text-color="#ff9900"
            score-template="评分{value}">
          </el-rate>
        </div>
        <div class="slider">
          <el-tooltip placement="top">
            <div slot="content">
              优势度衡量的是“受控——支配”的程度（最受控制、弱小到最可支配、强大有力）。<br />低优势度代表感到完全受控制、影响，是弱小顺从、被引导、受约束、受操纵、屈服的、处于劣势；<br />高优势度表示自己处于支配地位、感到自信、强大、有力量，具有充分的支配权和控制度、完全能制约、操纵、有影响力的、居优势地位的。<br />优势度越高，评分越接近
              9，优势度越低，评分越接近0。
            </div>
            <i class="el-icon-info"></i>
          </el-tooltip>
          <span>优势度</span>
          <el-rate v-model="testList[cumulation].youshi" :max="9" void-color="#999999" show-score text-color="#ff9900"
            score-template="评分{value}">
          </el-rate>
        </div>
      </div>
      <div class="guider" v-show="showGuider && testTypeCode == 0">
        <div class="txt">
          <p class="explain">
            观察图片中人物的面部表情，下方闪烁的选项是正确的情绪类型。请学习这种对应关系，点击下方按钮，选择正确的情绪类型
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { oSessionStorage, preloader, preloader2 } from "@/utils/utils";
import screenfull from "screenfull";
import peoples from "../../assets/data/EmotionalAbility";
export default {
  name: "ETBexperiment_new",
  data() {
    return {
      marks: {
        0: "0",
        1: "1",
        2: "2",
        3: "3",
        4: "4",
        5: "5",
        6: "6",
        7: "7",
        8: "8",
        9: "9",
        10: "10",
      },
      buttonShowTime: 2000, //按钮出现的时间
      cycles: 71, //循环的次数
      showGuider: false, //显示灰色背景当作引导
      testFlag: true, //显示提示页面与测试页面控制开关
      timingShow: true, //倒计时5秒提示开始
      timingFlag: null, // 倒计时名称
      countDown: 5, //倒计时5秒
      countDownStr: "学习阶段",
      crossShow: true, //显示注视点
      expressionShow: false, //显示表情图片
      buttonShow: true, //显示选择按钮
      buttonName: "学习阶段",
      timingOne: null,
      timingTwo: null,
      timingThree: null,
      flag: null, //反应时间计时器名
      cumulation: 0, //累加器
      examImgUrl: "", //展示图片
      randomArr: [], //从十个人中随机获取3个人
      emoList: {
        happy: { name: "开心", val: "happy" },
        fear: { name: "害怕", val: "fear" },
        angry: { name: "生气", val: "angry" },
        disgust: { name: "厌恶", val: "disgust" },
        sad: { name: "悲伤", val: "sad" },
        surprise: { name: "惊讶", val: "surprise" },
        neutral: { name: "中性", val: "neutral" },
      },
      testList: [], // 当前测试列表
      practiceList: [], // 练习测试列表
      normalList: [], // 正式测试列表
      studyList: [],
      testTypeCode: 0,
      phone: "",
      timer2: null,
      isLoading: false,
      threeMinStr: "",
    };
  },
  // 页面初始化函数
  created() {
    this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
    this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
    this.taskId = this.$route.query.taskId;
    this.phone = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9e87");
  },
  mounted() {
    this.buttonShowTime = 20000000;
  },
  methods: {
    screen() {
      screenfull.toggle();
    },
    startTiming() {
      if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        this.$message.error("请先登录！");
        return;
      }
      //关闭提示内容窗口
      this.testFlag = false;
      this.timingShow = true;
      this.crossShow = true;
      this.timingFlag = window.setInterval(() => {
        if (this.countDown == 0) {
          clearInterval(this.timingFlag);
          this.countDownStr = "开始";
          setTimeout(() => {
            //关闭倒计时提示页面
            this.timingShow = false;
            this.crossShow = false;
            this.countDown = 5;
            if (this.testTypeCode == 0) {
              this.showGuider = true;
            }
          }, 1000);
        } else {
          this.countDownStr = this.countDown;
          this.countDown--;
        }
      }, 1000);
    },
    format(percentage) {
      return `${this.cumulation + 1}/${this.testList.length}`;
    },

    shuffle(arr) {
      for (let i = 1; i < arr.length; i++) {
        const random = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[random]] = [arr[random], arr[i]];
      }
      return arr;
    },

    // 生成学习列表
    async createStudyList() {
      this.studyList = [];
      let emoList = this.shuffle([
        "happy",
        "fear",
        "angry",
        "disgust",
        "sad",
        "surprise",
        "neutral",
      ]);
      for (let i = 0; i < emoList.length; i++) {
        let w = 61 + i;
        let m = 71 + i;
        let imgList1 = peoples[w][emoList[i]];
        let imgList2 = peoples[m][emoList[i]];
        // 添加一个女性
        this.studyList.push({
          name: `${w}-${emoList[i]}-${imgList1[imgList1.length - 1]}`, // 图片名称
          imgUrl: require(`../../assets/congnitiveAblitity/EmotionalAbility/${w}/${emoList[i]
            }/${imgList1[imgList1.length - 1]}.png`), // 图片url
          emoType: `${emoList[i]}`, // 情绪类型
          userResponse: "", // 用户反映类型
          correct: false, // 是否正确
          xiyin: 0, // 吸引力
          yuyue: 0, // 愉悦度
          huanxing: 0, // 唤醒度
          youshi: 0, // 优势度
          buttonList: this.createAnwserList(emoList[i], i),
        });

        // 添加一个男性
        this.studyList.push({
          name: `${m}-${emoList[i]}-${imgList2[imgList2.length - 1]}`, // 图片名称
          imgUrl: require(`../../assets/congnitiveAblitity/EmotionalAbility/${m}/${emoList[i]
            }/${imgList2[imgList2.length - 1]}.png`), // 图片url
          emoType: `${emoList[i]}`, // 情绪类型
          userResponse: "", // 用户反映类型
          correct: false, // 是否正确
          xiyin: 0, // 吸引力
          yuyue: 0, // 愉悦度
          huanxing: 0, // 唤醒度
          youshi: 0, // 优势度
          buttonList: this.createAnwserList(emoList[i], i),
        });
      }

      this.studyList = this.shuffle(this.studyList);
    },

    // 生成测试列表
    async createPriticeList() {
      this.practiceList = [];
      let roleList = [61, 62, 62, 34, 65, 66, 67, 71, 72, 72, 74, 75, 76, 77];
      let tempList = [];
      while (tempList.length < 5) {
        let index = Math.floor(Math.random() * 14);
        if (!tempList.includes(roleList[index])) {
          tempList.push(roleList[index]);
        }
      }
      let emoList = this.shuffle([
        "happy",
        "fear",
        "angry",
        "disgust",
        "sad",
        "surprise",
        "neutral",
      ]);
      for (let item of tempList) {
        for (let j = 0; j < emoList.length; j++) {
          let imgList1 = peoples[item][emoList[j]];
          this.practiceList.push({
            name: `${item}-${emoList[j]}-${imgList1[imgList1.length - 1]}`, // 图片名称
            imgUrl: require(`../../assets/congnitiveAblitity/EmotionalAbility/${item}/${emoList[j]
              }/${imgList1[imgList1.length - 1]}.png`), // 图片url
            emoType: `${emoList[j]}`, // 情绪类型
            userResponse: "", // 用户反映类型
            correct: false, // 是否正确
            xiyin: 0, // 吸引力
            yuyue: 0, // 愉悦度
            huanxing: 0, // 唤醒度
            youshi: 0, // 优势度
            buttonList: this.createAnwserList(emoList[j]),
          });
        }
      }
      this.practiceList = this.shuffle(this.practiceList);
    },

    // 生成正式测试列表
    async createNormalList() {
      this.normalList = [];
      let emoList = [
        "happy",
        "fear",
        "angry",
        "disgust",
        "sad",
        "surprise",
        "neutral",
      ];
      for (let i = 0; i < 50; i++) {
        for (const item of emoList) {
          let m = Math.floor(Math.random() * 5);
          let imgList = peoples[i][item];
          this.normalList.push({
            name: `${i}-${item}-${imgList[m]}`, // 图片名称
            imgUrl: require(`../../assets/congnitiveAblitity/EmotionalAbility/${i}/${item}/${imgList[m]}.png`), // 图片url
            emoType: `${item}`, // 情绪类型
            userResponse: "", // 用户反映类型
            correct: false, // 是否正确
            xiyin: 0, // 吸引力
            yuyue: 0, // 愉悦度
            huanxing: 0, // 唤醒度
            youshi: 0, // 优势度
            buttonList: this.createAnwserList(item),
          });
        }
      }
      this.normalList = this.shuffle(this.normalList);
    },

    // 随机生成答案
    createAnwserList(item, index) {
      let arr = [
        "happy",
        "fear",
        "angry",
        "disgust",
        "sad",
        "surprise",
        "neutral",
      ];
      let i = arr.indexOf(item);
      arr.splice(i, 1);
      let j = Math.floor(Math.random() * 6);
      let temp = arr[j];
      let btnList = [];
      if (this.testTypeCode == 0 && index < 14) {
        btnList = [this.emoList[item]];
      } else {
        btnList = this.shuffle([this.emoList[temp], this.emoList[item]]);
      }
      return btnList;
    },

    userClick(param) {
      this.testList[this.cumulation].userResponse = param; //用户选择的情绪类型
      this.testList[this.cumulation].correct = param == this.testList[this.cumulation].emoType ? true : false;
      if (this.testTypeCode != 2) {
        this.nextHandle();
      }
    },

    // 上一题
    prevHandle() {
      if (this.cumulation > 0) {
        this.cumulation--;
      }
    },

    // 下一题
    nextHandle() {
      if (this.cumulation < this.testList.length - 1) {
        if (!this.testList[this.cumulation].userResponse) {
          this.$message.warning("请选择对应的情绪！");
        } else if (
          this.testTypeCode === 2 &&
          (this.testList[this.cumulation].xiyin == 0 ||
            this.testList[this.cumulation].yuyue == 0 ||
            this.testList[this.cumulation].huanxing == 0 ||
            this.testList[this.cumulation].youshi == 0)
        ) {
          this.$message.warning("请选择对应的评分！");
        } else {
          this.cumulation++;
          if (this.cumulation % 50 == 0 && this.cumulation < 349) {
            this.timingShow = true;
            this.crossShow = true;
            this.threeMinDown();
          }
        }
      } else {
        if (this.testTypeCode == 1) {
          let rate = this.getCorrectRate(this.testList);
          this.practiceResult(rate);
        } else if (this.testTypeCode == 2) {
          this.submitData();
        } else {
          this.showGuider = false;
          this.testFlag = true;
          this.cumulation = 0;
          this.testTypeCode = 1;
          this.buttonName = "练习阶段";
          this.countDownStr = "练习阶段";
        }
      }
    },

    // 计算准确率
    getCorrectRate(arr) {
      let num = 0;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].correct) {
          num += 1;
        }
      }
      return num / arr.length;
    },

    // 练习测试结果处理
    practiceResult(rate) {
      if (rate >= 0.8) {
        this.$message.success("恭喜你，通过练习测试");
        this.testTypeCode = 2;
        this.buttonName = "正式测试";
        this.countDownStr = "正式测试";
      } else {
        this.testTypeCode = 0;
        this.$message.warning("未通过练习测试");
        this.countDownStr = "学习阶段";
        this.buttonName = "学习阶段";
      }
      this.countDown = 5;
      this.testFlag = true;
      this.cumulation = 0;
      screenfull.exit();
    },

    submitData() {
      if (this.isLoading) {
        return;
      }
      let results = [];
      this.testList.forEach((el) => {
        results.push({
          name: el.name, // 图片名称
          emoType: el.emoType, // 情绪类型
          userResponse: el.userResponse, // 用户反映类型
          correct: el.correct, // 是否正确
          xiyin: el.xiyin, // 吸引力
          yuyue: el.yuyue, // 愉悦度
          huanxing: el.huanxing, // 唤醒度
          youshi: el.youshi, // 优势度
        });
      });
      this.$http.post(
        `/cognize/EAT`,
        {
          userId: this.userId,
          testPlanId: this.$route.query.testPlanId || "",
          results: results,
        },
        (response) => {
          this.isLoading = false;
          if (response && response.code == "200") {
            //跳转新测试结果页面
            this.goTestResult(response.data);
          } else {
            this.$message.error("接口数据出错");
          }
        },
        (err) => {
          this.isLoading = false;
        }
      );

      screenfull.exit();
      this.$message({
        message: "测试结束！",
        type: "success",
      });
    },
    startTest() {
      screenfull.request();
      if (this.testTypeCode == 0) {
        // 生成学习列表
        this.createStudyList().then(() => {
          preloader(this.studyList, () => {
            this.testList = this.studyList;
            this.startTiming();
          });
        });
      } else if (this.testTypeCode == 1) {
        // 生成练习测试列表
        this.createPriticeList().then(() => {
          preloader(this.practiceList, () => {
            this.testList = this.practiceList;
            this.startTiming();
          });
        });
      } else {
        // 生成正式测试列表
        this.createNormalList().then(() => {
          preloader(this.normalList, () => {
            this.testList = this.normalList;
            this.startTiming();
          });
        });
      }
    },
    // 倒计时三分钟
    threeMinDown() {
      var that = this;
      that.countDownStr = "休息一下";
      var maxtime = 3 * 60;
      var minutes = 0;
      var seconds = 0;
      var timer = setInterval(function () {
        if (maxtime >= 0) {
          minutes = Math.floor(maxtime / 60);
          seconds = Math.floor(maxtime % 60);
          that.countDownStr = `0${minutes}:${seconds < 10 ? "0" + seconds : seconds
            }`;
          --maxtime;
        } else {
          that.countDownStr = "";
          that.crossShow = false;
          this.timingShow = false;
          clearInterval(timer);
        }
      }, 1000);
    },
  },
  destroyed() {
    clearInterval(this.timingFlag);
    clearInterval(this.timer2);
  },
};
</script>

<style scoped>
.butt {
  width: 100px;
  text-align: center;
  border: 1px solid rgb(87, 172, 187);
  opacity: 1;
  border-radius: 10px;
}

.bgAdd {
  width: 150px;
  height: 400px;
  background: url("../../assets/congnitiveAblitity/whiteFlag-new.png") no-repeat center;
  position: absolute;
  top: 25%;
  left: 50%;
  margin-left: -75px;
}

.activeTask {
  width: 100%;
  height: 100%;
  background: url("../../assets/congnitiveAblitity/rememberAbilityTask.png") no-repeat center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.timingBox {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: black;
  font-size: 70px;
  text-align: center;
  line-height: 100px;
  margin: 0 auto;
  z-index: 10;
}

/* .active-img {
  position: absolute;
  width: 450px;
  height: 450px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
} */
.btn-content {
  text-align: center;
  position: absolute;
  left: 50%;
  transform: translate(-50%);
  margin-top: 26px;
  z-index: 1000;
}

.scaleName {
  margin-top: 70px;
  background-size: cover;
}

.scaleButton {
  margin-top: 20px;
  margin-bottom: 20px;
  background-size: cover;
  background: rgb(87, 172, 187);
  border: 2px solid rgb(255, 255, 255);
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
  opacity: 1;
  border-radius: 39px;
  color: #ffffff;
}

.steering {
  width: 50%;
  position: absolute;
  bottom: 20%;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: space-between;
}

.steering .left {
  width: 60px;
  height: 60px;
  background: url(../../assets/left.png) no-repeat center;
}

.steering .right {
  width: 60px;
  height: 60px;
  background: url(../../assets/right.png) no-repeat center;
  margin-left: 15px;
}

.guider {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: rgba(0, 0, 0, 0.75);
}

.addImg {
  width: 40%;
  height: auto;
  z-index: 1000;
}

.shape_glass {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  height: auto;
  margin: 5vh auto 0;
}

.active {
  position: relative;
}

.active:after {
  background-color: #2ea598;
}

/* 设置动画后颜色 */
.active:before {
  background-color: rgba(0, 168, 253, 0.2);
}

/* 设置动画 */
.active:before,
.active:after {
  content: "";
  width: 80px;
  height: 40px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -40px;
  margin-top: -20px;
  border-radius: 10%;
  animation: warn 1.5s ease-out 0s infinite;
}

@keyframes warn {
  0% {
    transform: scale(1.3);
    opacity: 0.6;
  }

  50% {
    transform: scale(1.4);
    opacity: 0.3;
  }

  100% {
    transform: scale(1.5);
    opacity: 0.1;
  }
}

.txt {
  width: 300px;
  font-weight: PingFang-SC-Medium;
  margin: 0 auto;
  font-size: 16px;
  color: #ffffff;
  position: absolute;
  left: 50%;
  top: 70%;
  transform: translateX(-50%);
  z-index: 1000;
}

.explain {
  padding: 6px 8px;
  border: 2px solid #0abdc4;
  border-radius: 5px;
}

.block {
  width: 30%;
  margin: 7vw auto 0;
}

.block .slider {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.block .slider i {
  font-size: 18px;
  margin-right: 5px;
}

.el-slider {
  width: 80%;
  margin-left: 20px;
}

.el-rate {
  width: 70%;
  margin-left: 40px;
}

.choose {
  color: #19b381;
  border: 2px solid #19b381;
}</style>
