<template>
  <div class="liuyan">
    <back title="模拟考试"></back>
    <div class="lx">
      <div class="times">剩余时间：{{ time_str }}</div>
      <div v-if="current_question_data.type == 13">
        <div class="lianxiTiMu">
          <span class="lianxiTiMu1">是非题</span>
          <span>{{ current_question_data.name }}</span>
        </div>
        <div
          class="lianxiTiMu"
          v-for="(item, index) in current_question_data.content"
          :key="index"
          @click="responseQ(item)"
        >
          <span
            class="lianxiXueZe"
            v-bind:class="{ active: current_question_data.response == item }"
            >{{ xuhao[index] }}</span
          >
          <span class="lianxiXueZe1">{{ item }}</span>
        </div>
      </div>
      <div v-if="current_question_data.type == 3">
        <div class="lianxiTiMu">
          <span class="lianxiTiMu1">单选题</span>
          <span>{{ current_question_data.name }}</span>
        </div>
        <div
          class="lianxiTiMu"
          v-for="(item, index) in current_question_data.content"
          :key="index"
          @click="responseQ(item)"
        >
          <span
            class="lianxiXueZe"
            v-bind:class="{ active: current_question_data.response == item }"
            >{{ xuhao[index] }}</span
          >
          <span class="lianxiXueZe1">{{ item }}</span>
        </div>
      </div>
      <div v-if="current_question_data.type == 4">
        <div class="lianxiTiMu">
          <span class="lianxiTiMu1">多选题</span>
          <span>{{ current_question_data.name }}</span>
        </div>
        <div
          class="lianxiTiMu"
          v-for="(item, index) in current_question_data.content"
          :key="index"
          @click="responseS(index)"
        >
          <span
            class="lianxiXueZe"
            v-bind:class="{
              active: current_question_data.response.indexOf(index) != -1,
            }"
            >{{ xuhao[index] }}</span
          >
          <span class="lianxiXueZe1">{{ item }}</span>
        </div>
      </div>
      <div v-if="current_question_data.type == 12">
        <div class="lianxiTiMu">
          <span class="lianxiTiMu1">填空题</span>
          <span>{{ current_question_data.name }}</span>
          <!-- <input type="tel" class="flyout" v-model="i.num[index]" ref="verifyCode"/> -->
          <div class="tiankong" v-for="(i, key) in tiankongdata" :key="key">
            <div v-for="(item, index) in i.label.length" :key="index">
              <!-- <div class="tiank">{{i.num[index]}}</div> -->
              <input
                type="text"
                class="tiank"
                maxlength="1"
                v-model="i.num[index]"
                @change="responseC()"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="lianxiBottom">
        <div class="lianxiBottomL">
          <div @click="prevQ">上一题</div>
          <div @click="nextQ">下一题</div>
          <div @click="subQ">交卷</div>
        </div>

        <div class="lianxiBottomR" @click="popupVisible = true">
          <img src="../../../static/img/gengduo.png" alt="" /><span>{{
            current_question + 1
          }}</span
          >/{{ questions.length }}
        </div>
      </div>
    </div>
    <mt-popup v-model="popupVisible" position="bottom">
      <div class="order_number">
        <div
          v-for="(item, index) in questions"
          :key="index"
          @click="goQ(index)"
          v-bind:class="{
            done: item.response != '' && current_question != index,
            error: !item.response && current_question != index,
            active: current_question == index,
          }"
        >
          {{ index + 1 }}
        </div>
      </div>
    </mt-popup>
    <WXTake ref="wxchild" @result="printResult"></WXTake>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Back from "../common/Back";
