<template>
  <div class="app-container">
    <Header />
    <!--<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;-->
    <!--"-->
    <!--&gt;-->
    <!--<div style="float: left; width: 50%; height: 100%; overflow-y: auto">-->
    <!--<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: left">-->
    <!--<p v-html="subjectInfo.testDescription"></p>-->
    <!--&lt;!&ndash; <p>{{subjectInfo.description}}</p> &ndash;&gt;-->
    <!--</div>-->
    <!--</div>-->
    <!--<div-->
    <!--class="right_part"-->
    <!--:style="{-->
    <!--background:-->
    <!--'url(' + require('../../assets/page' + taskId + '.png') + ')',-->
    <!--'background-size': '100% 100%',-->
    <!--}"-->
    <!--&gt;-->
    <!--<div id="title">-->
    <!--<span>{{ subjectInfo.name }}</span>-->
    <!--</div>-->
    <!--<div-->
    <!--style="-->
    <!--position: absolute;-->
    <!--bottom: 30px;-->
    <!--left: 50%;-->
    <!--transform: translateX(-50%);-->
    <!--"-->
    <!--&gt;-->
    <!--<el-button-->
    <!--class="start"-->
    <!--type="primary"-->
    <!--v-if="button0Show"-->
    <!--@click="startTest(0)"-->
    <!--&gt;练习测试</el-button-->
    <!--&gt;-->
    <!--<el-button-->
    <!--class="start"-->
    <!--type="primary"-->
    <!--v-if="button1Show"-->
    <!--@click="startTest(1)"-->
    <!--&gt;正式测试</el-button-->
    <!--&gt;-->
    <!--</div>-->
    <!--</div>-->
    <!--</div>-->
    <!--</div>-->
    <div class="main-container">
      <van-nav-bar
        :title="subjectInfo.name"
        left-arrow
        left-text=""
        @click-left="goBack"
      />
      <div v-if="!testResultStr" class="explan">
        <!-- LOGO  -->
        <!--<h1>{{ subjectInfo.name }}</h1>-->
        <div class="main-text-div">
          <!--<p v-html="subjectInfo.testDescription">{{ subjectInfo.testDescription }}</p>-->
          <p>{{ subjectInfo.mobileTestDescription }}</p>
        </div>
        <div class="btnArea">
          <van-button
            v-if="button0Show"
            block
            round
            type="primary"
            @click="startTest(0)"
            >练习测试
          </van-button>
          <van-button
            v-if="button1Show"
            block
            round
            style="margin-top: 15px"
            type="primary"
            @click="startTest(1)"
          >
            正式测试
          </van-button>
        </div>
      </div>

      <!-- LOGO  -->

      <div
        v-show="testResultStrShow"
        style="width: 650px; margin: 20px auto; line-height: 2"
      >
        <p style="margin-top: 20%; font-size: 30px">
          {{ testResultStr }}
        </p>
      </div>

      <div v-if="testFlag" class="activeTask">
        <div v-if="testTypeCode == 1" class="progress-content">
          <van-progress
            :percentage="(imgIndex * 100) / 120"
            color="#f2826a"
            pivot-text="任务进度"
          />
        </div>

        <div class="glass">
          <p v-show="countDownShow" class="timingBox">{{ countDownStr }}</p>

          <img v-show="showDuckEgg" :src="examImgUrl" alt="" class="shapeImg" />

          <div v-show="showDuckEgg" class="btn-content">
            <div class="btn-item">
              <van-button
                block
                round
                size="small"
                type="info"
                @click="userClick('L')"
              >
                <van-icon name="arrow-left" />
              </van-button>
            </div>
            <div class="btn-item">
              <van-button
                block
                round
                size="small"
                type="info"
                @click="userClick('R')"
              >
                <van-icon name="arrow" />
              </van-button>
            </div>
          </div>
        </div>
        <!-- <img v-show="showWhiteFlag" src='../../assets/congnitiveAblitity/whiteFlag.png' alt="" style="width: 50px; height: 50px; margin-top: 20%"> -->
        <!-- 演示使用 -->
        <!-- <div class="steering">
          <el-button type="primary" icon="el-icon-arrow-left" @click="userClick('L')"></el-button>
          <el-button type="primary" @click="userClick('R')"><i class="el-icon-arrow-right el-icon--right"></i></el-button>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script>
import { preloader } from "@/utils/utils";
import Header from "@/components/header/index.vue";

