<template>
  <div>
    <div class="desc_wrap" v-if="testFlag">
      <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-show="testTypeCode == 1" v-html="subjectInfo.testDescription"></p>
            <p v-show="testTypeCode == 2">
              在本实验中，你将看到一些情绪图片，请你对这些图片带给你的情绪感受进行自我评定，每一张图片需要评定：<br><br>
              一、效价：是指情绪刺激的愉悦或不愉悦程度，1代表“最不愉快” ，9代表“最愉快”<br><br>
              二、唤起度：是指情绪刺激时生理活动增强的状态，1代表“最弱” ，9代表“最强”<br><br>
              三、优势度：是指个体感觉自己对图片的掌控和支配程度，1代表“最弱” ，9代表“最强”<br><br>
              每张图片将呈现4秒，请你在1-9之间选择最符合情绪感受的数字。
            </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; right: 40%">
            <el-button v-if="buttonShow" class="start" @click="startTest()">{{buttonName}}</el-button>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!testFlag" class="activeTask">
      <img @click="screen()" src="../../assets/small-big.png" alt="" style="
          height: 48px;
          width: 48px;
          position: fixed;
          top: 24px;
          right: 22px;
          cursor: pointer;
        " />
      <div style="width: 50%; margin-left: 10%; margin-top: 24px; z-index: 10">
        <el-progress class="main_progress" :text-inside="true" :format="format" :stroke-width="24"
                     :percentage="((cumulation + 1) / testList.length) * 100"></el-progress>
      </div>
      <p v-if="timingShow" class="timingBox">{{ countDownStr }}</p>

      <div class="test-content">
        <div class="shape_glass">
          <img v-show="!imgShow" class="active-img addImg" :src="testList[cumulation].imgUrl" alt="" />
        </div>
        <div class="test-content-opt">

          <div v-if="!crossShow" class="block">
<!--            <div class="slider">-->
<!--              <el-tooltip placement="top">-->
<!--                <div slot="content">效价：是指情绪刺激的愉悦或不愉悦程度，1代表“最不愉快” ，9代表“最愉快”</div>-->
<!--                <i class="el-icon-info"></i>-->
<!--              </el-tooltip>-->
<!--              <span>效价</span>-->
<!--              <el-rate v-model="testList[cumulation].xiaojia" :max="9" void-color="#999999" show-score text-color="#ff9900"-->
<!--                       score-template="评分{value}">-->
<!--              </el-rate>-->
<!--            </div>-->
<!--            <div class="slider">-->
<!--              <el-tooltip placement="top">-->
<!--                <div slot="content">唤起度：是指情绪刺激时生理活动增强的状态，1代表“最弱” ，9代表“最强”</div>-->
<!--                <i class="el-icon-info"></i>-->
<!--              </el-tooltip>-->
<!--              <span>唤起度</span>-->
<!--              <el-rate v-model="testList[cumulation].huanqi" :max="9" void-color="#999999" show-score text-color="#ff9900"-->
<!--                       score-template="评分{value}">-->
<!--              </el-rate>-->
<!--            </div>-->
<!--            <div class="slider">-->
<!--              <el-tooltip placement="top">-->
<!--                <div slot="content">优势度：是指个体具有影响环境的能力的感觉，1代表“最弱” ，9代表“最强”</div>-->
<!--                <i class="el-icon-info"></i>-->
<!--              </el-tooltip>-->
<!--              <span>优势度</span>-->
<!--              <el-rate v-model="testList[cumulation].youshi" :max="9" void-color="#999999" show-score text-color="#ff9900"-->
<!--                       score-template="评分{value}">-->
<!--              </el-rate>-->
<!--            </div>-->

            <div class="slider">
              <el-tooltip placement="top">
                <div slot="content">效价：是指情绪刺激的愉悦或不愉悦程度，1代表“最不愉快” ，9代表“最愉快”</div>
                <i class="el-icon-info"></i>
              </el-tooltip>
              <p class="slider-title">效价</p>
              <div class="slide-item">
                <p class="slide-item-left">最不愉快</p>
                <el-slider
                    v-model="testList[cumulation].xiaojia"
                    show-stops
                    :min="0"
                    :max="9"
                    :marks="marks">
                </el-slider>
                <p class="slide-item-right">最愉快</p>
              </div>
            </div>
            <div class="slider">
              <el-tooltip placement="top">
                <div slot="content">唤起度：是指情绪刺激时生理活动增强的状态，1代表“最弱” ，9代表“最强”</div>
                <i class="el-icon-info"></i>
              </el-tooltip>
              <p class="slider-title">唤起度</p>
              <div class="slide-item">
                <p class="slide-item-left">最弱</p>
                <el-slider
                    v-model="testList[cumulation].huanqi"
                    show-stops
                    :min="0"
                    :max="9"
                    :marks="marks">
                </el-slider>
                <p class="slide-item-right">最强</p>
              </div>
            </div>
            <div class="slider">
              <el-tooltip placement="top">
                <div slot="content">优势度：是指个体具有影响环境的能力的感觉，1代表“最弱” ，9代表“最强”</div>
                <i class="el-icon-info"></i>
              </el-tooltip>
              <p class="slider-title">优势度</p>
              <div class="slide-item">
                <p class="slide-item-left">最弱</p>
                <el-slider
                    v-model="testList[cumulation].youshi"
                    show-stops
                    :min="0"
                    :max="9"
                    :marks="marks">
                </el-slider>
                <p class="slide-item-right">最强</p>
              </div>
            </div>

          </div>

          <div class="btn-content" v-if="!crossShow">
            <el-button class="butt" @click="prevHandle" :disabled="isLoading">
              上一题
            </el-button>
            <!--        <el-button v-for="item in testList[cumulation].buttonList" :key="item.val" class="butt" :class="{-->
            <!--            active: item.val == testList[cumulation].emoType && showGuider,-->
            <!--            choose: item.val == testList[cumulation].userResponse,-->
            <!--          }" @click="userClick(item.val)">-->
            <!--          {{ item.name }}-->
            <!--        </el-button>-->
            <el-button class="butt" @click="nextHandle" :disabled="isLoading">
              下一题
            </el-button>
          </div>

        </div>
      </div>

