<template>
  <div class="app-container">
    <Header />
    <div class="main-container">
      <van-nav-bar
        :title="subjectInfo.name"
        left-arrow
        left-text=""
        @click-left="goBack"
      />
      <div v-if="!userFinalTestStrShow" class="explan">
        <!-- LOGO  -->
        <!--<h1>{{subjectInfo.name}}</h1>-->
        <div class="main-text-div">
          {{ subjectInfo.mobileTestDescription }}
        </div>
        <!--        <div>-->
        <!--          <p>{{ subjectInfo.mobileTestDescription }}</p>-->
        <!--        </div>-->
        <div v-if="buttonShow" class="btnArea">
          <van-button block round type="primary" @click="startTest()"
            >{{ buttonName }}
          </van-button>
        </div>
      </div>

      <div v-if="userFinalTestStrShow" class="t3">
        <p v-if="userFinalTestStrShow" class="t4">
          GO信号正确反应总时间（毫秒）：{{ goTotalResponseTime }}
        </p>
        <p v-if="userFinalTestStrShow" class="t5">
          GO信号平均反应时间（毫秒）：{{
            goTotalResponseTime == 0 ? 0 : severalGoResponseTime
          }}
        </p>
        <p v-if="userFinalTestStrShow" class="t5">
          NO-GO信号反应正确率（%）：{{ blackRightRate }}
        </p>
      </div>
      <div
        v-if="testFlag"
        :class="{ testMainDiv: !testState, activeTask: testState }"
        @click="userClick()"
      >
        <div class="taskHead">
          <div v-if="testTypeCode == 1" class="progress-content">
            <van-progress
              :percentage="percentage"
              color="#f2826a"
              pivot-text="任务进度"
            />
          </div>
        </div>
        <div class="glass">
          <span v-if="countDownSpanShow" class="countdownStr">{{
            countDownStr
          }}</span>
          <div
            v-if="divShow"
            :style="{ background: backgroundColor }"
            class="goNoGoTask txt-center"
          ></div>
        </div>
      </div>
      <div v-if="saveFlag" class="t6" @click="resultSave()">
        <van-button class="scaleButton" type="primary">结果保存</van-button>
      </div>
    </div>
  </div>
</template>
<script>
// import screenfull from "screenfull";
// import { oSessionStorage } from "../../utils/utils";
import Header from "@/components/header/index.vue";

