<template>
  <!--<div>波士顿测试</div>-->
  <div class="boston-box">
    <div class="boston-warp">
      <div
        class="modelName"
        style="position: absolute; left: 20px; top: 20px; z-index: 10"
      >
        {{ showCover ? "观看模式" : "控制模式" }}
      </div>
      <div
        style="
          position: absolute;
          right: 20px;
          top: 20px;
          z-index: 10;
          padding: 20px;
        "
        @click.stop="screen()"
      >
        <img src="../../assets/small-big.png" alt="" />
      </div>

      <div v-if="timingShow" class="timing-content">
        <!--<p class="timing-des">{{timingDes}}</p>-->
        <p class="timing-num">{{ countDownStr }}</p>
      </div>

      <div v-if="!timingShow" class="prograss-content">
        <el-progress
        class="main_progress"
          :text-inside="true"
          :stroke-width="16"
          color="#57ACBB"
          :percentage="setItemProgress(scale_index, scale_all)"
          v-if="!isNaN(parseInt((scale_index / scale_all) * 100))"
          :format="setItemText(scale_index, scale_all)"
        ></el-progress>
      </div>

      <div v-if="!timingShow" class="pic-warp">
        <div class="pic-content">
          <img :src="imgUrl" alt="" />
        </div>

        <div class="btn-content">
          <!--<el-button @click="sentChoice(1)">回答</el-button>-->
          <!--<el-button @click="sentChoice(2)">提示</el-button>-->
          <!--<el-button @click="sentChoice(3)">辨认</el-button>-->
          <!--<el-button @click="sentChoice(4)">错误</el-button>-->
          <el-radio
            v-model="radio"
            @change="sentChoice(1)"
            :label="1"
            size="small"
            border
            >回答</el-radio
          >
          <el-radio
            v-model="radio"
            @change="sentChoice(2)"
            :label="2"
            size="small"
            border
            >提示</el-radio
          >
          <el-radio
            v-model="radio"
            @change="sentChoice(3)"
            :label="3"
            size="small"
            border
            >辨认</el-radio
          >
          <el-radio
            v-model="radio"
            @change="sentChoice(4)"
            :label="4"
            size="small"
            border
            >错误</el-radio
          >
        </div>
      </div>

      <div v-if="!timingShow && role == 'doc'" class="btn-switch-content">
        <div>
          <el-button v-if="scale_index != 1" @click="prevClick()"
            >上一题</el-button
          >
        </div>
        <div>
          <el-button v-if="scale_index != 30" @click="nextClick()"
            >下一题</el-button
          >
        </div>
      </div>
    </div>
    <el-radio-group
      @change="changeMaster"
      v-if="role == 'doc'"
      v-model="radio1"
      class="contral_group"
    >
      <el-radio-button label="patient">用户控制</el-radio-button>
      <el-radio-button label="doc">医生控制</el-radio-button>
    </el-radio-group>
    <div class="cover" v-show="showCover" @click="disableHandle"></div>

    <!-- 选择文化程度 -->
    <el-dialog
        :z-index="95"
        title="请选择学历"
        :visible.sync="dialogEducationVisible"
        width="30%"
        :modal="true"
        :show-close="false"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
    >
      <el-radio-group v-model="qualification" @change="changeQualification">
        <el-radio :label="1">初中及以下</el-radio>
        <el-radio :label="2">高中</el-radio>
        <el-radio :label="3">大学及以上</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="computeSum(true)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { oSessionStorage, preloader } from "@/utils/utils";
import screenfull from "screenfull";