<!--      <div class="guider" v-show="showGuider && testTypeCode == 0">-->
<!--        <div class="txt">-->
<!--          <p class="explain">-->
<!--            观察图片中人物的面部表情，下方闪烁的选项是正确的情绪类型。请学习这种对应关系，点击下方按钮，选择正确的情绪类型-->
<!--          </p>-->
<!--        </div>-->
<!--      </div>-->

    </div>
  </div>
</template>

<script>
import {oSessionStorage, preloader} from "@/utils/utils";
import screenfull from "screenfull";
import {fearLevel1,fearLevel2,fearLevel3,fearLevel4} from "@/assets/data/emotionalImageAssessment";

export default {
  name: "emotionalImageAssessment",
  data() {
    return {
      subjectInfo: {},
      userId: '',
      taskId: '',
      showGuider: false, //显示灰色背景当作引导
      testFlag: true, //显示提示页面与测试页面控制开关
      timingShow: true, //倒计时5秒提示开始
      timingFlag: null, // 倒计时名称
      countDown: 5, //倒计时5秒
      countDownStr: "练习测试",
      crossShow: true, //显示评分栏
      imgShow: true, //图片显示
      expressionShow: false, //显示表情图片
      buttonShow: true, //显示选择按钮
      buttonName: "练习测试",
      timeImg: null,
      timerRest: null,
      cumulation: 0, //累加器

      testList: [], // 当前测试列表
      practiceList: [], // 练习测试列表
      normalList: [], // 正式测试列表
      studyList: [],
      testTypeCode: 1,
      phone: "",
      isLoading: false,
      marks: {
        0: '',
        1: '1',
        2: '2',
        3: '3',
        4: '4',
        5: '5',
        6: '6',
        7: '7',
        8: '8',
        9: '9',
      }, //评分标记
    };
  },
  // 页面初始化函数
  created() {
    this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
    this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
    this.taskId = this.$route.query.taskId;
    this.phone = sessionStorage.getItem("f7a42fe7211f98ac7a60a285ac3a9e87");
  },
  mounted() {

  },
  methods: {
    screen() {
      screenfull.toggle();
    },
    //显示图片方法
    showImg(){
      this.timingShow = false;
      this.imgShow = false;//显示图片
      this.crossShow = false;//显示操作按钮
      // this.timeImg = setTimeout(()=>{
      //   this.imgShow = true;//隐藏图片
      // },4000)
    },
    startTiming() {
      if (
          sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
          sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        this.$message.error("请先登录！");
        return;
      }
      //关闭提示内容窗口
      this.testFlag = false;
      this.timingShow = true;
      this.imgShow = true;
      this.crossShow = true;
      this.timingFlag = window.setInterval(() => {
        if (this.countDown == 0) {
          clearInterval(this.timingFlag);
          this.countDownStr = "开始";
          setTimeout(() => {
            //关闭倒计时提示页面
            // this.timingShow = false;
            // this.crossShow = false;
            this.showImg()
            this.countDown = 5;
            // if (this.testTypeCode == 0) {
            //   this.showGuider = true;
            // }
          }, 1000);
        } else {
          this.countDownStr = this.countDown;
          this.countDown--;
        }
      }, 1000);
    },
    format(percentage) {
      return `${this.cumulation + 1}/${this.testList.length}`;
    },
    // 随机抽取人数
    randomList(arr,length) {
      // 从arr中随机获取长度为length不同的数组
      let randomArr = [];

      for (let k = 0; k < length; k++) {
        let id = Math.floor(Math.random() * arr.length);
        if (k < arr.length) {
          if (randomArr.indexOf(arr[id]) === -1) {
            randomArr.push(arr[id]);
          } else {
            k = k - 1;
            continue;
          }
        } else {
          randomArr.push(arr[id]);
        }
      }
      return  randomArr;
    },
    //顺序打乱
    shuffle(arr) {
      for (let i = 1; i < arr.length; i++) {
        const random = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[random]] = [arr[random], arr[i]];
      }
      return arr;
    },

    // userClick(param) {
    //   this.testList[this.cumulation].userResponse = param; //用户选择的情绪类型
    //   this.testList[this.cumulation].correct = param == this.testList[this.cumulation].emoType ? true : false;
    //   if (this.testTypeCode != 2) {
    //     this.nextHandle();
    //   }
    // },

    // 上一题
    prevHandle() {
      clearTimeout(this.timeImg);
      if (this.cumulation > 0) {
        this.cumulation--;
        this.showImg()
      }
    },

    // 下一题
    nextHandle() {
      clearTimeout(this.timeImg);
      if (this.cumulation < this.testList.length - 1) {
         if(this.testList[this.cumulation].xiaojia == 0 ||
             this.testList[this.cumulation].huanqi == 0 ||
             this.testList[this.cumulation].youshi == 0)
         {
          this.$message.warning("请选择对应的评分！");
         } else {
            this.cumulation++;
            if (this.cumulation == 42 || this.cumulation == 133 || this.cumulation == 219) {
              this.imgShow = true;
              this.timingShow = true;
              this.crossShow = true;
              this.threeMinDown();
            }else {
              this.showImg()
            }
        }
      } else {
        if (this.testTypeCode == 1) {
          // let rate = this.getCorrectRate(this.testList);
          this.practiceResult(1);
        } else if (this.testTypeCode == 2) {
          this.submitData();
        } else {
          // this.showGuider = false;
          // this.testFlag = true;
          // this.cumulation = 0;
          // this.testTypeCode = 1;
          // this.buttonName = "练习阶段";
          // this.countDownStr = "练习阶段";
        }
      }
    },

    // 计算准确率
    getCorrectRate(arr) {
      let num = 0;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].correct) {
          num += 1;
        }
      }
      return num / arr.length;
    },

    // 练习测试结果处理
    practiceResult(rate) {
      if (rate >= 0.8) {
        this.$message.success("恭喜你，通过练习测试");
        this.testTypeCode = 2;
        this.buttonName = "正式测试";
        this.countDownStr = "正式测试";
      } else {
        this.testTypeCode = 1;
        this.$message.warning("未通过练习测试");
        this.countDownStr = "练习测试";
        this.buttonName = "练习测试";
      }
      this.countDown = 5;
      this.testFlag = true;
      this.cumulation = 0;
      screenfull.exit();
    },

    submitData() {
      if (this.isLoading) {
        return;
      }
      this.isLoading = true;//防重复点击

      // let results = [];
      // this.testList.forEach((el) => {
      //   results.push({
      //     name: el.name, // 图片名称
      //     emoType: el.emoType, // 情绪类型
      //     userResponse: el.userResponse, // 用户反映类型
      //     correct: el.correct, // 是否正确
      //     xiyin: el.xiyin, // 吸引力
      //     yuyue: el.yuyue, // 愉悦度
      //     huanxing: el.huanxing, // 唤醒度
      //     youshi: el.youshi, // 优势度
      //   });
      // });

      this.$http.post(
          `/cognize/EPRT`,
          {
            userId: this.userId,
            testPlanId: this.$route.query.testPlanId || "",
            results: this.testList,
          },
          (response) => {
            this.isLoading = false;
            if (response && response.code == "200") {
              //跳转新测试结果页面
              this.goTestResult(response.data);
            } else {
              this.$message.error("接口数据出错");
            }
          },
          (err) => {
            this.isLoading = false;
          }
      );

      screenfull.exit();
      this.$message({
        message: "测试结束！",
        type: "success",
      });
    },
    startTest() {
      screenfull.request();
      if (this.testTypeCode == 0) {
        // 生成学习列表
        // this.createStudyList().then(() => {
        //   preloader(this.studyList, () => {
        //     this.testList = this.studyList;
        //     this.startTiming();
        //   });
        // });
      } else if (this.testTypeCode == 1) {
        // 生成练习测试列表
        // this.createPriticeList().then(() => {
        //   preloader(this.practiceList, () => {
        //     this.testList = this.practiceList;
        //     this.startTiming();
        //   });
        // });

        this.testList = this.randomList(fearLevel1,5)
        preloader(this.testList, () => {
          this.startTiming();
        });

      } else {
        // 生成正式测试列表
        let allArr = [this.shuffle(fearLevel1),this.shuffle(fearLevel2),this.shuffle(fearLevel3),this.shuffle(fearLevel4)]
        let randomNum = this.shuffle([0,1,2,3]);
        // console.log(allArr,"总数组")
        // console.log(randomNum,"随机序号")

        let itemArr = [...allArr[randomNum[0]],...allArr[randomNum[1]],...allArr[randomNum[2]],...allArr[randomNum[3]]]
        this.testList = itemArr;
        // console.log(this.testList,"最终数组")
        preloader(this.testList, () => {
          this.startTiming();
        });

      }
    },
    // 倒计时三分钟
    threeMinDown() {
      this.countDownStr = "休息一下";

      let seconds = 30;
      this.timerRest = setInterval(()=> {
        if (seconds >= 0) {
          this.countDownStr = seconds
          --seconds;
        } else {
          this.countDownStr = "";
          // this.crossShow = false;
          // this.timingShow = false;
          this.showImg();
          clearInterval(this.timerRest);
        }
      }, 1000);
    },
  },
  destroyed() {
    clearInterval(this.timingFlag);
    clearInterval(this.timerRest);
    clearTimeout(this.timeImg)
  },
}
</script>