export default {
  name: "shapeIntuition2",
  components: { Header },
  data() {
    return {
      userId: "",
      userTestResult: {},
      imgUrl: "",
      examImgUrl: "",
      taskId: "", // 认知任务id
      testFlag: false,
      testState: false,
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: "", //认知任务详情
      button0Show: true, // 控制按钮显示隐藏
      button1Show: false, // 控制按钮显示隐藏
      buttonName: "开始测试", // 正式测试  // 重新练习
      testTypeCode: 0, // 0-练习测试 1-正式测试 2-重新测试
      imgIndex: 0,
      userTestPicList: [], //用户点击图片列表
      showImage: true,
      difficultList: [0], // [0,10,30,45,60,90,120,180,360]
      testPicCount: 10, //测试数目
      userRightClickDirection: "", //测试者应该点击的方向
      userRightResponseCount: 0, //测试者反应正确的次数
      showDuckEgg: false,
      countDownTime: 6, //开始前的倒计时
      countDownStr: "练习马上开始！",
      countDownShow: true,
      testTunrnCount: 0, //正式测试轮数
      testEndFlag: false, //测试结束标志
      testResultStrShow: false, //测试结果展示
      testResultStr: "", //测试成绩
      userCanClick: true, //用户标识用户单次刺激只能点击一次
      myInterval: "",
      timeOne: "",
      timeTwo: "",
      startMilliSeconds: 0, //反应时
      userResponseRecords: [], //用户测试反应记录
      saveFalg: true,
      testPlanId: ""
    };
  },
  // 页面初始化函数
  created() {
    // this.taskId = this.$route.query.taskId;
    this.init();
  },
  destroyed() {
    clearInterval(this.myInterval);
    clearTimeout(this.timeOne);
    clearTimeout(this.timeTwo);
  },
  methods: {
    goBack() {
      if (this.testPlanId) {
        //来自测试计划列表
        this.$router.push({
          name: "testPlanClassify",
          params: {
            testPlanId: this.testPlanId
          }
        });
      } else {
        this.$router.push("/index/cognitionTask");
      }
    },
    init() {
      this.testPlanId = this.$route.query.testPlanId || "";
      this.userId = JSON.parse(sessionStorage.getItem("userInfo")).id;
      this.subjectInfo = JSON.parse(sessionStorage.getItem("subjectInfo"));
    },
    userClick(clickFlag) {
      if (this.countDownShow || !this.userCanClick) {
        return;
      }
      this.userCanClick = false;
      let milliSecondsCount = new Date().getTime() - this.startMilliSeconds;
      let userResponseStr = "Wrong";
      clearTimeout(this.timeOne);

      //用户反应正确性判断

      if (this.userRightClickDirection == clickFlag) {
        this.userRightResponseCount++;
        userResponseStr = "Right";
      }
      //判断是否测试结束
      if (this.imgIndex == this.userTestPicList.length) {
        this.testEndFlag = true;
        clearTimeout(this.timeOne);
      }
      //记录用户反应
      // console.log(this.imgIndex);
      if (this.testTypeCode == 1) {
        this.userResponseRecords.push({
          index: this.imgIndex,
          rightOrWrong: userResponseStr,
          responseTime: milliSecondsCount,
          diff: this.userTestPicList[this.imgIndex - 1].diff
        });
      }
      // console.log(this.userResponseRecords);
      this.showDuckEgg = false;
      this.timeTwo = setTimeout(() => {
        this.showTargetNow();
      }, 500);
    },
    startTest(testType) {
      if (!sessionStorage.getItem("userInfo")) {
        this.$toast("请先登录！");
        this.$router.push("/login");
        return;
      }

      if (testType == 0) {
        this.testTypeCode = 0;
      } else {
        this.saveFalg = true;
        this.testTypeCode = 1;
      }

      if (this.testTypeCode == 1) {
        this.difficultList = [360, 180, 90, 60, 30, 0]; // [360,180,90,60,30,0]
        this.imgIndex = 0;
        this.countDownStr = "马上开始！";
        this.countDownTime = 6;
        this.testEndFlag = false;
        this.showDuckEgg = false;
        this.userTestPicList = [];
      }
      this.countDownShow = true;
      this.userTestPicListCreate();
      // 预加载图片后开始测试
      preloader(this.userTestPicList, () => {
        this.testFlag = true;
        this.testState = true;
        this.countDown();
      });
    },
    showTargetNow() {
      // 练习间隔2~4，正式测试2~12；
      this.showDuckEgg = false;
      if (this.testEndFlag) {
        this.computeScore();
      } else {
        this.userRightClickDirection = this.userTestPicList[
          this.imgIndex
        ].imgDirection;
        this.examImgUrl = this.userTestPicList[this.imgIndex].imgUrl;
        this.showDuckEgg = true;
        this.imgIndex++;
        this.startMilliSeconds = new Date().getTime();
        this.userCanClick = true;

        if (this.imgIndex == this.userTestPicList.length) {
          this.testEndFlag = true;
        }
        this.timeOne = setTimeout(this.ifShowNextOne, 10 * 1000, this.imgIndex);
        // this.timeOne = setTimeout(() => {
        //   this.userClick('NULL')
        // },10*1000);
      }
    },
    ifShowNextOne(needClickIndex) {
      if (needClickIndex == this.imgIndex) {
        this.userClick("NULL");
      }
    },
    computeScore() {
      if (this.testTypeCode == 0) {
        this.testFlag = false;
        this.testState = false;
        //this.testTypeCode =1
        this.countDownStr = "练习马上开始！";
        this.userRightResponseCount = 0;
        this.imgIndex = 0;
        this.countDownTime = 6;
        this.testEndFlag = false;
        this.showDuckEgg = false;
        this.userTestPicList = [];
        this.button1Show = true;
        // this.$message({
        //     message: "测试结束！",
        //     type: "success",
        // });
        this.$toast.success({
          message: "测试结束！",
          position: "top"
        });
      } else {
        let userScore = (
          (this.userRightResponseCount / this.userResponseRecords.length) *
          100
        ).toFixed(2);
        this.testFlag = false;
        this.testState = false;
        this.button0Show = false;
        this.button1Show = false;
        //console.log(this.userResponseRecords)
        if (this.saveFalg) {
          this.$http.post(
            `/cognize/SHAPE2`,
            {
              userId: this.userId,
              userScore: userScore + "%",
              userResponseRecords: this.userResponseRecords,
              testPlanId: this.testPlanId
            },
            response => {
              if (response?.code == 200) {
                // sessionStorage.setItem("resultInfo", JSON.stringify({"测试准确率":response.data.userScore}));
                // this.$router.push(`/cognitiveTestResult?from=1&testPlanId=${this.testPlanId}`);
                //跳转新测试结果页面
                this.goTestResult(response.data);
              } else {
                this.$toast.fail(response?.msg);
              }
            },
            err => {
              this.$toast.fail(err.msg);
            }
          );
          this.$toast.success("测试结束！");
          this.saveFalg = false;
        }
      }
    },
    // 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("获取数据失败！服务器异常");
    //         }
    //     });
    // },
    userTestPicListCreate() {
      let imgObj = {
        // imgUrl:'',
        // imgDirection:'',
        // userClickDirection:''
      };
      if (this.testTypeCode == 0) {
        //随机呈现最简单的10张图片
        let imgIndexList = this.getRandomNumber(10, 20);
        for (let j = 0; j < this.difficultList.length; j++) {
          for (let i = 0; i < imgIndexList.length; i++) {
            imgObj = {};
            if (i % 2 == 0) {
              imgObj.imgUrl = require("../../assets/congnitiveAblitity/shapeIntuition/R_ELP_test_jitter" +
                this.difficultList[j] +
                "_s" +
                imgIndexList[i] +
                ".jpg");
              imgObj.imgDirection = "R";
              imgObj.userClickDirection = "";
            } else {
              imgObj.imgUrl = require("../../assets/congnitiveAblitity/shapeIntuition/ELP_test_jitter" +
                this.difficultList[j] +
                "_s" +
                imgIndexList[i] +
                ".jpg");
              imgObj.imgDirection = "L";
              imgObj.userClickDirection = "";
            }
            this.userTestPicList.push(imgObj);
          }
        }
        this.shuffle(this.userTestPicList);
      } else {
        //展示所有图片
        for (let j = 0; j < this.difficultList.length; j++) {
          var tempList = [];
          for (let i = 1; i < 11; i++) {
            imgObj = {};
            imgObj.imgUrl = require("../../assets/congnitiveAblitity/shapeIntuition/R_ELP_test_jitter" +
              this.difficultList[j] +
              "_s" +
              i +
              ".jpg");
            imgObj.imgDirection = "R";
            imgObj.userClickDirection = "";
            imgObj.diff = this.difficultList[j];
            tempList.push(imgObj);
            imgObj = {};
            imgObj.imgUrl = require("../../assets/congnitiveAblitity/shapeIntuition/ELP_test_jitter" +
              this.difficultList[j] +
              "_s" +
              i +
              ".jpg");
            imgObj.imgDirection = "L";
            imgObj.userClickDirection = "";
            imgObj.diff = this.difficultList[j];
            tempList.push(imgObj);
            //console.log(tempList)
          }
          this.shuffle(tempList);
          this.userTestPicList = this.userTestPicList.concat(tempList);
          console.log(this.userTestPicList);
          this.testPicCount = this.userTestPicList.length;
        }
      }
    },
    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;
        if (this.countDownTime == 0) {
          this.countDownShow = false;
          //显示鸭蛋
          this.showTargetNow();
          // 清除定时器
          clearInterval(this.myInterval);
          //this.countDownTime = 5;
        }
      }, 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>
.explan {
  box-sizing: border-box;
  padding: 15px 15px 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-bottom: 20px;
}

.activeTask {
  box-sizing: border-box;
  padding-top: 46px;
  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;
}

.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;
}

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

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

.btn-content {
  position: absolute;
  width: 100%;
  left: 50%;
  bottom: 10%;
  transform: translate(-50%, 0);
  text-align: center;
  z-index: 10;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  box-sizing: border-box;
  padding: 0 5px;
}

.btn-content .btn-item {
  width: 30%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.btn-content .btn-item /deep/ .van-button {
  margin: 35px 0;
}

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

.shapeImg {
  width: 90%;
  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>