export default {
  name: "bostonTask",
  data() {
    return {
      picList: [
        {
          index: 0,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/shu.jpg"),
          picName: "树",
          picChoice: 0,
        },
        {
          index: 1,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/bi.jpg"),
          picName: "笔",
          picChoice: 0,
        },
        {
          index: 2,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/jiandao.jpg"),
          picName: "剪刀",
          picChoice: 0,
        },
        {
          index: 3,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/hua.jpg"),
          picName: "花",
          picChoice: 0,
        },
        {
          index: 4,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/juzi.jpg"),
          picName: "锯子",
          picChoice: 0,
        },
        {
          index: 5,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/saoba.jpg"),
          picName: "扫把",
          picChoice: 0,
        },
        {
          index: 6,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/donggu.jpg"),
          picName: "冬菇",
          picChoice: 0,
        },
        {
          index: 7,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/yijia.jpg"),
          picName: "衣架",
          picChoice: 0,
        },
        {
          index: 8,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/lunyi.jpg"),
          picName: "轮椅",
          picChoice: 0,
        },
        {
          index: 9,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/luotuo.jpg"),
          picName: "骆驼",
          picChoice: 0,
        },
        {
          index: 10,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/yumaoqiupai.jpg"),
          picName: "羽毛球拍",
          picChoice: 0,
        },
        {
          index: 11,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/woniu.jpg"),
          picName: "蜗牛",
          picChoice: 0,
        },
        {
          index: 12,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/haima.jpg"),
          picName: "海马",
          picChoice: 0,
        },
        {
          index: 13,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/feibiao.jpg"),
          picName: "飞镖",
          picChoice: 0,
        },
        {
          index: 14,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/kouqin.jpg"),
          picName: "口琴",
          picChoice: 0,
        },
        {
          index: 15,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/xiniu.jpg"),
          picName: "犀牛",
          picChoice: 0,
        },
        {
          index: 16,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/bingwu.jpg"),
          picName: "冰屋",
          picChoice: 0,
        },
        {
          index: 17,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/xianrenzhang.jpg"),
          picName: "仙人掌",
          picChoice: 0,
        },
        {
          index: 18,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/fushoudianti.jpg"),
          picName: "扶手电梯",
          picChoice: 0,
        },
        {
          index: 19,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/shuqin.jpg"),
          picName: "竖琴",
          picChoice: 0,
        },
        {
          index: 20,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/tingzhenqi.jpg"),
          picName: "听诊器",
          picChoice: 0,
        },
        {
          index: 21,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/jinzita.jpg"),
          picName: "金字塔",
          picChoice: 0,
        },
        {
          index: 22,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/loudou.jpg"),
          picName: "漏斗",
          picChoice: 0,
        },
        {
          index: 23,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/shoufengqin.jpg"),
          picName: "手风琴",
          picChoice: 0,
        },
        {
          index: 24,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/yuangui.jpg"),
          picName: "圆规",
          picChoice: 0,
        },
        {
          index: 25,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/sanjiaojia.jpg"),
          picName: "三脚架",
          picChoice: 0,
        },
        {
          index: 26,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/qian.jpg"),
          picName: "钳",
          picChoice: 0,
        },
        {
          index: 27,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/huapeng.jpg"),
          picName: "花棚",
          picChoice: 0,
        },
        {
          index: 28,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/liangjiaoqi.jpg"),
          picName: "量角器",
          picChoice: 0,
        },
        {
          index: 29,
          imgUrl: require("../../assets/congnitiveAblitity/bostonTask/suanpan.jpg"),
          picName: "算盘",
          picChoice: 0,
        },
      ],
      imgUrl: "", //初始化图片地址
      count: 0, //累加器初始化
      subjectInfo: "",
      userId: "",
      taskId: "",
      timingShow: true, //显示倒计时
      timingFlag: null, //倒计时名称
      countDownStr: "测试马上开始！",
      timingNum: 5, //倒计时初始化时间
      rightNum: [], //正确数组
      tipNum: [], //提示数组
      identifyNum: [], //辨认数组
      errorNum: [], //回答错误数组
      scale_index: 1, //初始化进度条个数
      scale_all: 30, //进度条总个数
      radio: 0, //选项值
      webSocket: {},
      role: "",
      toUserId: "",
      radio1: "doc",
      // webSocket: "",
      qualification: 1,
      dialogEducationVisible: false,
    };
  },
  computed: {
    showCover: function () {
      return this.role == this.radio1 ? false : true;
    },
  },
  watch: {
    count(val) {
      if (val >= 30) {
        this.scale_index = 30;
      } else {
        this.scale_index = val + 1;
      }
    },
  },
  created() {
    this.chooseRole();
    //绑定事件
    window.addEventListener('beforeunload', e => this.closeWebsocket(e));
  },
  mounted() {},
  methods: {
    init() {
      this.subjectInfo = JSON.parse(oSessionStorage.getItem("subjectInfo"));
      this.userId = sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f");
      this.toUserId =
        this.role == "doc" ? `${this.userId}patient` : `${this.userId}doc`;
      this.taskId = this.$route.query.taskId;
      this.creatScoket();
      this.screen();
      this.startTiming();
    },
    screen() {
      screenfull.toggle();
    },
    screenOpen() {
      screenfull.request();
    },
    screenExit() {
      screenfull.exit();
    },
    setItemProgress(currentIndex, totalIndex) {
      if (currentIndex >= totalIndex) {
        return 100;
      } else {
        return (currentIndex / totalIndex) * 100;
      }
    },
    setItemText(currentIndex, totalIndex) {
      return () => {
        return currentIndex + "/" + totalIndex;
      };
    },
    startTiming() {
      // if (
      //     sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
      //     sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      // ) {
      //     this.$message.error("请先登录！");
      //     return;
      // }

      this.timingFlag = setInterval(() => {
        if (this.timingNum == 0) {
          this.countDownStr = "开始";

          setTimeout(() => {
            //关闭倒计时提示页面
            this.timingShow = false;

            this.timingFlag = clearInterval(this.timingFlag);
            // 预加载图片后开始测试
            preloader(this.picList, () => {
              //开始第一张照片
              this.changePic(this.count);
            });
          }, 1000);

          this.timingFlag = clearInterval(this.timingFlag);
        } else {
          this.countDownStr = this.timingNum;
          this.timingNum--;
        }
      }, 1000);
    },
    sentChoice(type) {
      if (
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == "" ||
        sessionStorage.getItem("b80bb7740288fda1f201890375a60c8f") == null
      ) {
        this.$message.error("请先登录！");
        return;
      }

      // 获取选项值
      this.picList[this.count].picChoice = type;

      //累加器自增
      this.count++;

      if (this.count > 29) {
        //统计选项各回答个数
        // this.rightNum = [];
        // this.tipNum = [];
        // this.identifyNum = [];
        // this.errorNum = [];
        //
        // this.picList.map((item, index) => {
        //   switch (item.picChoice) {
        //     case 1:
        //       this.rightNum.push(this.picList[index]);
        //       break;
        //     case 2:
        //       this.tipNum.push(this.picList[index]);
        //       break;
        //     case 3:
        //       this.identifyNum.push(this.picList[index]);
        //       break;
        //     case 4:
        //       this.errorNum.push(this.picList[index]);
        //       break;
        //   }
        // });
        //调用数据统计接口
        // this.$http.post(
        //   `/cognize/BSNTask`,
        //   {
        //     qualification: this.qualification,
        //     userId: this.userId,
        //     testPlanId: this.$route.query.testPlanId || "",
        //     result: {
        //       rightNum: this.rightNum.length,
        //       tipNum: this.tipNum.length,
        //       identifyNum: this.identifyNum.length,
        //       errorNum: this.errorNum.length,
        //       picList: this.picList,
        //     },
        //   },
        //   (response) => {
        //     if (response) {
        //       let routerInfo = {
        //         name: "TestResult",
        //         params: {
        //           result: [
        //             {
        //               name: "回答正确个数",
        //               value: this.rightNum.length + "",
        //             },
        //             {
        //               name: "提示回答个数",
        //               value: this.tipNum.length + "",
        //             },
        //             {
        //               name: "辨认回答个数",
        //               value: this.identifyNum.length + "",
        //             },
        //             {
        //               name: "回答错误个数",
        //               value: this.errorNum.length + "",
        //             },
        //           ],
        //         },
        //       };
        //       // 向非控制端发送结束通知
        //       if (!this.showCover) {
        //         // this.sendMsgHandle(4104, routerInfo);
        //           this.sendMsgHandle(4104, response.data);
        //       }
        //       // 跳转到结果页面
        //       // this.$router.push(routerInfo);
        //       //跳转新测试结果页面
        //       this.goTestResult(response.data);
        //       //关闭socket
        //       this.closeWebsocket()
        //     }
        //   }
        // );
        //
        // this.$message({
        //   message: "测试结束",
        //   type: "success",
        // });
        // //提交数据或跳转得分页
        // this.screenExit();
        // this.$router.push("/welcome/CognitiveAbility");

        this.computeSum(false);
      } else {
        //切换图片
        this.changePic(this.count);
        // 发送同步通知
        this.sendMsgHandle(4101, type);
      }
    },
    computeSum (hasQualification){
      if (hasQualification) {

        this.rightNum = [];
        this.tipNum = [];
        this.identifyNum = [];
        this.errorNum = [];

        this.picList.map((item, index) => {
          switch (item.picChoice) {
            case 1:
              this.rightNum.push(this.picList[index]);
              break;
            case 2:
              this.tipNum.push(this.picList[index]);
              break;
            case 3:
              this.identifyNum.push(this.picList[index]);
              break;
            case 4:
              this.errorNum.push(this.picList[index]);
              break;
          }
        });

        this.$http.post(
            `/cognize/BSNTask`,
            {
              qualification: this.qualification,
              userId: this.userId,
              testPlanId: this.$route.query.testPlanId || "",
              result: {
                rightNum: this.rightNum.length,
                tipNum: this.tipNum.length,
                identifyNum: this.identifyNum.length,
                errorNum: this.errorNum.length,
                picList: this.picList,
              },
            },
            (response) => {
              if (response) {
                // 向非控制端发送结束通知
                if (!this.showCover) {
                  // this.sendMsgHandle(4104, routerInfo);
                  this.sendMsgHandle(4104, response.data);
                }
                //跳转新测试结果页面
                this.goTestResult(response.data);
                //关闭socket
                this.closeWebsocket()
              }
            }
        );

        this.$message({
          message: "测试结束",
          type: "success",
        });
        //提交数据或跳转得分页
        this.screenExit();
      }else {
        this.dialogEducationVisible = true;
        this.sendMsgHandle(4105, true);
      }
    },
    changePic(param) {
      this.imgUrl = this.picList[param].imgUrl;
      // 绑定回答选项值
      this.radio = this.picList[param].picChoice;
      console.log(this.radio, "选项值");
    },
    prevClick() {
      this.count--;
      this.changePic(this.count);
      this.sendMsgHandle(4102, "");
    },
    nextClick() {
      if (this.picList[this.count].picChoice == 0) {
        this.$message.error("请先答本题！");
      } else {
        this.count++;
        this.changePic(this.count);
        this.sendMsgHandle(4103, "");
      }
    },
    // 选择身份
    chooseRole() {
      this.$confirm("请选择你的身份，医生还是普通用户", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "医生",
        cancelButtonText: "普通用户",
        type: "info",
      })
        .then(() => {
          this.role = "doc";
          this.init();
        })
        .catch(() => {
          this.role = "patient";
          this.init();
        });
    },

    // 切换控制权限
    changeMaster() {
      let msg = {
        toUserId: this.toUserId,
        message: {
          msg: "角色切换",
          master: this.radio1 == this.role,
        },
      };
      console.log(msg);
      this.webSocket.send(JSON.stringify(msg));
    },

    // 创建socket连接
    creatScoket() {
      this.webSocket = new WebSocket(`${scoketUrl}${this.userId}${this.role}`);
      console.log("连接成功");
      this.webSocket.onerror = (event) => {
        alert("连接错误");
      };

      this.webSocket.onopen = (event) => {
        //alert("open"+event.data);
        //console.log(event);
      };

      this.webSocket.onclose = (event) => {
        alert("服务不存在或者被关闭");
      };

      this.webSocket.onmessage = (event) => {
        let data = JSON.parse(event.data);
        if (!data.message) {
          // if (data.code == "201") {
          //   this.chooseRole();
          //   this.$message.error(data.msg);
          // }
        } else {
          this.receiveMsgHandle(data.message);
        }
      };
    },

    // 接收消息处理方法
    receiveMsgHandle(res) {
      // 切换控制权权
      if (res.master == undefined) {
        if (res.eventNo == 4101) {
          console.log(res.data);
          this.sentChoice(res.data);
        }

        if (res.eventNo == 4102) {
          this.prevClick();
        }

        if (res.eventNo == 4103) {
          this.nextClick();
        }

        if (res.eventNo == 4104) {
          screenfull.exit();
          // this.$router.push(res.data);
          //跳转新测试结果页面
          this.goTestResult(res.data);
        }

        //学历弹窗控制
        if (res.eventNo == 4105) {
          this.dialogEducationVisible = res.data;
        }
        if (res.eventNo == 4106) {
          this.qualification = res.data;
        }
      } else {
        this.radio1 = res.master ? "doc" : "patient";
      }
    },

    // 发送消息处理方法
    sendMsgHandle(No, data) {
      let msg = {
        toUserId: this.toUserId,
        message: {
          msg: "发送成功",
          eventNo: No,
          data: data,
        },
      };
      this.webSocket.send(JSON.stringify(msg));
    },
    // 禁止操作
    disableHandle() {
      this.$message.warning("您暂时不需要操作，请耐心等待");
    },
    //关闭websocket
    closeWebsocket(e){
        if(this.webSocket){
            this.webSocket.close();
            // let _this=this
            this.webSocket.onclose = function(evt) {
                console.log("websocket已关闭");
            };
        }
    },
    changeQualification(){
      this.sendMsgHandle(4106, this.qualification);
    },
  },
  beforeDestroy() {
      //卸载事件
      window.removeEventListener('beforeunload', e => this.closeWebsocket(e))
  },
  destroyed() {
    clearInterval(this.timingFlag);
    //关闭socket
    this.closeWebsocket()
  },
};
</script>