import { getStore } from "@/utils/storage";
import { Toast } from "mint-ui";
import { MessageBox } from "mint-ui";
import WXTake from "../study/weixinTake.vue";
export default {
  name: "LiuYan",
  components: { Back, WXTake },
  data() {
    return {
      id: "",
      config: {},
      exam_data: {},
      xuhao: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"],
      questions: [],
      current_question: 0,
      current_question_data: {},
      popupVisible: false,
      timer: "",
      time_str: "",
      tiankongdata: [],
      submitCount: 0, //开启相机的次数
      canTakePhoto: true, //节流，十秒内只执行一次，能否拍照
      isFaceDetected: false, //是否成功检测过一次人脸
      exam_alltime: "", //考试时长
      currenttime: 1, //当前考试时间
    };
  },
  methods: {
    bulrinput() {
      this.$refs.verifyCode.focus();
    },
    start() {
      // // 获取现在的时间戳（毫秒）
      var current_time_stamp = new Date().getTime();
      // console.log('course_id:'+this.$route.query.course_id)
      this.getData("/Question/getSimulatedQuestions", {
        token: getStore("token"),
        course_id: this.$route.query.course_id,
      }).then(
        (data) => {
          if (data.code == 1) {
            let _this = this;
            // this.is_start = 1;
            this.id = data.data.id;
            this.config = data.data;
            // console.log(data.data.id,"--------------");
            // console.log(this.$route.query.course_id)
            this.questions = data.data.question_data;
            // console.log(data.data.question_data);
            this.current_question_data = data.data.question_data[0];
            //此处增加一个针对所以普的条填空题的答案的循环，调用后面的判断每个标点写道界面上面的值
            //字符串变成数组！！随便写

            var count = 1;
            //var b = str.split(''); //[a, b, +, c, +, d, e]
            //var daanshuzu=daan.split('')
            //调用通用的方法把标点显示出来
            // console.log(this.current_question_data,"----------------")
            if (this.current_question_data.type == 12) {
              this.tk(this.current_question_data.answer.split("*"));
            }

            this.exam_data = data.data.exam_data;
            this.exam_alltime = data.data.exam_data.remain_time;
            this.timer = setInterval(function () {
              var nowonceTime = new Date().getTime();
              if (_this.exam_data.remain_time > 0) {
                //过了多少秒，因为setInterval方法倒计时并不准确，这里使用算法让倒计时尽量准确一些
                var jiange = (nowonceTime - current_time_stamp) / 1000 - count;
                count = (nowonceTime - current_time_stamp) / 1000;
                _this.exam_data.remain_time = _this.exam_data.remain_time - jiange;
              } else {
                _this.time_str = "时间结束";
                _this.subQ();
                clearInterval(_this.timer);
              }
              let times = _this.exam_data.remain_time;
              _this.currenttime = parseInt(_this.exam_alltime - times);
              if (times > 60) {
                _this.time_str =
                  parseInt(times / 60.0) +
                  "分" +
                  parseInt((parseFloat(times / 60.0) - parseInt(times / 60.0)) * 60) +
                  "秒";
              } else {
                _this.time_str = parseInt(times) + "秒";
              }

              // 计算过了多少时间，人脸检测

              var timePassed = 5400 - _this.exam_data.remain_time;

              timePassed = Math.trunc(timePassed);
              // console.log(timePassed);

              // 先提示用户准备人脸检测
              if (
                (timePassed == 895 ||
                  timePassed == 2695 ||
                  timePassed == 4495 ||
                  timePassed == 6295) &&
                _this.loginInfo.need_check_face == 1
              ) {
                Toast("稍后开启相机，进行人脸检测，请做好准备");
              }
              // 拍照
              if (
                (timePassed == 900 ||
                  timePassed == 2700 ||
                  timePassed == 4500 ||
                  timePassed == 6300) &&
                _this.loginInfo.need_check_face == 1
              ) {
                if (_this.canTakePhoto) {
                  _this.canTakePhoto = false;
                  _this.partakePhoto();
                  setTimeout(() => {
                    _this.canTakePhoto = true;
                  }, 10000);
                }
              }
            }, 1000);
          } else {
            Toast(data.msg);
          }
        },
        (err) => {}
      );
    },
    //传递进来当前填空题的前端填写的再绑定和答案内容
    tk(daan) {
      let _this = this;
      _this.tiankongdata = [];
      let bb = this.questions[this.current_question].response;

      if (bb.length > 0) {
        let cc = bb.split("*");

        for (var i = 0; i < daan.length - 1; i++) {
          var json = {
            label: daan[i],
            num: cc[i].split("|"),
          };
          _this.tiankongdata.push(json);
        }
      } else {
        for (var i = 0; i < daan.length - 1; i++) {
          var json = {
            label: daan[i],
            num: [],
          };
          _this.tiankongdata.push(json);
        }
      }
      // console.log(_this.tiankongdata);

      // daan.forEach(function(data,i){
      //   var str=['，','。','、',',','.'] //定义一个能够被使用的标点符号集合，这块补充全面，足以注意徐弘雯应中文英文都需要考虑的
      //   //如果是文字。就跳出，如果是标点，就放到具体的位置上面
      //   if(str.indexOf(data)>=0){
      //     //faxian标点，就把标点昂到卡暖绑定的数组相应的位置显示
      //     _this.current_question_data.response[i] = data
      //     setTimeout(function(){
      //       document.getElementById('tk'+i).disabled = true
      //     },100)
      //   }else{
      //     setTimeout(function(){
      //      document.getElementById('tk'+i).disabled = false
      //     },100)
      //   }
      // })
    },
    prevQ() {
      if (this.current_question <= 0) {
        Toast("已是第一题");
      } else {
        this.current_question--;
        this.current_question_data = this.questions[this.current_question];

        if (this.current_question_data.type == 12) {
          this.tk(this.current_question_data.answer.split("*"));
        }
      }
    },
    nextQ() {
      if (this.current_question >= this.questions.length - 1) {
        Toast("已是最后一题");
      } else {
        this.current_question++;
        this.current_question_data = this.questions[this.current_question];
        if (this.current_question_data.type == 12) {
          this.tk(this.current_question_data.answer.split("*"));
        }
      }
    },
    responseQ(item) {
      this.questions[this.current_question].response = item;
      this.current_question_data = {};
      this.current_question_data = this.questions[this.current_question];
    },
    responseS(item) {
      let arr = this.questions[this.current_question].response;
      if (!arr) {
        this.questions[this.current_question].response = [item];
        return;
      }
      let index;
      index = arr.indexOf(item);
      if (index == -1) {
        this.questions[this.current_question].response.push(item);
      } else {
        this.questions[this.current_question].response.splice(index, 1);
      }
      this.current_question_data = {};
      this.current_question_data = this.questions[this.current_question];
    },
    responseC() {
      var str = "";
      for (let i = 0; i < this.tiankongdata.length; i++) {
        var aa = this.tiankongdata[i].num;
        for (var j = 0; j < aa.length; j++) {
          str += aa[j];
          str += "|";
        }
        str += "*";
        // console.log(this.tiankongdata[i].num)
      }
      this.questions[this.current_question].response = str;
    },
    /*对焦到下一个input框去*/
    // @keyup="nextFocus($event,index)"
    // nextFocus(el,index){
    //   var dom = document.getElementsByClassName("tiank");//document.getElementById('tk'+index)
    //   var currInput = dom[index];
    //   var nextInput = dom[index + 1];
    //   var lastInput = dom[index - 1];
    //   console.log(1,dom)
    //   for (let i=0;i<this.tiankongdata.length;i++){
    //     if (el.keyCode != 8) {
    //       if (index < (this.tiankongdata[i].label.length)) {
    //           nextInput.focus();
    //       } else {
    //           currInput.blur();
    //       }
    //     }else{
    //         if (index !=0) {
    //             lastInput.focus();
    //         }
    //     }
    //   }
    // },

    goQ(index) {
      this.current_question = index;
      this.current_question_data = this.questions[this.current_question];
    },
    subQ() {
      if (this.currenttime >= 1200) {
        let subQuestions = this.questions;
        // console.log(this.questions)
        for (let i = 0; i < subQuestions.length; i++) {
          if (subQuestions[i].type == 4) {
            let arr = subQuestions[i].response;
            //let newArr = arr.sort(compare);
            let newArr = arr;
            let res = "";
            for (let j = 0; j < newArr.length; j++) {
              res += subQuestions[i].content[newArr[j]];
              if (j < newArr.length - 1) {
                res += "|";
              }
            }
            subQuestions[i].response = res;
          }

          if (subQuestions[i].type == 12) {
            let arrT = subQuestions[i].response;
            if (typeof arrT == "string") {
              subQuestions[i].response = arrT.replace(/\|/g, "");
            }
          }
        }
        // console.log("hahahaha",subQuestions)
        // return
        this.getData("/Question/sendSimulated", {
          token: getStore("token"),
          content: JSON.stringify(subQuestions),
          id: this.id,
          num: "2",
        }).then(
          (data) => {
            // console.log(data.code + "----------");
            if (data.code == 1) {
              if (data.data.is_standard == 1) {
                MessageBox.alert(
                  "您的考试成绩为" + data.data.score + "分，通过了本次考试",
                  "恭喜"
                ).then((action) => {
                  this.$router.push({ path: "/" });
                });
              } else {
                MessageBox({
                  message:
                    "考试剩余时间为" +
                    this.time_str +
                    "，是否<b style='color:red;'>继续答题</b>？",
                  showConfirmButton: true,
                  showCancelButton: true,
                  confirmButtonText: "继续答题",
                  cancelButtonText: "提交考卷",
                  confirmButtonHighlight: true,
                }).then((action) => {
                  if (action == "confirm") {
                  } else {
                    MessageBox.alert(
                      "您的考试成绩为" + data.data.score + "分，暂未通过本次考试",
                      "抱歉"
                    ).then((action) => {
                      this.$router.push({ path: "/" });
                    });
                  }
                });

                // MessageBox.alert(
                //   "您的考试成绩为" +
                //     data.data.score +
                //     "分，暂未通过本次考试，是否继续答题？",
                //   "抱歉"
                // ).then((action) => {
                //   // this.$router.push({path: '/'});
                // });
              }
            } else {
              Toast(data.msg);
            }
          },
          (err) => {}
        );
      } else {
        Toast("考试20分钟以后才可交卷，请耐心等待");
      }
    },

    //直接提交，当人脸检测三次失败
    directSubQ() {
      let subQuestions = this.questions;
      for (let i = 0; i < subQuestions.length; i++) {
        if (subQuestions[i].type == 4) {
          let arr = subQuestions[i].response;
          let newArr = arr;
          let res = "";
          for (let j = 0; j < newArr.length; j++) {
            res += subQuestions[i].content[newArr[j]];
            if (j < newArr.length - 1) {
              res += "|";
            }
          }
          subQuestions[i].response = res;
        }

        if (subQuestions[i].type == 12) {
          let arrT = subQuestions[i].response;
          if (typeof arrT == "string") {
            subQuestions[i].response = arrT.replace(/\|/g, "");
          }
        }

        //判断做对了几道题
        if (subQuestions[i].response == subQuestions[i].answer) {
          this.true_quesstion++;
        }

        if (this.config.exam_type == 1) {
          this.getData("/Question/sendExam", {
            token: getStore("token"),
            content: JSON.stringify(subQuestions),
            course_id: this.courseID,
          }).then(
            (data) => {
              if (data.code == 1) {
                if (data.data.is_standard == 1) {
                  MessageBox.alert(
                    "您的考试成绩为" + data.data.score + "分，通过了本次考试",
                    "恭喜"
                  ).then((action) => {
                    this.$router.push({ path: "/" });
                  });
                } else {
                  MessageBox.alert(
                    "您的考试成绩为" + data.data.score + "分，未通过本次考试",
                    "抱歉"
                  ).then((action) => {
                    this.$router.push({ path: "/" });
                  });
                }
              } else {
                Toast(data.msg);
              }
            },
            (err) => {}
          );
        } else if (this.config.exam_type == 2) {
          this.getData("/Question/sendExamBu", {
            token: getStore("token"),
            content: JSON.stringify(this.questions),
            id: this.exam_data.id,
            num: "3",
          }).then(
            (data) => {
              if (data.code == 1) {
                if (data.data.is_standard == 1) {
                  MessageBox.alert(
                    "您的考试成绩为" + data.data.score + "分，通过了本次补考",
                    "恭喜"
                  ).then((action) => {
                    this.$router.push({ path: "/" });
                  });
                } else {
                  MessageBox.alert(
                    "您的考试成绩为" + data.data.score + "分，未通过本次补考",
                    "抱歉"
                  ).then((action) => {
                    this.$router.push({ path: "/" });
                  });
                }
              } else {
                Toast(data.msg);
              }
            },
            (err) => {}
          );
        } else {
          Toast("非法操作");
        }
      }
    },
    partakePhoto() {
      this.$refs.wxchild.takePhoto();
    },

    printResult(e1, e2) {
      if (e2 == 0) {
      } else {
        console.log("识别结果：", e1);
        if (e1 == "success") {
          Toast("识别成功，请继续答题");
          this.submitCount = 0;
          this.isFaceDetected = true;
        } else {
          this.submitCount = this.submitCount + 1;
          if (this.submitCount > 2) {
            //清空调用相机的次数
            this.submitCount = 0;
            setTimeout(() => {
              Toast("人脸检测失败，在正式考试中，系统将会自动提交考卷");
            }, 5000);
          } else {
            setTimeout(() => {
              // Toast("第" + (this.submitCount + 1) + "次开启相机,请重新拍照提交");
              Toast("将再次打开相机，请重新拍照提交");
            }, 5000);
            setTimeout(() => {
              this.partakePhoto();
            }, 10000);
          }
        }
      }
    },
  },

  mounted() {
    console.log(this.loginInfo);

    this.start();
  },
  computed: {
    ...mapState(["loginInfo"]),
  },
  destroyed() {
    window.removeEventListener("popstate", this.fun, false); //false阻止默认事件
  },
};
</script>

