<template>
  <div>
    <van-nav-bar
      :title="subjectInfo.name"
      left-arrow
      left-text="返回"
      @click-left="goBack"
    />
    <div v-if="!testFlag" class="explan">
      <div>
        <p>{{ subjectInfo.mobileTestDescription }}</p>
      </div>
      <div class="btnArea">
        <van-button
          v-if="button0Show"
          block
          round
          type="primary"
          @click="startTest(1)"
          >开始测试
        </van-button>
      </div>
    </div>

    <!--    <div class="desc_wrap">-->
    <!--      <div-->
    <!--        style="-->
    <!--          width: 70%;-->
    <!--          height: 100%;-->
    <!--          background: rgb(248, 248, 248);-->
    <!--          opacity: 1;-->
    <!--          border-radius: 12px;-->
    <!--          margin: 0 auto;-->
    <!--        "-->
    <!--      >-->
    <!--        <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-->
    <!--                class="voiceBg"-->
    <!--                :class="{ active: isActive }"-->
    <!--                @click="videoPlay"-->
    <!--              ></div>-->
    <!--            </div>-->
    <!--          </div>-->
    <!--          <audio-->
    <!--            id="video"-->
    <!--            ref="video"-->
    <!--            :src="require('../../assets/voice/description/description44.mp3')"-->
    <!--          ></audio>-->
    <!--          <div style="margin: 100px auto; width: 80%; text-align: justify;text-justify: distribute-all-lines;">-->
    <!--            <p>-->
    <!--              请你注视眼前屏幕，注视点“+”过后，你将陆续看到一些词语，如果觉得这个词您很喜欢，按鼠标左键表示您【喜欢】，觉得这个词您不喜欢，按鼠标右键表示您【不喜欢】。-->
    <!--            </p>-->
    <!--          </div>-->
    <!--        </div>-->
    <!--        <div-->
    <!--          class="right_part"-->
    <!--          :style="{-->
    <!--            background: 'url(' + require('../../assets/page28.png') + ')',-->
    <!--            'background-size': '100% 100%',-->
    <!--          }"-->
    <!--        >-->
    <!--          <div id="title">-->
    <!--            <span>情绪分类任务（ECAT）（成瘾版）</span>-->
    <!--          </div>-->
    <!--          <div style="position: absolute; bottom: 30px; right: 38%">-->
    <!--            <el-button class="start" @click="startTest(1)">开始测试</el-button>-->
    <!--          </div>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </div>-->

    <div
      v-if="testFlag"
      :class="{ testMainDiv: !testState, activeTask: testState }"
    >
      <!--      <div style="width: 50%; margin-left: 10%; margin-top: 24px">-->
      <!--        <el-progress-->
      <!--          class="main_progress"-->
      <!--          :text-inside="true"-->
      <!--          :format="format"-->
      <!--          :stroke-width="48"-->
      <!--          :percentage="(currentIndex / 41) * 100"-->
      <!--        ></el-progress>-->
      <!--      </div>-->
      <div class="progress-content">
        <van-progress
          :percentage="(currentIndex / 41) * 100"
          color="#f2826a"
          pivot-text="任务进度"
        />
      </div>

      <p
        v-show="showlist"
        style="margin-top: 20%; font-size: 50px; color: black"
      >
        {{ wordlist[currentIndex].currentword }}
      </p>
      <!--      <p v-show="countDownShow" class="imgBox1">{{ countDownStr }}</p>-->
      <!--      <img-->
      <!--        v-show="showWhiteFlag"-->
      <!--        src="../../assets/congnitiveAblitity/whiteFlag-new.png"-->
      <!--        alt=""-->
      <!--        style="width: 50px; height: 50px; margin-top: 20%"-->
      <!--      />-->
      <p v-show="countDownShow" class="timingBox">{{ countDownStr }}</p>
      <div v-show="showWhiteFlag" class="look-point">
        <img alt="" src="../../assets/congnitiveAblitity/whiteFlag-new.png" />
      </div>

      <div v-show="flag" class="btn-content">
        <div class="btn-item">
          <van-button
            block
            round
            size="small"
            type="primary"
            @click="userClick('L')"
          >
            <van-icon name="arrow-left" />
          </van-button>
        </div>
        <div class="btn-item">
          <van-button
            block
            round
            size="small"
            type="primary"
            @click="userClick('R')"
          >
            <van-icon name="arrow" />
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import cognitiveAbilityTaskList from "@/assets/data/cognitiveAbilityData.js";

