<template>
  <div>
    <!-- LOGO  -->
    <div class="desc_wrap" v-if="!testResultStr">
      <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;
              left: 50%;
              transform: translateX(-50%);
            "
          >
            <el-button
              class="start"
              type="primary"
              v-if="buttonShow"
              @click="startTest()"
              >{{ buttonName }}</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div style="width: 650px; margin: 20px auto; line-height: 2">
      <p
        v-show="testResultStr"
        style="margin-top: 20%; font-size: 30px; text-align: center"
      >
        {{ testResultStr }}
      </p>
    </div>
    <div
      v-if="testFlag"
      :class="{ testMainDivMove: !testState, activeTaskMove: testState }"
      class="txt-center"
    >
      <div class="taskHead">
        <div class="scale" @click.stop="screen">
          <img src="../../assets/small-big.png" alt="" />
        </div>
        <el-progress
          class="main_progress"
          :text-inside="true"
          :format="format"
          :stroke-width="24"
          :percentage="(imgIndex / 72) * 100"
          v-if="testTypeCode == 1"
          style="width: 50%"
        ></el-progress>
      </div>
      <div class="glass">
        <p v-show="countDownShow" class="countdownStr">
          {{ countDownStr }}
        </p>
        <img
          v-show="showDuckEgg"
          rel="preload"
          :src="examImgUrl"
          alt=""
          class="shapeImg"
        />
        <img
          v-show="showWhiteFlag"
          src="../../assets/congnitiveAblitity/whiteFlag-new.png"
          alt=""
          class="addImg"
        />
      </div>
    </div>
  </div>
</template>
<script>
import cognitiveAbilityTaskList from "@/assets/data/cognitiveAbilityData.js";
import { oSessionStorage, preloader } from "@/utils/utils";
import screenfull from "screenfull";

