<template>
  <div class="content-container">
    <div class="content-outline" v-if="!testResultDivShow">
      <div class="left_part">
        <div id="left_top" class="flex-row">
          <el-image class="setting" :src="require('@/assets/9551.png')" fit="cover" />
          <div class="text"> 操作提示：</div>
        </div>
        <div class="left-desc-80" v-html="subjectInfo.testDescription"></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: 0.156rem;
            left: 50%;
            transform: translateX(-50%);
          "
        >
          <el-button type="primary" class="start" @click="startTest()">{{
              buttonName
            }}</el-button>
        </div>
      </div>
    </div>

    <!-- LOGO  -->
    <!-- <h1 class="txt-center">
      {{ subjectInfo.name }}
      <h5>({{ testType }})</h5>
    </h1>

    <div
      v-if="!testResultDivShow"
      style="width: 650px; margin: 20px auto; line-height: 2"
    >
      <p style="text-align: left; text-indent: 2em">
        {{ subjectInfo.testDescription }}
      </p>
    </div> -->
    <div v-if="testResultDivShow" class="testResultDiv">
      <table class="test_result">
        <tr>
          <th>指标名称</th>
          <th>测试结果</th>
        </tr>
        <tr>
          <td>测试题目总数：</td>
          <td>{{ totalCount }}</td>
        </tr>
        <tr>
          <td>正确题目数：</td>
          <td>{{ rightCount }}</td>
        </tr>
        <tr>
          <td>测试成绩：</td>
          <td>{{ userScore }}</td>
        </tr>
      </table>
    </div>
    <div
      v-if="testFlag"
      :class="{ testMainDiv: !testState, activeTask: testState }"
    >
      <MainProgress v-if="testTypeCode === 1" :cur-percentage="(100 - countDownTime) / 100" />

      <div class="taskHead">
        <div class="scale" @click.stop="screenState">
          <img src="@/assets/small-big.png" alt="" />
        </div>
      </div>

      <!-- <h1 class="txt-center" style="color: rgb(231, 226, 226); font-size: 52px">
        {{ showSpanText }}
      </h1> -->
      <div v-if="answerButtonShow" style="" class="txt-center">
        <div align="center" style="padding-bottom: 20px; padding-top: 100px">
          <span class="bn-in"> {{ showSpanText }}</span>
        </div>
        <div class="add-mid">
          <div style="margin-top: 10px">
            <el-button class="oneBu bn-bottom" @click="userClick(1)">1</el-button>
            <el-button class="oneBu bn-bottom" @click="userClick(2)">2</el-button>
            <el-button class="bn-bottom" @click="userClick(3)">3</el-button>
          </div>
          <div style="margin-top: 10px">
            <el-button class="oneBu bn-bottom" @click="userClick(4)">4</el-button>
            <el-button class="oneBu bn-bottom" @click="userClick(5)">5</el-button>
            <el-button class="bn-bottom" @click="userClick(6)">6</el-button>
          </div>
          <div style="margin-top: 10px">
            <el-button class="oneBu bn-bottom" @click="userClick(7)">7</el-button>
            <el-button class="oneBu bn-bottom" @click="userClick(8)">8</el-button>
            <el-button class="bn-bottom" @click="userClick(9)">9</el-button>
          </div>
          <div style="margin-top: 10px">
            <el-button class="bn-bottom" @click="userClick(0)">0</el-button>
          </div>
        </div>
      </div>
    </div>
    <div style="text-align: center">
      <!-- <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>

    <go-back />
  </div>