export default {
  name: "ECATAddiction",
  data() {
    return {
      userId: "",
      userTestResult: {},
      imgUrl: "",
      examImgUrl: "",
      taskId: "", // 认知任务id
      testFlag: false,
      testState: false,
      saveFlag: false, //结果保存按钮显示标志
      subjectInfo: "", //认知任务详情
      button0Show: false, // 控制按钮显示隐藏
      button1Show: true, // 控制按钮显示隐藏
      button2Show: false,
      testTypeCode: 0,
      countDownStr: "马上开始！",
      countDownShow: true,
      countDownTime: 6,
      showWhiteFlag: false,
      showlist: false, //控制文字显示
      // showbutton: false, //控制选择按钮显示
      timeOne: "",
      timeTwo: "",
      timeThree: "",
      timeFour: "",
      currentIndex: 0,
      amount: 0,
      negamount: 0,
      average: 0,
      negaverage: 0,
      flag: false,
      startMilliSeconds: 0, //反应时
      userResponseRecords: [], //记录喜欢反应
      // milliSecondsCount:0,
      wordlist: [
        {
          index: 1,
          currentword: "水杯",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 2,
          currentword: "鼠标",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 3,
          currentword: "瓜子",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 4,
          currentword: "苹果",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 5,
          currentword: "琵琶",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 6,
          currentword: "小溪",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 7,
          currentword: "墨汁",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 8,
          currentword: "钢笔",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 9,
          currentword: "布鞋",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 10,
          currentword: "纱窗",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 11,
          currentword: "剪纸",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 12,
          currentword: "拖把",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 13,
          currentword: "笔记本",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 14,
          currentword: "枸杞",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 15,
          currentword: "太阳",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 16,
          currentword: "衬衫",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 17,
          currentword: "枕头",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 18,
          currentword: "松树",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 19,
          currentword: "马蹄",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 20,
          currentword: "肥皂",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 21,
          currentword: "电灯",
          wordtype: "positive",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 22,
          currentword: "冰毒",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 23,
          currentword: "冰",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 24,
          currentword: "溜冰",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 25,
          currentword: "毒品",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 26,
          currentword: "海洛因",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 27,
          currentword: "可卡因",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 28,
          currentword: "新型毒品",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 29,
          currentword: "摇头丸",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 30,
          currentword: "快乐丸",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 31,
          currentword: "钻石",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 32,
          currentword: "开心果",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 33,
          currentword: "大麻",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 34,
          currentword: "白粉",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 35,
          currentword: "杜冷丁",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 36,
          currentword: "十字架",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 37,
          currentword: "吗啡",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 38,
          currentword: "氯胺酮",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 39,
          currentword: "K粉",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 40,
          currentword: "甲基苯丙胺",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 41,
          currentword: "冷东西",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        },
        {
          index: 42,
          currentword: "笑气",
          wordtype: "negative",
          userResponse: "",
          responseTime: 500
        }
      ], //词语列表
      isActive: false, //音频播放按钮
      testPlanId: ""
    };
  },
  created() {
    // this.taskId = this.$route.query.taskId;
    // this.testPlanId = this.$route.query.testPlanId;
    // this.init(this.taskId);
    this.testPlanId = this.$route.query.testPlanId || "";
    this.userId = JSON.parse(sessionStorage.getItem("userInfo")).id;
    this.subjectInfo = JSON.parse(sessionStorage.getItem("subjectInfo"));
    this.userTestPicListCreate();
  },
  mounted() {
    //进入页面即开始测试任务
    // this.startTest(1)
  },
  destroyed() {
    // 清除定时器
    clearTimeout(this.timeOne);
    clearTimeout(this.timeTwo);
    clearTimeout(this.timeThree);
    clearTimeout(this.timeFour);
  },
  methods: {
    format(percentage) {
      return percentage === 100 ? "任务已完成" : "任务进度";
    },
    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);
    },
    // screen() {
    //   screenfull.toggle();
    // },
    // exitFullscreen() {
    //   if (document.exitFullscreen) {
    //     document.exitFullscreen();
    //   } else if (document.msExitFullscreen) {
    //     document.msExitFullscreen();
    //   } else if (document.mozCancelFullScreen) {
    //     document.mozCancelFullScreen();
    //   } else if (document.webkitExitFullscreen) {
    //     document.webkitExitFullscreen();
    //   }
    // },
    // init(taskId) {
    //   console.log(taskId);
    //   console.log(cognitiveAbilityTaskList);
    //   this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
    //   console.log(this.subjectInfo);
    // },
    userClick(clickFlag) {
      if (!this.flag) {
        return;
      }

      if (clickFlag === "L") {
        this.showlist = false;
        this.showWhiteFlag = true;
        let milliSecondsCount = new Date().getTime() - this.startMilliSeconds;
        console.log(milliSecondsCount);
        //记录用户喜欢反应
        // 积极词同意统计
        if (this.wordlist[this.currentIndex].index <= 20) {
          (this.amount = ++this.amount), //积极词同意个数
            this.userResponseRecords.push({
              index: this.wordlist[this.currentIndex].index,
              // currentword:this.wordlist[this.currentIndex].currentword,
              wordtype: this.wordlist[this.currentIndex].wordtype,
              responseTime: milliSecondsCount,
              userSelectWordType: "1" //用户选择的情绪类型 1（积极）,0（消极）
            });
        }
        // 消极词同意统计
        else if (this.wordlist[this.currentIndex].index > 20) {
          (this.negamount = ++this.negamount), //消极词同意个数
            this.userResponseRecords.push({
              index: this.wordlist[this.currentIndex].index,
              // currentword:this.wordlist[this.currentIndex].currentword,
              wordtype: this.wordlist[this.currentIndex].wordtype,
              responseTime: milliSecondsCount,
              userSelectWordType: "1" //用户选择的情绪类型 1（积极）,0（消极）
            });
        }
      } else if (clickFlag === "R") {
        this.showlist = false;
        this.showWhiteFlag = true;
        let negSecondsCount = new Date().getTime() - this.startMilliSeconds;
        // 积极词不同意统计
        if (this.wordlist[this.currentIndex].index <= 20) {
          this.userResponseRecords.push({
            index: this.wordlist[this.currentIndex].index,
            // currentword:this.wordlist[this.currentIndex].currentword,
            wordtype: this.wordlist[this.currentIndex].wordtype,
            responseTime: negSecondsCount,
            userSelectWordType: "0" //用户选择的情绪类型 1（积极）,0（消极）
          });
        }
        // 消极词不同意统计
        else if (this.wordlist[this.currentIndex].index > 20) {
          this.userResponseRecords.push({
            index: this.wordlist[this.currentIndex].index,
            wordtype: this.wordlist[this.currentIndex].wordtype,
            responseTime: negSecondsCount,
            userSelectWordType: "0" //用户选择的情绪类型 1（积极）,0（消极）
          });
        }
      }
      this.flag = false;
    },
    startTest(testType) {
      // if (
      //   sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
      //   sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      // ) {
      //   this.$message.error("请先登录！");
      //   return;
      // }
      if (!sessionStorage.getItem("userInfo")) {
        this.$toast("请先登录！");
        this.$router.push("/login");
        return;
      }

      if (testType == 0) {
        this.testTypeCode = 0;
      } else {
        this.testTypeCode = 1;
      }
      // this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      if (this.testTypeCode == 1) {
        this.screen();
        this.userTestPicList = [];
        this.testFlag = true;
        this.testState = true;
        this.countDown();
      }
    },
    // 时间定时器
    showTargetNow() {
      // var time = 4000;
      var time = 1500;
      this.showWhiteFlag = true;
      this.flag = false;
      this.showlist = false;
      this.timeTwo = setTimeout(() => {
        this.showWhiteFlag = false;
        this.showlist = true;
        this.flag = true;
        this.startMilliSeconds = new Date().getTime();
        this.timeThree = setTimeout(() => {
          this.showlist = false;
        }, 1000);
      }, 500);
      this.timeOne = setInterval(() => {
        this.showWhiteFlag = true;
        this.showlist = false;
        this.flag = false;
        // this.showbutton = false;
        this.timeTwo = setTimeout(() => {
          this.flag = true;
          this.showWhiteFlag = false;
          this.showlist = true;
          this.startMilliSeconds = new Date().getTime();
          this.timeThree = setTimeout(() => {
            this.showlist = false;
            // this.showbutton = true;
          }, 1000);
        }, 500);
        if (this.currentIndex == 42) {
          this.testEnd();
        } else {
          this.currentIndex++;
        }
      }, time);
    },
    // 打乱数组顺序
    userTestPicListCreate() {
      for (var i = this.wordlist.length - 1; i >= 0; i--) {
        var randomIndex = Math.floor(Math.random() * (i + 1));
        var itemAtIndex = this.wordlist[randomIndex];
        this.wordlist[randomIndex] = this.wordlist[i];
        this.wordlist[i] = itemAtIndex;
      }
    },
    meanresponseTime() {
      var sum = 0,
        index = 0,
        negsum = 0,
        oppcount = 0,
        negcount = 0;
      for (var i = 0; i < this.userResponseRecords.length; i++) {
        if (this.userResponseRecords[index].index <= 20) {
          sum += this.userResponseRecords[index].responseTime;
          index++;
          oppcount++;
        } else if (this.userResponseRecords[index].index > 20) {
          negsum += this.userResponseRecords[index].responseTime;
          index++;
          negcount++;
        }
      }
      this.average = sum / index; // 计算积极词语平均反应时
      this.negaverage = negsum / negcount; // 计算消极词语平均反应时
    },
    testEnd() {
      clearInterval(this.timeOne);
      clearInterval(this.timeTwo);
      this.showWhiteFlag = false;
      this.testFlag = false;
      this.testState = false;
      this.button1Show = false;
      this.meanresponseTime();

      let result = {
        data: this.userResponseRecords,
        result: {
          posNum: this.amount + "个", //积极个数
          negNum: this.negamount + "个", //消极个数
          posAverageTime: this.average.toFixed(2) + "ms", //积极平均反应时
          negAverageTime: this.negaverage.toFixed(2) + "ms" //消极平均反应时
        }
      };

      this.$store.dispatch("setVocabularyClassify", result);

      this.$alert(
        "词汇分类任务结束，接下来进行词汇回忆测试，请按确定按钮继续。",
        "提示",
        {
          confirmButtonText: "确定",
          showClose: false,
          callback: action => {
            this.$router.push(
              `/welcome/CognitiveAbilityTask/ERECAddiction?testPlanId=${this.testPlanId}`
            );
          }
        }
      );

      // this.$message({
      //   message: "测试结束！",
      //   type: "success",
      // });
      this.$toast.success("试结束！");
    },
    videoPlay() {
      let video = document.getElementById("video");
      if (this.isActive == false) {
        this.isActive = true;
        video.loop = false;
        video.addEventListener("ended", () => {
          this.isActive = false;
        });
        video.play();
      } else {
        this.isActive = false;
        video.pause();
      }
    }
  }
};
</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;
}

.testMainDiv {
  margin: 0 auto;
  margin-top: 10px;
  background: gray;
  background-size: cover;
  width: 500px;
  height: 300px;
}

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

.scaleButton {
  margin-top: 20px;
  margin-bottom: 20px;
  background-size: cover;
  background: rgb(87, 172, 187);
  border: 2px solid rgb(255, 255, 255);
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
  opacity: 1;
  border-radius: 39px;
  color: #ffffff;
}

/*.voiceBg {*/
/*  width: 40px;*/
/*  height: 40px;*/
/*  background: url(../../assets/voice.png);*/
/*  background-size: cover;*/
/*  float: left;*/
/*  margin-left: 60px;*/
/*  cursor: pointer;*/
/*}*/
/*.voiceBg.active {*/
/*  width: 40px;*/
/*  height: 40px;*/
/*  background: url(../../assets/voice.gif);*/
/*  background-size: cover;*/
/*}*/
.progress-content {
  position: absolute;
  width: 100%;
  height: 20px;
  left: 0;
  top: 60px;
  box-sizing: border-box;
  padding: 4px 10px;
}

.look-point {
  position: absolute;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  text-align: center;
}

.look-point img {
  width: 50px;
  height: 50px;
}

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