export default {
  components: { Header },
  data() {
    return {
      userId: "",
      beginCount: false,
      countDownTime: 6, //倒计时时长
      countDownSpanShow: false, //8秒倒计时显示标志
      testTurnCount: 0, //正式测试轮数
      backgroundColor: "",
      bgImage: require("../../assets/congnitiveAblitity/whiteFlag.png"),
      backgroundList: ["red", "black", "yellow", "blue"],
      taskId: "", // 认知任务id
      greenFlagCount: 0,
      redFlagCount: 0,
      blueFlagCount: 0,
      blackFlagCount: 0,
      totalCount: 0, //共有多少个刺激
      singleTurnCount: 2, //每一轮多少个刺激
      rightClickCount: 0, //正确点击次数
      blackClickCount: 0, //黑色框点击次数（错误点击次数）
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: {}, //认知任务详情
      divShow: false, // 控制黑框显示隐藏
      buttonShow: true, // 控制按钮显示吟唱
      passTestExam: false, //练习测试通过标识
      testType: "练习测试", // 正式测试
      testFlag: false,
      buttonName: "开始练习", // 正式测试  // 重新练习
      testTypeCode: 0, // 0-练习测试 1-正式测试 2-重新测试
      startMilliSeconds: 0, //div出现时的毫秒数
      divShowInteval: "", //控制div显示的定时器
      myInterval: "",
      countDownInterval: "", //倒计时定时器
      qualifiedCount: 0, //点击合格数
      unQualifiedCount: 0, //点击不合格数
      cuntdownMinMilliSeconds: 2000, //练习时   2-4秒  2000
      cuntdownMaxMilliSeconds: 4000, //正式测试时2-12秒
      testState: false,
      goTotalResponseTime: 0, //Go信号总反应时常
      userCanClick: false, //用户是否可以进行点击
      currentBackgroundName: "",
      countDownStr: "练习马上开始！",
      userResponseRecords: [],
      userFinalTestStrShow: false,
      blackRightRate: 0, //NO-GO信号正确率
      severalGoResponseTime: 0, //go信号平均反应时间
      testPlanId: "",
      currentIndex: 0
    };
  },
  computed: {
    percentage() {
      return (this.currentIndex / this.totalCount) * 100;
    }
  },
  // 页面初始化函数
  created() {
    // this.taskId = this.$route.query.taskId;
    this.init();
  },
  destroyed() {
    clearInterval(this.divShowInteval);
    clearInterval(this.myInterval);
  },
  methods: {
    init() {
      this.testPlanId = this.$route.query.testPlanId || "";
      this.userId = JSON.parse(sessionStorage.getItem("userInfo")).id;
      this.subjectInfo = JSON.parse(sessionStorage.getItem("subjectInfo"));
      this.imgUrl = this.subjectInfo.imageUrl;
    },
    format(percentage) {
      return percentage === 100 ? "测试已完成" : "任务进度";
    },
    userClick() {
      //用户点击动作
      if (this.userCanClick) {
        this.userCanClick = false;
        let milliSecondsCount = new Date().getTime() - this.startMilliSeconds;
        this.userResponseRecords[
          this.currentIndex
        ].responseTime = milliSecondsCount;
        if (milliSecondsCount < 1500) {
          //正确反应
          if (this.backgroundColor == "black") {
            this.blackClickCount++;
          } else {
            this.rightClickCount++;
            this.goTotalResponseTime += milliSecondsCount;
          }
        }
      } else if (!this.userCanClick && this.userCanClick != false) {
        this.$toast("错误点击！");
      }
    },
    startTest() {
      //开始测试
      if (
        sessionStorage.getItem("userInfo") == "" ||
        sessionStorage.getItem("userInfo") == null
      ) {
        this.$toast("请先登录！");
        return;
      }
      if (this.testTypeCode == 1 && this.beginCount == false) {
        this.countDownStr = "马上开始！";
        this.beginCount = true;
      }
      //   screenfull.request();
      this.countDownSpanShow = true;
      this.pageDataInit();
      this.buttonShow = false;
      this.testState = true;
      this.backgroundColor = "";
      this.myInterval = setInterval(() => {
        this.countDownTime--;
        this.countDownStr = this.countDownTime;
        if (this.countDownTime == 0) {
          this.countDownStr = "开始！";
        }
        if (this.countDownTime == -1) {
          //清除定时器
          clearInterval(this.myInterval);
          this.countDownStr = "准备";
          this.countDownSpanShow = false;
          this.countDownTime = 6;
          this.backgroundColor = `url(${this.bgImage}) no-repeat center`;
          this.divShowInteval = setInterval(() => {
            //this.backgroundColor = ''
            this.divShow = true;
            this.divRandomShow();
          }, 2000);
        }
      }, 1000);
    },
    testEnd() {
      this.computeScore();
    },
    computeScore() {
      //计算练习成绩
      this.divShow = false;
      clearInterval(this.divShowInteval);
      if (this.testTypeCode == 0) {
        // 退出全屏
        // screenfull.exit();
        //练习测试
        let rightRate = parseFloat(
          (this.rightClickCount + this.singleTurnCount - this.blackClickCount) /
            this.totalCount
        ).toFixed(2);
        if (rightRate > 0.9) {
          this.passTestExam = true;
          this.testTypeCode = 1;
          this.testType = "正式测试";
          this.buttonName = "正式测试";
          this.singleTurnCount = 9;
          this.buttonShow = true;
          this.testState = false;
          this.testFlag = false;
          this.backgroundColor = "";
          this.rightClickCount = 0;
          this.blackClickCount = 0;
          this.subjectInfo.testDescription = this.subjectInfo.testExplain;
          //通过测试
          this.$toast("您已掌握测试规则，请点击正式测试按钮，进入正式测试！");
        } else {
          //重新练习
          this.rightClickCount = 0;
          this.blackClickCount = 0;
          this.buttonName = "重新测试";
          this.buttonShow = true;
          this.testState = false;
          this.testFlag = false;
          this.backgroundColor = "";
          this.$toast("测试未通过，请点击'重新测试'按钮继续练习！");
        }
        this.userResponseRecords = [];
        this.currentIndex = 0;
      } else {
        //正式测试
        //计算测试结果
        this.testTurnCount++;
        //console.log(this.testTurnCount)
        this.pageDataInit(); //页面数据初始化
        if (this.testTurnCount != 4) {
          this.countDownStr = "休息一下！";
          this.startTest();
        } else {
          //计算入参数据
          let goResponseTimeSum = 0;
          let goRightClickSum = 0;
          let noGoErrorClickSum = 0;

          this.userResponseRecords.forEach((item, index) => {
            if (item.responseTime < 1500) {
              //用户反应小于1000
              if (item.flag == "black" && item.responseTime != 0) {
                //反应块是黑色
                noGoErrorClickSum += 1;
              } else if (item.flag != "black" && item.responseTime != 0) {
                //反应块是彩色
                goResponseTimeSum += item.responseTime;
                goRightClickSum += 1;
              }
            }
          });

          let sendObj = {
            userId: this.userId,
            goTotalResponseTime: goResponseTimeSum,
            totalRightRate: parseFloat(
              ((goRightClickSum +
                this.singleTurnCount * 4 -
                noGoErrorClickSum) *
                100) /
                this.totalCount
            ).toFixed(2),
            goSeveralResponseTime: parseFloat(
              goResponseTimeSum / (this.singleTurnCount * 3 * 4)
            ).toFixed(2),
            NoGoRightRate: parseFloat(
              (1 - noGoErrorClickSum / (this.singleTurnCount * 4)) * 100
            ).toFixed(2),
            goRightRate: parseFloat(
              (goRightClickSum * 100) / (this.singleTurnCount * 3 * 4)
            ).toFixed(2),
            testTotalCount: this.totalCount,
            userResponseRecords: this.userResponseRecords,
            testPlanId: this.testPlanId || ""
          };

          this.$http.post(`/cognize/GO_NO-GO`, sendObj, res => {
            this.testState = false;
            this.testFlag = false;
            this.backgroundColor = "";
            this.$toast("测试结束！");
            this.goTestResult(res.data);
          });
        }
      }
    },
    // goTestResult(id) {
    //   this.$http.get(`getRecordById?id=${id}`, {}, (res) => {
    //     if (res.code == 2001) {
    //       this.$toast.fail(res.msg);
    //       return;
    //     }
    //     if (res && res.code == 200) {
    //       if (
    //         JSON.parse(res.data?.userRecordEntity?.testResult).versionNo ==
    //         "2.0.1"
    //       ) {
    //         //跳转新测试结果模版数据暂存本地
    //         // sessionStorage.setItem("testResult", res.data?.userRecordEntity?.testResult);
    //         // this.$store.dispatch('setTestResult',JSON.parse(res.data?.userRecordEntity?.testResult));
    //         this.$store.dispatch("setTestResult", res?.data);
    //         this.$router.push({
    //           name: "testResultNew",
    //           query: {
    //             id: res.data?.userRecordEntity?.id,
    //             title: res.data?.userRecordEntity?.name,
    //             testPlanId: this.testPlanId || "",
    //             come: 1, //1-来自认知任务列表，2-测试记录列表
    //           },
    //         });
    //       } else {
    //         //跳转旧测试结果模版
    //
    //         let testResult = JSON.parse(
    //           res.data?.userRecordEntity?.testResult
    //         )[0].version;
    //
    //         if (testResult == 2) {
    //           this.$router.push("/testRecordsSCl?id=" + id);
    //         } else {
    //           this.$router.push(
    //             "/testResult?flag=" +
    //             res.data?.userRecordEntity?.flag +
    //             "&id=" +
    //             id
    //           );
    //         }
    //       }
    //     } else {
    //       this.$toast.fail("获取数据失败！服务器异常");
    //     }
    //   });
    // },
    countDown() {
      // 测试时间倒计时
      this.myInterval = setInterval(() => {
        this.countDownTime--;
        if (this.countDownTime == 0) {
          //计算测试结果
          this.computeScore();
          // 清除定时器
          clearInterval(this.myInterval);
          this.countDownTime = 6;
        }
      }, 1000);
    },
    divRandomShow() {
      if (this.backgroundList.length > 0) {
        let colorIndex = Math.floor(Math.random() * this.backgroundList.length);
        this.backgroundColor = this.backgroundList[colorIndex];
        this.currentBackgroundName = this.backgroundColor;
        this.userResponseRecords.push({
          flag: this.backgroundColor,
          responseTime: 0
        });
        this.userCanClick = true;
        this.startMilliSeconds = new Date().getTime();
        switch (this.backgroundColor) {
          case "red":
            this.redFlagCount--;
            if (this.redFlagCount == 0) {
              this.backgroundList.splice(colorIndex, 1);
            }
            break;
          case "black":
            this.blackFlagCount--;
            if (this.blackFlagCount == 0) {
              this.backgroundList.splice(colorIndex, 1);
            }
            break;
          case "yellow":
            this.greenFlagCount--;
            if (this.greenFlagCount == 0) {
              this.backgroundList.splice(colorIndex, 1);
            }
            break;
          case "blue":
            this.blueFlagCount--;
            if (this.blueFlagCount == 0) {
              this.backgroundList.splice(colorIndex, 1);
            }
            break;
          default:
            break;
        }
        setTimeout(() => {
          this.divShow = false;
        }, 500);

        setTimeout(() => {
          this.backgroundColor = `url(${this.bgImage}) no-repeat center`;
          this.currentIndex++;
        }, 1900);
      } else {
        this.backgroundColor = `url(${this.bgImage}) no-repeat center`;
        this.testEnd();
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    pageDataInit() {
      this.backgroundList = ["red", "black", "yellow", "blue"];
      this.greenFlagCount = this.singleTurnCount;
      this.redFlagCount = this.singleTurnCount;
      this.blueFlagCount = this.singleTurnCount;
      this.blackFlagCount = this.singleTurnCount;
      this.testFlag = true;
      if (this.testTypeCode == 0) {
        this.rightClickCount = 0;
        this.blackClickCount = 0;
        this.totalCount = this.singleTurnCount * 4;
      } else {
        this.totalCount = this.singleTurnCount * 4 * 4;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.btnArea {
  width: 85%;
  margin: 50px auto 0;
}

.explan {
  box-sizing: border-box;
  padding: 16px 10px 0;
}

.explan h1 {
  font-size: 16px;
  color: #222222;
  text-align: center;
}

.explan p {
  font-size: 14px;
  color: #666666;
  line-height: 26px;
  text-indent: 15px;
  margin: 20px 0 20px;
}

.progress-content {
  position: absolute;
  width: 100%;
  height: 20px;
  left: 0;
  top: 60px;
  box-sizing: border-box;
  padding: 4px 10px;
}

.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/goNoGoBg.png) no-repeat center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
}

.goNoGoTask {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* background:black; */
  background-size: cover;
  /* text-align:center; */
  width: 190px;
  height: 140px;
  box-shadow: 0px 8px 12px rgba(0, 0, 0, 0.16);
  opacity: 1;
  border-radius: 28px;
  /* object-fit:fill; */
}

.countdownStr {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: black;
  font-size: 18px;
  /*font-weight: bold;*/
  text-align: center;
  margin: 0 auto;
}

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

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

.stip2 {
  padding: 0 20px;
  margin: 0 auto;
  text-align: left;
  position: absolute;
  z-index: 8;
}

.stips {
  height: 100%;
  background: rgb(248, 248, 248);
  opacity: 1;
  border-radius: 12px;
  margin: 0 auto;
}

.stip {
  float: left;
  height: 100%;
  overflow-y: auto;
}

.t3 {
  width: 750px;
  height: 100px;
  margin: 0 auto;
}

.t7 {
  background: url(../../assets/page4.png) no-repeat center;

  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-size: cover;
  z-index: 1;
}

.t4 {
  color: red;
  text-align: left;
  margin-top: 3%;
  margin-left: 15%;
  font-size: 30px;
}

.t5 {
  color: red;
  text-align: left;
  font-size: 30px;
  margin-left: 15%;
}

.t6 {
  text-align: center;
  /* padding-bottom: 2rem;  */
}

.pix {
  position: fixed;
  bottom: 130px;
  right: 0;
  left: 0;
  width: 70px;
  margin: 0 auto;
  cursor: pointer;
  z-index: 99;
}

.start {
  position: fixed;
  z-index: 999;
}
</style>