<style scoped>
.butt {
  width: 100px;
  text-align: center;
  border: 1px solid rgb(87, 172, 187);
  opacity: 1;
  border-radius: 10px;
}

.bgAdd {
  width: 150px;
  height: 400px;
  background: url("../../assets/congnitiveAblitity/whiteFlag-new.png") no-repeat center;
  position: absolute;
  top: 25%;
  left: 50%;
  margin-left: -75px;
}

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

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

.test-content {
  width: 100%;
  padding-top: 15vh;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}
.test-content-opt {
  width: 45%;
}

/* .active-img {
  position: absolute;
  width: 450px;
  height: 450px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
} */
.btn-content {
  width: 70%;
  /*text-align: center;*/
  /*position: absolute;*/
  /*left: 50%;*/
  /*transform: translate(-50%);*/
  margin-top: 26px;
  /*z-index: 1000;*/
  display: flex;
  flex-direction: row;
  justify-content: space-between;

}

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

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

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

.guider {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: rgba(0, 0, 0, 0.75);
}

.addImg {
  width: 40%;
  height: auto;
  z-index: 1000;
}

.shape_glass {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  height: auto;
  /*min-height: 60%;*/
  /*margin: 2vh auto 0;*/
}
.shape_glass img {
  width: 100%;
}