<style scoped>
.boston-box {
  width: 100%;
  height: 100%;
}
.boston-warp {
  width: 100%;
  height: 100%;
  background: url(../../assets/congnitiveAblitity/zhixing.png) no-repeat center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  z-index: 2;
}
.prograss-content {
  width: 800px;
}
.pic-warp {
  width: 650px;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}
.pic-content {
  width: 380px;
  height: 380px;
  border-radius: 5px;
  /*background: #000;*/
  text-align: center;
}
.pic-content img {
  /*width: 100%;*/
  /*height: 100%;*/
  max-height: 100%;
  max-width: 100%;
  vertical-align: middle;
  margin: 0 auto;
}
.btn-content {
  width: 100px;
  height: 380px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
.btn-content .el-radio {
  background: #fff;
  border-radius: 8px;
  margin: 0 !important;
}
.btn-switch-content {
  width: 600px;
  height: 50px;
  /*margin-top: 60px;*/
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.btn-content .el-button,
.btn-switch-content .el-button {
  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: #fff;
}
.btn-content .el-button:hover,
.btn-switch-content .el-button:hover {
  color: rgb(87, 172, 187);
  background: #fff;
  border: 2px solid rgb(87, 172, 187);
}
.timing-content {
  width: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: black;
  font-size: 70px;
  text-align: center;
  line-height: 100px;
}

.contral_group {
  position: fixed;
  bottom: 5%;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}

.cover {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  z-index: 99;
  background: #ddd;
  opacity: 0.2;
}
</style>