export default {
  data() {
    return {
      userId: "",
      userTestResult: {},
      imgUrl: "",
      examImgUrl: "",
      taskId: "", // 认知任务id
      testFlag: false,
      testState: false,
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: "", //认知任务详情
      buttonShow: true, // 控制按钮显示吟唱
      buttonName: "开始测试", // 正式测试  // 重新练习
      testTypeCode: 0, // 0-练习测试 1-正式测试 2-重新测试
      imgIndex: 0,
      userTestPicList: [
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_10_Noise_0.1_1.gif"),
          imgDirection: 39,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_10_Noise_0.1_2.gif"),
          imgDirection: 39,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_80_Noise_0.1_1.gif"),
          imgDirection: 38,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_80_Noise_0.1_2.gif"),
          imgDirection: 38,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_100_Noise_0.1_1.gif"),
          imgDirection: 38,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_100_Noise_0.1_2.gif"),
          imgDirection: 38,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_350_Noise_0.1_2.gif"),
          imgDirection: 39,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
        {
          imgUrl: require("../../assets/congnitiveAblitity/movementPerception/practice/Coherent_Motion_Dist_0.3_MotDegree_350_Noise_0.1_1.gif"),
          imgDirection: 39,
          userClickDirection: "",
          dist: 0.3,
          noise: 0.1,
        },
      ], //用户点击图片列表
      showImage: true,
      difficultList: [10], //[10,30,45,60,90]
      testPicCount: 0, //测试数目
      userRightClickDirection: "", //测试者应该点击的方向
      userRightResponseCount: 0, //测试者反应正确的次数
      showWhiteFlag: false,
      showDuckEgg: false,
      countDownTime: 6, //开始前的倒计时
      countDownStr: "开始测试",
      countDownShow: true,
      testTunrnCount: 0, //正式测试轮数
      testEndFlag: false, //测试结束标志
      testResultStrShow: false, //测试结果展示
      testResultStr: "", //测试成绩
      userCanClick: false, //用户标识用户单次刺激只能点击一次
      motDegreeList: [
        { key: 10, value: 39 },
        { key: 350, value: 39 },
        { key: 80, value: 38 },
        { key: 100, value: 38 },
        { key: 170, value: 37 },
        { key: 190, value: 37 },
        { key: 280, value: 40 },
        { key: 260, value: 40 },
      ], //水平10 350  垂直 80 100
      noiseList: [0.1, 0.3, 0.5],
      distList: [0.12, 0.1, 0.08],
      testPicShowTimeOut: "", //控制显示的延时器
      testPicShowControlTimeOut: "",
      myInterval: "", //控制倒计时的定时器
      diff: 0,
      dist: 0,
      noise: 0,

      oldSecond: 0, //定义时，分，秒，毫秒并初始化为0；
      oldMillSecond: 0,
      newSecond: 0,
      newMillSecond: 0, //秒
      second: 0,
      millSecond: 0,

      userResponseRecords: [], //用户测试记录
    };
  },
  // 页面初始化函数
  created() {
    this.taskId = this.$route.query.taskId;
    this.init();
    // this.startTest();
  },
  mounted: function () {
    var _this = this;
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      ////键盘按键判断:左箭头-37;上箭头-38；右箭头-39;下箭头-40
      if (40 >= key && key >= 37) _this.userClick(key);
    };
  },
  destroyed() {
    clearInterval(this.myInterval);
    clearTimeout(this.testPicShowTimeOut);
    clearTimeout(this.testPicShowControlTimeOut);
  },
  methods: {
    init() {
      this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
    },
    format(percentage) {
      return percentage === 100 ? "测试已完成" : "任务进度";
    },
    getNowTime() {
      this.oldSecond = new Date().getSeconds();
      this.oldMillSecond = new Date().getMilliseconds();
      // console.log("老时间为："+this.oldSecond+":"+this.oldMillSecond)
    },
    computeTime() {
      this.newSecond = new Date().getSeconds();
      this.newMillSecond = new Date().getMilliseconds();
      // console.log("新时间为："+this.newSecond+":"+this.newMillSecond)

      if (
        this.newSecond > this.oldSecond &&
        this.newMillSecond > this.oldMillSecond
      ) {
        this.second = this.newSecond - this.oldSecond;
        this.millSecond = this.newMillSecond - this.oldMillSecond;
        console.log("时间差为：" + this.second + ":" + this.millSecond);
      } else if (
        this.newSecond < this.oldSecond &&
        this.newMillSecond > this.oldMillSecond
      ) {
        this.second = this.newSecond + 60 - this.oldSecond;
        this.millSecond = this.newMillSecond - this.oldMillSecond;
        console.log("时间差为：" + this.second + ":" + this.millSecond);
      } else if (
        this.newSecond > this.oldSecond &&
        this.newMillSecond < this.oldMillSecond
      ) {
        this.second = this.newSecond - 1 - this.oldSecond;
        this.millSecond = this.newMillSecond + 1000 - this.oldMillSecond;
        console.log("时间差为：" + this.second + ":" + this.millSecond);
      } else if (
        this.newSecond < this.oldSecond &&
        this.newMillSecond < this.oldMillSecond
      ) {
        this.second = this.newSecond + 59 - this.oldSecond;
        this.millSecond = this.newMillSecond + 1000 - this.oldMillSecond;
        console.log("时间差为：" + this.second + ":" + this.millSecond);
      } else if (
        this.newSecond == this.oldSecond &&
        this.newMillSecond > this.oldMillSecond
      ) {
        this.second = this.newSecond - this.oldSecond;
        this.millSecond = this.newMillSecond - this.oldMillSecond;
        console.log("时间差为：" + this.second + ":" + this.millSecond);
      }
    },
    userClick(clickFlag) {
      // console.log("进入了userClick方法")
      let Obj = {
        // index:'',
        // diff:'',
        // direction:'',
        // userResponse:'',
        // responseTime: ''
      };

      if (this.countDownShow) {
        return;
      }

      if (this.userCanClick == true) {
        this.computeTime();
        Obj = {};
        Obj.index = this.imgIndex;
        Obj.diff = this.diff;
        Obj.dist = this.dist;
        Obj.noise = this.noise;
        if (this.userRightClickDirection == 37) {
          Obj.direction = "left";
        } else if (this.userRightClickDirection == 38) {
          Obj.direction = "up";
        } else if (this.userRightClickDirection == 39) {
          Obj.direction = "right";
        } else if (this.userRightClickDirection == 40) {
          Obj.direction = "down";
        }
        if (clickFlag == 37) {
          Obj.userResponse = "left";
        } else if (clickFlag == 38) {
          Obj.userResponse = "up";
        } else if (clickFlag == 39) {
          Obj.userResponse = "right";
        } else if (clickFlag == 40) {
          Obj.userResponse = "down";
        }

        Obj.responseTime = this.second * 1000 + this.millSecond;
        this.userResponseRecords.push(Obj);
      }

      this.showWhiteFlag = true;
      this.showDuckEgg = false;
      if (
        this.userRightClickDirection == clickFlag &&
        this.userCanClick == true
      ) {
        console.log("正确了  反应正确数加一");
        this.userRightResponseCount++;
        this.userCanClick = false;
      }
      if (
        this.userRightClickDirection != clickFlag &&
        this.userCanClick == true
      ) {
        console.log("错了 ");
        this.userCanClick = false;
      }
      if (this.imgIndex == this.userTestPicList.length) {
        this.testEndFlag = true;
      }
    },
    screen() {
      // 如果不允许进入全屏，发出不允许提示
      // if (!screenfull.isEnabled) {
      //   this.$message("您的浏览器不能全屏");
      //   return false;
      // }
      screenfull.toggle();
    },
    startTest() {
      if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        this.$message.error("请先登录！");
        return;
      }
      screenfull.request();
      this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      if (this.testTypeCode == 1) {
        this.countDownStr = "马上开始！";
        this.imgIndex = 0;
        this.countDownTime = 6;
        this.testEndFlag = false;
        this.showWhiteFlag = false;
        this.showDuckEgg = false;
        this.userTestPicList = [];
        this.userResponseRecords = [];
      }
      this.countDownShow = true;
      this.userTestPicListCreate();
      // 预加载图片后开始测试
      preloader(this.userTestPicList, () => {
        this.testFlag = true;
        this.testState = true;
        this.countDown();
      });
    },
    // format(percentage) {
    //   return percentage === 100 ? "测试已完成" : "任务进度";
    // },
    showTargetNow() {
      let Obj = {};
      // 练习间隔2~4，正式测试2~12；
      //var time = Math.round(Math.random()*400) + 800;
      this.testPicShowTimeOut = setTimeout(() => {
        this.showWhiteFlag = true;
        this.showDuckEgg = false;
        console.log("用户测试记录如下：");
        console.log(this.userResponseRecords);
        if (this.userCanClick == true) {
          Obj = {};
          Obj.index = this.imgIndex;
          Obj.diff = this.diff;
          Obj.dist = this.dist;
          Obj.noise = this.noise;
          if (this.userRightClickDirection == 37) {
            Obj.direction = "left";
          } else if (this.userRightClickDirection == 38) {
            Obj.direction = "up";
          } else if (this.userRightClickDirection == 39) {
            Obj.direction = "right";
          } else if (this.userRightClickDirection == 40) {
            Obj.direction = "down";
          }

          Obj.userResponse = "";
          Obj.responseTime = 3000;
          this.userResponseRecords.push(Obj);
          this.userCanClick = false;
        }
        this.testPicShowControlTimeOut = setTimeout(() => {
          if (this.testEndFlag) {
            console.log("进入了结束标志方法");
            clearTimeout(this.testPicShowTimeOut);
            clearTimeout(this.testPicShowControlTimeOut);
            this.computeScore();
            if (this.testTypeCode == 0) {
              console.log(this.userResponseRecords);
            }
          } else {
            this.userRightClickDirection =
              this.userTestPicList[this.imgIndex].imgDirection;
            this.diff = this.userTestPicList[this.imgIndex].diff;
            this.dist = this.userTestPicList[this.imgIndex].dist;
            this.noise = this.userTestPicList[this.imgIndex].noise;

            this.examImgUrl = this.userTestPicList[this.imgIndex].imgUrl;
            this.showWhiteFlag = false;
            this.showDuckEgg = true;
            this.userCanClick = true;
            this.imgIndex++;
            console.log(this.imgIndex);
            console.log("正确的方向是");
            console.log(this.userRightClickDirection);
            // console.log("imgIndex:"+this.imgIndex)
            // if (this.imgIndex == this.userTestPicList.length) {
            // if (this.imgIndex == 10) {
            //   this.testEndFlag = true;
            // }
            if (this.imgIndex == this.userTestPicList.length) {
              this.testEndFlag = true;
            }
            this.showTargetNow();
            this.getNowTime();
          }
        }, 1000);
      }, 3000);
    },
    testEnd() {
      this.testState = false;
      this.radioShow = false;
      this.examImgUrl = "";
      this.testFlag = false;
      this.$message({
        message: "测试结束！",
        type: "success",
      });
      this.buttonName = "结果保存";
      this.buttonShow = true;
    },
    computeScore() {
      screenfull.exit();
      if (this.testTypeCode == 0) {
        console.log("testPicCount" + this.testPicCount);
        console.log("userRightResponseCount" + this.userRightResponseCount);
        if (this.testPicCount == this.userRightResponseCount) {
          this.testFlag = false;
          this.testState = false;
          this.testTypeCode = 1;
          this.buttonName = "正式测试";
          this.userRightResponseCount = 0;
          this.buttonShow = true;
          this.$message({
            message: "测试通过！",
            type: "success",
          });
        } else {
          this.testFlag = false;
          this.testState = false;
          this.userRightResponseCount = 0;
          this.buttonName = "重新测试";
          this.imgIndex = 0;
          this.countDownTime = 10;
          this.testEndFlag = false;
          this.showWhiteFlag = false;
          this.showDuckEgg = false;
          this.userResponseRecords = [];
          //this.userTestPicList = []
          this.buttonShow = true;
          this.countDownStr = "练习马上开始！";
          this.$message({
            message: "练习测试不达标，请您重新进行练习测试！",
            type: "warning",
          });
        }
      } else {
        this.testTunrnCount++;
        if (this.testTunrnCount < 1) {
          this.startTest();
        } else {
          let userScore = parseFloat(
            (this.userRightResponseCount /
              (this.testTunrnCount * this.testPicCount)) *
              100
          ).toFixed(2);
          this.testFlag = false;
          this.testState = false;
          this.buttonShow = false;
          this.$http.post(
            `/cognize/MOVEMENT_CHILD`,
            {
              userId: this.userId,
              userScore: userScore + "%",
              userResponseRecords: this.userResponseRecords,
              testPlanId: this.$route.query.testPlanId || "",
            },
            (res) => {
              this.$message({
                message: "测试结束！",
                type: "success",
              });
              this.goTestResult(res.data);
            }
          );
        }
      }
    },
    userTestPicListCreate() {
      let imgObj = {
        // imgUrl:'',
        // imgDirection:'',
        // userClickDirection:''
      };

      if (this.testTypeCode == 1) {
        //随机呈现20张难度不同的图片
        let imgIndexList = this.getRandomNumber(2, 5);
        // noiseList:[0.3,0.5,0.7],
        // distList:[0.1,0.06,0.08],
        for (let i = 0; i < this.motDegreeList.length; i++) {
          for (let j = 0; j < this.noiseList.length; j++) {
            //noise
            for (let k = 0; k < this.distList.length; k++) {
              //dist
              imgObj = {};
              imgObj.imgUrl = require("../../assets/congnitiveAblitity/movementPerception/Coherent_Motion_Dist_" +
                this.distList[k] +
                "_MotDegree_" +
                this.motDegreeList[i].key +
                "_Noise_" +
                this.noiseList[j] +
                "_" +
                (Math.floor(Math.random() * 2) + 1) +
                ".gif");
              imgObj.imgDirection = this.motDegreeList[i].value;
              imgObj.userClickDirection = "";
              imgObj.diff = this.motDegreeList[i].key;
              imgObj.dist = this.distList[k];
              imgObj.noise = this.noiseList[j];
              this.userTestPicList.push(imgObj);
            }
          }
        }
      }
      this.shuffle(this.userTestPicList);
      this.testPicCount = this.userTestPicList.length;
      console.log(this.userTestPicList);
    },
    getRandomNumber(size, maxNumber) {
      let numberList = [];
      for (var i = 0; i < size; i++) {
        numberList.push(Math.floor(Math.random() * maxNumber) + 1);
      }
      return numberList;
    },
    countDown() {
      // 测试时间倒计时

      this.myInterval = setInterval(() => {
        this.countDownTime--;
        this.countDownStr = this.countDownTime;
        console.log(this.countDownTime);
        if (this.countDownTime == 3) {
          this.showTargetNow();
        }
        if (this.countDownTime == 0) {
          this.countDownShow = false;
          this.showWhiteFlag = true;
          // 清除定时器
          clearInterval(this.myInterval);
          this.countDownTime = 6;
        }
      }, 1000);
    },
    shuffle(arr) {
      var i = arr.length,
        t,
        j;
      while (i) {
        j = Math.floor(Math.random() * i--);
        t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
      }
    }
  },
};
</script>
<style scoped>
.testMainDivMove {
  margin: 0 auto;
  margin-top: 10px;
  background: black;
  background-size: cover;
  /* text-align:center; */
  width: 500px;
  height: 300px;
  /* object-fit:fill; */
}

.activeTaskMove {
  background: url(../../assets/congnitiveAblitity/shapeIntuition.png) no-repeat
    center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

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

.scaleButton {
  margin-top: 20px;
  margin-bottom: 20px;
  background-size: cover;
}

.imgBox {
  font-size: 50px;
  color: black;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.shapeImg {
  width: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.addImg {
  width: 71px;
  width: 71px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