.active {
  position: relative;
}

.active:after {
  background-color: #2ea598;
}

/* 设置动画后颜色 */
.active:before {
  background-color: rgba(0, 168, 253, 0.2);
}

/* 设置动画 */
.active:before,
.active:after {
  content: "";
  width: 80px;
  height: 40px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -40px;
  margin-top: -20px;
  border-radius: 10%;
  animation: warn 1.5s ease-out 0s infinite;
}

@keyframes warn {
  0% {
    transform: scale(1.3);
    opacity: 0.6;
  }

  50% {
    transform: scale(1.4);
    opacity: 0.3;
  }

  100% {
    transform: scale(1.5);
    opacity: 0.1;
  }
}

.txt {
  width: 300px;
  margin: 0 auto;
  font-size: 16px;
  color: #ffffff;
  position: absolute;
  left: 50%;
  top: 70%;
  transform: translateX(-50%);
  z-index: 1000;
}

.explain {
  padding: 6px 8px;
  border: 2px solid #0abdc4;
  border-radius: 5px;
}

.block {
  width: 100%;
  /*margin: 7vw auto 0;*/
}

.block .slider {
  display: flex;
  align-items: center;
  margin-top: 30px;
  flex-direction: row;
  justify-content: flex-start;
}

.block .slider i {
  font-size: 18px;
  margin-right: 5px;
}

.slider .slide-item {
  width: 70%;
  margin-left: 20px;
  position: relative;
}
.slider .slider-title {
  width: 55px;
}
.slide-item .slide-item-left {
  position: absolute;
  left: -12px;
  top: -10px;
  font-size: 12px;
  color: #909399;
}
.slide-item .slide-item-right {
  position: absolute;
  right: -12px;
  top: -10px;
  font-size: 12px;
  color: #909399;
}

.choose {
  color: #19b381;
  border: 2px solid #19b381;
}
</style>