</template>
<script>
import axios from "axios";
import cognitiveAbilityTaskList from "@/assets/data/cognitiveAbilityData.js";
import { oSessionStorage } from "@/utils/utils";
import screenfull from "screenfull";
import MainProgress from "@/components/MainProgress/index.vue";
import GoBack from "@/components/goBack/index.vue";
export default {
  components: {GoBack, MainProgress},
  data() {
    return {
      userId: "",
      testResult: {},
      countDownTime: 100, //倒计时时长
      testCount: 6,
      taskId: "", // 认知任务id
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: "", //认知任务详情
      answerButtonShow: false,
      buttonShow: true, // 控制按钮显示隐藏
      passTestExam: false, //练习测试通过标识
      testType: "练习测试", // 正式测试
      buttonName: "开始练习", // 正式测试  // 重新练习
      testTypeCode: 0, // 0-练习测试 1-正式测试 2-重新测试
      testFlag: false, //true继续测试，false结束测试
      countDownInterval: "", //倒计时定时器
      additionNumCount: 2, //当前轮需要计算的数字个数
      currentAnswer: 0, //当前题答案
      showSpanText: "", //显示题目文本
      totalCount: 0, //测试总次数
      rightCount: 0, //正确总次数
      rightCount2: 0, //n个数相加正确次数
      rightCount3: 0,
      rightCount4: 0,
      rightCount5: 0,
      rightCount6: 0,
      currentRoundRightCount: 0, //当前轮正确次数
      stepWidth: 1, //练习测试时步长为2，正式测试为1
      stepEndFlag: 6,
      testState: false,
      testResultDivShow: false, //控制测试结果显示
      testResultStr: "", //测试结果
      userScore: "", //用户总成绩
      rightThree: 0, //连续对3次
      wrongTwo: 0, //连续错两次
      rightCountList: [],//统计每个层级答对个数
    };
  },
  // 页面初始化函数
  created() {
    this.taskId = this.$route.query.taskId;
    this.init(this.taskId);
    this.divShow = false;
    this.testState = false;
    clearInterval(this.divShowInteval);
    clearInterval(this.countDownInterval);
  },
  destroyed() {
    clearInterval(this.divShowInteval);
    clearInterval(this.countDownInterval);
  },
  mounted: function () {
    var _this = this;
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key === 122) {
        e.preventDefault();
        screenfull.toggle();
      }
      if ((57 >= key && key >= 48) || (105 >= key && key >= 96))
        _this.userClick(window.event.key);
    };
  },
  methods: {
    screenState() {
      screenfull.toggle();
    },
    init(taskId) {
      // this.subjectInfo = cognitiveAbilityTaskList[taskId];
      this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
      this.imgUrl = this.subjectInfo.imageUrl;
    },
    userClick(answer) {
      //用户点击动作
      this.totalCount++;
      if (answer == this.currentAnswer) {
        if (this.testTypeCode == 1) {
          //正确次数
          this.rightCount++;
          //当前数字个数计算正确数加1
          this.nNumRightCount();
          //本轮正确次数
          this.currentRoundRightCount++;
          // if (
          //   this.additionNumCount <= 6 &&
          //   this.currentRoundRightCount == this.additionNumCount
          // ) {
          //   this.currentRoundRightCount = 0;
          //   this.additionNumCount =
          //     this.additionNumCount + 1 > 6 ? 6 : this.additionNumCount + 1;
          // }
          this.rightThree ++;
          this.wrongTwo = 0;
          if(this.rightThree >= 3 && this.wrongTwo == 0){
              this.additionNumCount ++;
              this.rightThree = 0;
              this.wrongTwo = 0;
          }

        } else {
          this.rightCount++;
          if (this.totalCount % 2 == 0) {
            this.additionNumCount =
              this.additionNumCount + 1 > 6 ? 6 : this.additionNumCount + 1;
          }
        }
      } else {
        //分练习时和正式测试时两种情况,练习测试时，不加处理

        //正式测试时要做降级处理
        if (this.testTypeCode == 1) {
          this.currentRoundRightCount = 0;
          // this.additionNumCount -= 1;
          // if (this.additionNumCount == 1) {
          //   this.additionNumCount = 2;
          // }
          this.rightThree = 0;
          this.wrongTwo ++;
          if(this.additionNumCount > 2 && this.rightThree == 0 && this.wrongTwo >= 2){
              this.additionNumCount --;
              this.rightThree = 0;
              this.wrongTwo = 0;
          }
        } else {
          if (this.totalCount % 2 == 0) {
            this.additionNumCount =
              this.additionNumCount + 1 > 6 ? 6 : this.additionNumCount + 1;
          }
        }
      }
      if (this.totalCount == 6 && this.testTypeCode == 0) {
        this.testEnd();
        this.testFlag = false;
        this.showSpanText = "";
        this.answerButtonShow = false;
        return;
      }
      //生成下一道题
      if (this.testFlag) {
        this.createComputeSpanText();
      }
    },
    format(percentage) {
      return percentage === 100 ? "任务已完成" : "任务进度";
    },
    screen() {
      // 如果不允许进入全屏，发出不允许提示
      // if (!screenfull.isEnabled) {
      //   this.$message("您的浏览器不能全屏");
      //   return false;
      // }
      screenfull.request();
    },
    screenExit() {
      // 如果不允许进入全屏，发出不允许提示
      // if (!screenfull.isEnabled) {
      //   this.$message("您的浏览器不能全屏");
      //   return false;
      // }
      screenfull.exit();
    },
    startTest() {
      if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        alert("请先登录！");
        return;
      }
      this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      //开始测试
      this.createComputeSpanText();
      // 按钮隐藏
      this.testFlag = true;
      this.buttonShow = false;
      this.answerButtonShow = true;
      this.testState = true;
      this.screen();
      //练习测试时进行倒计时，正式测试时进行测试测试校验
      if (this.testTypeCode == 1) {
        this.countDown();
      }
    },
    testEnd() {
      this.screen();
      //计算练习成绩
      if (this.testTypeCode == 0) {
        if (this.totalCount == this.rightCount) {
          //通过测试
          //开始正式测试

          this.subjectInfo.testDescription = this.subjectInfo.testExplain;
          this.testTypeCode = 1;
          this.buttonName = "正式测试";
          this.testType = "正式测试";
          this.buttonShow = true;
          this.answerButtonShow = true;
          this.testState = false;
          this.$message({
            message: "通过练习测试，开始进行正式测试！",
            type: "success",
          });
          //this.pageDataInit()
        } else {
          //重新测试

          this.testTypeCode = 0;
          this.buttonName = "重新测试";
          this.buttonShow = true;
          this.testState = false;
          this.answerButtonShow = true;
          this.$message({
            message: "测试未通过，请点击'重新测试'按钮继续练习！",
            type: "warning",
          });
        }
        this.screenExit();
        this.pageDataInit();
      } else {
        this.screenExit();
        this.testState = false;
        this.getUserTestScore();
        this.$message({
          message: "测试结束！",
          type: "success",
        });
        this.buttonShow = false;
        this.answerButtonShow = false;
        this.showSpanText = "";
        //测试结束隐藏测试页面-liwenlong20220720
        this.testFlag = false;
      }
    },
    countDown() {
      // 测试时间倒计时
      let myInterval = setInterval(() => {
        this.countDownTime--;
        if (this.countDownTime == 0) {
          //计算测试结果
          this.testEnd();
          // 清除定时器
          clearInterval(myInterval);
          this.countDownTime = 0;
        }
      }, 1000);
    },
    createComputeSpanText() {
      //生成下一道题和答案
      this.testCount--;
      var tempSpanText = "";
      var additionResult = 0;
      for (var i = this.additionNumCount; i > 0; i--) {
        var tempNum = Math.floor(Math.random() * 10);
        additionResult += tempNum;
        tempSpanText += tempNum + "+";
      }
      this.showSpanText = tempSpanText.substr(0, tempSpanText.length - 1);
      this.currentAnswer = additionResult % 10;
    },
    nNumRightCount() {
      // switch (this.additionNumCount) {
      //   case 2:
      //     this.rightCount2++;
      //     break;
      //   case 3:
      //     this.rightCount3++;
      //     break;
      //   case 4:
      //     this.rightCount4++;
      //     break;
      //   case 5:
      //     this.rightCount5++;
      //     break;
      //   case 6:
      //     this.rightCount6++;
      //     break;
      //   default:
      //     break;
      // }
      let isIndex = this.rightCountList.findIndex(item => item.key == this.additionNumCount);
      if(isIndex !== -1){
          this.rightCountList[isIndex].value ++;
      }else {
          this.rightCountList.push({
              key: this.additionNumCount,
              value: 1
          })
      }

    },
    pageDataInit() {
      this.rightCount2 = 0;
      this.rightCount3 = 0;
      this.rightCount4 = 0;
      this.rightCount5 = 0;
      this.rightCount6 = 0;
      this.totalCount = 0;
      this.rightCount = 0;
      this.additionNumCount = 2;
      this.currentAnswer = 0;
      this.currentRoundRightCount = 0;
    },
    getUserTestScore() {
        console.log(this.rightCountList,"测试记录列表")
      this.testResult.userId = this.userId;
      this.testResult.total = this.totalCount;
      this.testResult.testPlanId = this.$route.query.testPlanId || "";
      // let data = [];
      // data.push({ key: 2, value: this.rightCount2 });
      // data.push({ key: 3, value: this.rightCount3 });
      // data.push({ key: 4, value: this.rightCount4 });
      // data.push({ key: 5, value: this.rightCount5 });
      // data.push({ key: 6, value: this.rightCount6 });
      // this.testResult.data = data;
      // this.userScore = parseFloat(
      //   Math.log2(
      //     this.rightCount2 * Math.pow(2, 0) +
      //       this.rightCount3 * Math.pow(2, 1) +
      //       this.rightCount4 * Math.pow(2, 2) +
      //       this.rightCount5 * Math.pow(2, 3) +
      //       this.rightCount6 * Math.pow(2, 4)
      //   )
      // ).toFixed(2);
      // this.testResult.score = this.userScore;

      this.testResult.data = this.rightCountList;
      let sum = 0;
      this.rightCountList.map((item) => {
          sum += item.value * Math.pow(2, item.key - 2)
      });
      this.testResult.score = sum == 0 ? 0 : parseFloat(Math.log2(sum)).toFixed(2);

      this.userTestResultSave();
    },
    userTestResultSave() {
      let that = this;
      // this.testResultDivShow = true;
      //跳转页面到结果页面

      this.$http.post(`/cognize/ADDITION`, this.testResult, (res) => {
        // that.$router.push({
        //   name: "TestResult",
        //   params: {
        //     result: [
        //       {
        //         name: "测试题目总数",
        //         value: that.totalCount,
        //       },
        //       {
        //         name: "正确题目数",
        //         value: that.rightCount,
        //       },
        //       {
        //         name: "测试成绩",
        //         value: this.testResult.score,
        //       },
        //     ],
        //   },
        // });
        // that.testState = false;
        // that.testFlag = false;
        this.goTestResult(res.data);
      });
    }
  },
};
</script>
<style scoped>
.testResultDiv {
  margin: 0 auto;
  /* margin-top: 10%; */
  margin-left: 33%;
  /* background: gray; */
  background-size: cover;
  /* text-align:center; */
  width: 500px;
  height: 100px;
}

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

.activeTask {
  background: url(../../assets/congnitiveAblitity/add-bg.png) no-repeat center;
  background-size: cover;
  /* background: gray; */
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.el-progress__text {
  color: black;
}
.scaleName {
  margin-top: 70px;
  background-size: cover;
}

.scaleButton {
  margin-top: 20px;
  margin-bottom: 20px;
  background-size: cover;
}
.add-mid {
  background: url('~@/assets/congnitiveAblitity/add-mid.png') no-repeat 0 0 / 100% 100%;
  height: 470px;
  width: 425px;
  margin: 20px auto 0;
}
h1 {
  font-size: 2em;
  margin: 0em 0 !important;
}
.oneBu {
  margin-right: 55px;
}
.bn-bottom {
  margin-top: 20px;
  width: 84px;
  height: 84px;
  background: rgb(87, 172, 187);
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.48);
  border-radius: 50%;
  opacity: 1;
  color: white;
  font-size: 28px;
}
.bn-in {
  border-radius: 14px;
  display: block;
  width: 500px;
  height: 54px;
  color: white;
  background-color: black;
  font-size: 32px;
  padding-top: 10px;
}
.aa {
  visibility: hidden;
}
</style>
