<!-- 精神运动警觉度（成瘾版） -->
<template>
  <div>
    <!-- LOGO  -->
    <div class="desc_wrap" v-if="!testResultDivShow">
      <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-html="subjectInfo.testDescription"></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 type="primary" class="start" @click="startTest()">{{
              buttonName
            }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-if="testResultDivShow" class="coginitiveTestResultDiv">
      <p v-if="testResultDivShow" class="testResultStr" style="margin-top: 5%">
        超过0.5秒的比例:{{ pass05SecRate }}%
      </p>
      <p v-if="testResultDivShow" class="testResultStr">
        超过1秒的比例:{{ pass1SecRate }}%
      </p>
      <p v-if="testResultDivShow" class="testResultStr">
        平均时长:{{ severalTime }}(ms)
      </p>
    </div>
    <div
      v-if="testFlag"
      :class="{ testMainDiv: !testState, activeTask: testState }"
      @click="userClick()"
    >
      <div class="taskHead">
        <div class="scale" @click.stop="scaleScreen">
          <img src="../../assets/small-big.png" alt="" />
        </div>
        <el-progress
          class="main_progress"
          v-if="testTypeCode == 1"
          :text-inside="true"
          :format="format"
          :stroke-width="24"
          :percentage="((50 - testCount) / 50) * 100"
          style="width: 50%"
        ></el-progress>
      </div>
      <div class="glass_wrap">
        <div class="glass">
          <div class="cognitiveTask" v-if="divShow">
            <img :src="imgList[currentIndex].imgUrl" alt="" />
          </div>
          <p class="countdownStr" v-show="showCountDown">
            {{ countDownStr }}
          </p>
        </div>
      </div>
    </div>
    <div
      style="
        text-align: center;
        padding-bottom: 2rem;
        display: block;
        margin-top: 3%;
      "
    >
      <!-- <el-button
          class="scaleButton"
          type="primary"
          v-if="buttonShow"
          @click="startTest()"
          >{{ buttonName }}</el-button
        > -->
      <el-button
        class="scaleButton"
        type="primary"
        v-if="saveFlag"
        @click="resultSave()"
        >结果保存</el-button
      >
    </div>
  </div>
</template>
  <script>
import cognitiveAbilityTaskList from "@/assets/data/cognitiveAbilityData.js";
import screenfull from "screenfull";
import { oSessionStorage, preloader } from "@/utils/utils";
import { relevant, irrelevant } from "@/utils/addictionImg";

export default {
  data() {
    return {
      userId: "",
      countDownTime: 20, //倒计时时长
      testCount: 50, //正式测试时50次结束
      userResponseMilliSeconds: 0, //当前刺激用户反应时间
      userTestAnswer: [], //用户测试反应记录
      taskId: "", // 认知任务id
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: "", //认知任务详情
      divShow: false, // 控制黑框显示隐藏
      buttonShow: true, // 控制按钮显示吟唱
      passTestExam: false, //练习测试通过标识
      testType: "练习测试", // 正式测试
      testFlag: false,
      buttonName: "开始练习", // 正式测试  // 重新练习
      testTypeCode: 0, // 0-练习测试 1-正式测试 2-重新测试
      startMilliSeconds: 0, //div出现时的毫秒数
      divShowInteval: "", //控制div显示的定时器
      countDownInterval: "", //倒计时定时器
      myInterval: null,
      qualifiedCount: 0, //点击合格数
      unQualifiedCount: 0, //点击不合格数
      cuntdownMinMilliSeconds: 2000, //练习时   2-4秒  2000
      cuntdownMaxMilliSeconds: 4000, //正式测试时2-12秒
      testState: false, // 开始测试
      testResultDivShow: false, //控制结果展示隐藏
      pass05SecRate: "", //超过0.5秒的比例
      pass1SecRate: "", //超过1秒的比例
      severalTime: "", //平均时长(ms)
      showCountDown: true,
      countDownStr: "练习马上开始！",
      redayTime: 5,
      imgList: [...relevant, ...irrelevant],
      currentIndex: 0
    };
  },
  // 页面初始化函数
  created() {
    this.taskId = this.$route.query.taskId;
    this.init(this.taskId);
    window.addEventListener(
      "popstate",
      function (e) {
        this.divShow = false;
        this.testState = false;
        this.testFlag = false;
        clearInterval(this.divShowInteval);
        clearInterval(this.countDownInterval);
      },
      false
    );
  },
  mounted() {
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key === 122) {
        e.preventDefault();
        screenfull.toggle();
      }
    };
  },
  destroyed() {
    clearInterval(this.divShowInteval);
    clearInterval(this.myInterval);
  },
  methods: {
    init(taskId) {
      // this.subjectInfo = cognitiveAbilityTaskList[taskId];
      this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
      this.imgUrl = this.subjectInfo.imageUrl;
      this.imgList = this.shuffle(this.imgList);
    },
    format(percentage) {
      return percentage === 100 ? "测试已完成" : "任务进度";
    },
    screen() {
      screenfull.toggle();
    },
    userClick() {
      //用户点击动作
      if (this.divShow) {
        this.userResponseMilliSeconds =
          new Date().getTime() - this.startMilliSeconds;
        //console.log(this.userResponseMilliSeconds)
        if (this.userResponseMilliSeconds > 500) {
          this.unQualifiedCount++;
        } else {
          this.qualifiedCount++;
        }
        this.divShow = false;
      } else {
        this.unQualifiedCount++;
        this.$message.error("错误点击！");
      }
    },
    startTest() {
      if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        this.$message.error("请先登录！");
        return;
      }
      this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      this.startTestTime = new Date().getTime();
      this.testState = true;
      this.buttonShow = false;
      this.testFlag = true;
      this.screen();
      this.showCountDown = true;
      if (this.testTypeCode == 0) {
        this.countDownStr = "练习马上开始！";
      } else {
        this.countDownStr = "测试马上开始！";
      }
      preloader(this.imgList, () => {
        // 测试准备倒计时
        var countDown2 = setInterval(() => {
          if (this.redayTime == 0) {
            // 测试开始
            this.countDownStr = "开始";
            this.redayTime = 5;
            setTimeout(() => {
              this.showCountDown = false;
            }, 1000);
            clearInterval(countDown2);
            if (this.testTypeCode == 0) {
              this.countDownTime = 20;
              this.countDown();
            }
            this.divShowInteval = setInterval(() => {
              this.divRandomShow();
              this.currentIndex ++;
              if (this.testTypeCode == 1) {
                this.testCount--;
                if (this.testCount == 0) {
                  //计算测试结果
                  this.computeScore();
                  //清除div控制定时器
                  clearInterval(this.divShowInteval);
                }
              }
            }, Math.floor(Math.random() * (this.cuntdownMaxMilliSeconds - this.cuntdownMinMilliSeconds + 1)) + this.cuntdownMinMilliSeconds);
          } else {
            this.countDownStr = this.redayTime;
            this.showCountDown = true;
            this.redayTime--;
          }
        }, 1000);
      });
    },
    testEnd() {
      //clearInterval(divShowInteval);
      this.testState = false;
      this.testFlag = false;
      this.$message({
        message: "测试结束！",
        type: "success",
      });
    },
    computeScore() {
      this.screen();
      //计算练习成绩
      if (this.testTypeCode == 0) {
        let qualifiedRate =
          (this.qualifiedCount * 100) /
          (this.unQualifiedCount * 100 + this.qualifiedCount * 100);
        if (qualifiedRate >= 0.6) {
          this.$message({
            message: "通过练习测试，开始进行正式测试！",
            type: "success",
          });
          this.subjectInfo.testDescription = this.subjectInfo.description;
          this.passTestExam = true;
          this.buttonName = "正式测试";
          this.buttonShow = true;
          this.testType = "正式测试";
          this.testState = false;
          this.testFlag = false;
          this.testTypeCode = 1;
          this.cuntdownMaxMilliSeconds = 6000;
        } else {
          this.divShow = false;
          this.passTestExam = false;
          this.buttonName = "重新练习";
          this.buttonShow = true;
          this.testState = false;
          this.testFlag = false;
          this.$message({
            message: "测试未通过，请点击'重新测试'按钮继续练习！",
            type: "warning",
          });
        }
      } else {
        this.testState = false;
        this.testFlag = false;
        //结果保存
        this.userResponserSave();
        //this.userTestAnswer.push({key:60-this.testCount,value:this.userResponseMilliSeconds==0?new Date()-this.startMilliSeconds:this.userResponseMilliSeconds})
        this.$message({
          message: "测试结束！",
          type: "success",
        });
        this.buttonShow = false;
      }
    },
    countDown() {
      // 测试时间倒计时
      this.myInterval = setInterval(() => {
        this.countDownTime--;
        if (this.countDownTime == 0) {
          //计算测试结果
          this.computeScore();
          // 清除定时器
          clearInterval(this.myInterval);
          this.countDownTime = 0;
          this.currentIndex = 0;
          //清除div控制定时器
          clearInterval(this.divShowInteval);
          screenfull.toggle();
        }
      }, 1000);
    },
    divRandomShow() {
      if (this.testTypeCode == 1) {
        this.userTestAnswer.push({
          key: 50 - this.testCount,
          value:
            this.userResponseMilliSeconds == 0
              ? new Date() - this.startMilliSeconds
              : this.userResponseMilliSeconds,
        });
      }
      this.divShow = !this.divShow;
      this.userResponseMilliSeconds = 0;
      this.startMilliSeconds = new Date().getTime();
      setTimeout(() => {
        this.divShow = false;
      }, 1000);
    },
    userResponserSave() {
      this.$http.post(
        `/cognize/ALERTNESS_ADDICTION`,
        {
          userId: this.userId,
          data: this.userTestAnswer,
          testPlanId: this.$route.query.testPlanId,
        },
        (response) => {
          // this.$router.push({
          //   name: "TestResult",
          //   params: {
          //     result: [
          //       {
          //         name: "超过0.5秒的比例",
          //         value: response.data["超过0.5秒的比例"],
          //       },
          //       {
          //         name: "超过1秒的比例",
          //         value: response.data["超过1秒的比例"],
          //       },
          //       {
          //         name: "平均时长(ms)",
          //         value: response.data["平均时长(ms)"],
          //       },
          //     ],
          //   },
          // });
           if(response && response.code == 200){
               this.goTestResult(response.data);
           } else {
               this.$message({
                   message: response.msg,
                   type: "error",
               });
           }

        }
      );
    },
    // 缩放屏幕
    scaleScreen() {
      screenfull.toggle();
    },
    // 实现数组随机排序
    shuffle(arr) {
      var len = arr.length;
      for (var i = 0; i < len; i++) {
        var a = parseInt(Math.random() * len);
        var temp = arr[a];
        arr[a] = arr[i];
        arr[i] = temp;
      }
      return arr;
    },
  },
};
</script>
  <style scoped>
.coginitiveTestResultDiv {
  margin: 0 auto;
  /* margin-top: 2%; */
  margin-left: 33%;
  /* background: black; */
  background-size: cover;
  /* text-align:center; */
  width: 500px;
  height: 150px;
}
.testResultStr {
  color: red;
  text-align: left;
  font-size: 30px;
  margin-top: 2%;
  margin-left: 15%;
}

.testMainDiv {
  margin: 0 auto;
  margin-top: 10px;
  background: gray;
  background-size: cover;
  /* text-align:center; */
  width: 500px;
  height: 300px;
  /* object-fit:fill; */
}

.activeTask {
  /* background: linear-gradient(180deg, #57acbb 0%, #6190db 100%); */
  background: url(../../assets/congnitiveAblitity/alert.png) no-repeat center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
}

.cognitiveTask {
  display: flex;
  align-items: center;
  width: 347px;
  height: 351px;
  background: #000000;
  border-radius: 24px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.cognitiveTask img {
  width: 100%;
  height: auto;
}

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

.scaleButton {
  margin-top: 40px;
  margin-bottom: 20px;
  background-size: cover;
}
</style>