<style lang="scss" scoped>
.liuyan {
  padding-top: 5rem;
  .exam-info {
    width: 80%;
    margin: 0 auto;
    text-align: left;
    font-size: 1.35rem;
    line-height: 2rem;
    > div {
      margin-bottom: 2rem;
      p {
        font-size: 1.5rem;
        &.active {
          color: #e60012;
        }
      }
    }
  }
  .pass-exam {
    width: 80%;
    margin: 10rem auto;
    text-align: center;
    font-size: 3rem;
    line-height: 6rem;
    color: #e60012;
    font-weight: bold;
  }
}
.lx {
  padding-bottom: 5rem;
  .lianxiTiMu {
    width: 90%;
    margin: 2rem auto;
    font-size: 1.56rem;
    font-family: MicrosoftYaHei;
    font-weight: 400;
    text-align: left;
    line-height: 2.5rem;
    color: #333333;
    .lianxiTiMu1 {
      width: 4.9rem;
      line-height: 1.7rem;
      color: #0375e4;
      border: 0.05rem solid #0375e4;
      border-radius: 1rem 0rem 1rem 0rem;
      display: inline-block;
      text-align: center;
      font-size: 1.04rem;
      font-family: MicrosoftYaHei;
      font-weight: 400;
    }
    .lianxiXueZe {
      color: #5e5e5e;
      width: 2.5rem;
      line-height: 2.5rem;
      border: 0.05rem solid #5e5e5e;
      border-radius: 50%;
      display: inline-block;
      font-size: 1.56rem;
      font-family: ArialMT;
      font-weight: 400;
      text-align: center;
      margin-right: 1rem;
      &.active {
        background: #0083ff;
        color: #fff;
        border-color: #0083ff;
      }
    }
    .lianxiXueZe1 {
      color: #5e5e5e;
    }
    &.cuoti {
      color: red;
    }
    .tiankong {
      display: flex;
      flex-wrap: wrap;
      .tiank {
        width: 3rem;
        height: 3rem;
        border: 0.05rem solid #9c9c9c;
        margin: 0.5rem;
        text-align: center;
      }
      .tianks {
        background: red;
      }
    }
  }
  .lianxiBottom {
    width: 100%;
    height: 5rem;
    border-top: 0.05rem solid #9c9c9c;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 2rem;
    font-size: 1.56rem;
    font-family: MicrosoftYaHei;
    font-weight: 400;
    background: white;
    img {
      width: 1.5rem;
      height: 1.5rem;
      margin-right: 0.5rem;
    }
    .lianxiBottomL {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 69%;
      div {
        padding: 0 0.4rem;
        background: #0083ff;
        color: white;
        line-height: 2rem;
        &.disable {
          background: grey;
        }
      }
    }
    .lianxiBottomR {
      color: #a5a5a5;
      span {
        color: #333333;
      }
    }
  }
}
.order_number {
  width: 100vw;
  display: flex;
  flex-wrap: wrap;
  > div {
    width: 10vw;
    font-size: 1.5rem;
    height: 10vw;
    line-height: 10vw;
    border: 1px solid black;
    box-sizing: border-box;
    &.active {
      background: #31a6ff;
    }
    &.error {
      background: red;
    }
    &.done {
      background: yellowgreen;
    }
  }
}
</style>
