<template>
  <div class="li" :class="{ 'disable': !area, 'wait': [0].includes(examState), 'startedAlready': examState == 42 }">
    <div class="userInfo" @click="getChooseStudent">
      <div class="userInfo-center">
        <Transition :enter-active-class="proxy?.animate.dialog.enter">
          <div class="pic" :class="{ 'pic2': faceCheckStu.student_id }" v-if="faceCheckStu.student_id"> <img
              :src="faceCheckStu.face_pic || faceCheckStu.logo_url" /></div>
          <div class="pic" v-else>
            <div class="area">{{ area }}</div>
            <img src="@/assets/images/test/profilePicture2.png" />
          </div>
        </Transition>
        <div class="name" :class="{ 'name2': faceCheckStu.student_id }">
          {{ faceCheckStu.student_id ? faceCheckStu.name : area && ![0].includes(examState) ? examState ==
            41 ? "正在识别" : "虚位以待" : area &&
              [0].includes(examState) ? "离线" : "未启用" }}
        </div>
        <!-- <Transition :enter-active-class="proxy?.animate.hand.enter">
          <div class="ctrlBox"
            v-if="props.examState == 43 && examState == 43 && handcontroller && ctrl == area && faceCheckStu.student_id">
            <img src="@/assets/images/test/jushou.png" />
            <div class="lable">
              请举左手开始
            </div>
          </div>
        </Transition> -->
      </div>
    </div>
    <div class="score">
      {{ currentResultObj.count
        || 0 }}
    </div>
    <!-- <div>当前状态：({{ examState == 3 ? "初始化完成" : examState == 40 ? "创建测试" : examState == 41 ? "正在人脸识别" :examState == 43 ? "停止人脸识别" : examState == 42 ? "正在测试" : "离线状态" }})</div> -->
  </div>
</template>

<script setup lang="ts">
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers';
import dataDictionary from "@/utils/dataDictionary"
// const { initWs, examEnds, openOneTest, startFace, stopFace, faceConfirmOnly, startOneTest, finishOneTest, closeOneTest, suspendFaceRecognitionChannels, resumeFaceRecognitionChannels } = useWs();
const route = useRoute();
const { proxy } = getCurrentInstance() as any;
const emit = defineEmits(['returnData', 'getChooseStudent']);

//父值
const props = defineProps({
  parentTrainWsMethod: {
    type: Object,
    default: {}
  },
  parentSpeechMethod: {
    type: Object,
    default: {}
  },
  area: {
    type: String,
    default: ""
  },
  examState: {
    type: Number,
    default: null
  },
  needStart: {
    type: Boolean,
    default: false
  },
  styleType: {
    type: Number,
    default: null
  },
});

let project: any = route.query.project;
let area: any = props.area;
let examId: string = `${project}_${area}`; //项目+区

const data = reactive<any>({
  examState: 0,//当前状态
  resultId: null,//测试ID
  currentResultObj: {},//成绩
  faceCheckStu: {},//人脸信息
  unit: "",//单位
  backReason: [],//犯规项
  handcontroller: null,//是否开启手势控制
  ctrl: "",//控制位
});
const { examState, resultId, faceCheckStu, currentResultObj, unit, backReason, handcontroller, ctrl } = toRefs(data);

/**
 * 接收消息
*/
const getMessage = (e: any) => {
  //console.log("WS响应：", e)
  //实时状态
  if (e.cmd === 'exam_status') {
    examState.value = e.data;
  }
  //工作站状态
  if (e.cmd === 'init_result') {

  }
  //测试违规
  if (e.cmd === 'warning_result') {
    let message = e.data?.message;
    if (message) {
      proxy?.$modal.msgError(`【${area}】${message}`);
      props.parentSpeechMethod.speckText(`${area}区，${message}`);
    }
  }
  //后端播报语音
  if (e.cmd === 'return_audio_msg') {
    let message = e.data?.message;
    if (message) {
      proxy?.$modal.msgError(`【${area}】${message}`);
      props.parentSpeechMethod.speckText(`${area}区，${message}`);
    }
  }
  //错误提示
  if (e.cmd === 'info_result') {
    proxy?.$modal.msgError(`【${area}】${e.data.message}`);
  }
  //错误提示
  if (e.cmd === 'error_result') {
    proxy?.$modal.msgError(`【${area}】${e.data.message}`);
  }
  //测试中违规提示
  if (e.cmd === 'warning_notify') {

  }
  //断线状态
  if (e.cmd === 'disconnect_request') {
    examState.value = 0;
    emit('returnData', { examState: examState.value, area: area });
    let message = e.data.message;
    if (message) {
      proxy?.$modal.msgError(`【${area}】${message}`);
      //props.parentSpeechMethod.speckText(e.data.message);
    }
  }
  //状态变更
  if (e.cmd === 'set_exam_state') {
    examState.value = e.data;
    if (e.data === 3) {
      initProject();
    }
    if (e.data === 40) {
      cleanData();
    }
    if (e.data == 41) {

    }
    if (e.data == 43) {

    }
    if (e.data == 42) {

    }
  }
  //新建测试后返回信息，获取result_id
  if (e.cmd === 'open_one_test_ack') {
    resultId.value = e.data.result_id;
  }
  //人脸识别状态
  if (e.cmd === 'face_check_result') {
    let myData = e.data[0] || e.data;
    returnStudent(myData);
  }
  //测试结束结果
  if (e.cmd === 'oneresult') {
    if (e.data.length) {
      let data = e.data[0];
      getAchievement(data)
    }
  }
  //结果生成完成（视频图片）
  if (e.cmd === 'static_urls_finished') {
  }
  //选择学生或测试结束后返回的数据
  if (e.cmd === 'result_info') {
  }
};

/**
 * 开始项目和识别
*/
const getOpenOneTestAndStartFace = async () => {
  if (area == null || area == "") {
    return false;
  }
  console.log("examId", examId)
  if (examState.value > 3) {
    await props.parentTrainWsMethod.closeOneTest(examId);
  }
  await props.parentTrainWsMethod.openOneTest(examId);
  await props.parentTrainWsMethod.startFace(examId);
};

/**
 * 开始项目
*/
const getOpenOneTest = async () => {
  if (area == null || area == "") {
    return false;
  }
  console.log("examId", examId)
  if (examState.value > 3) {
    await props.parentTrainWsMethod.closeOneTest(examId);
  }
  await props.parentTrainWsMethod.openOneTest(examId);
};

/**
 * 开始识别
*/
const getStartFace = async () => {
  if (area == null || area == "") {
    return false;
  }
  await props.parentTrainWsMethod.startFace(examId);
};

/**
 * 停止人脸识别
*/
const getStopFace = async () => {
  if (area == null || area == "") {
    return false;
  }
  // 旧版识别成功直接43了这里先屏蔽
  // if (examState.value != 41) {
  //   return false;
  // }
  if (examState.value == 41) {
    await props.parentTrainWsMethod.stopFace(examId);
  }
  if (faceCheckStu.value.student_id) {
    getFaceConfirmOnly();
  }
};

/**
 * 确定人脸信息
*/
const getFaceConfirmOnly = (data?: any) => {
  if (data) {
    faceCheckStu.value = data;
  }
  props.parentTrainWsMethod.faceConfirmOnly({
    exam_id: examId,
    result_id: resultId.value,
    student_id: faceCheckStu.value.student_id,
    gender: faceCheckStu.value.gender
  }, () => {
  });
};

/**
 * 重新识别
*/
const getRetestFace = () => {
  if (props.examState == 42 || examState.value == 0) {
    return false;
  }
  proxy?.$modal.confirm("确定重新识别吗？").then(() => {
    cleanData();
    if (props.needStart == false) {
      //自动流程项目重新识别直接返回3
      props.parentTrainWsMethod.closeOneTest(examId);
    } else {
      //手动流程项目重新识别43返回41,42返回3
      if (examState.value == 43) {
        props.parentTrainWsMethod.startFace(examId);
      } else {
        props.parentTrainWsMethod.closeOneTest(examId);
      }
    }
  }).finally(() => {
  });
};

/**
 * 开始测试
*/
const getStartOneTest = () => {
  if (area == null || area == "") {
    return false;
  }
  if (examState.value != 43 || !faceCheckStu.value.student_id) {
    return false;
  }
  props.parentTrainWsMethod.startOneTest(examId, () => { })
};

/**
 * 再测一次
*/
const getAgain = async () => {
  if (area == null || area == "") {
    return false;
  }
  //预存测试人员
  let student = JSON.parse(JSON.stringify(faceCheckStu.value));
  //测试中
  if (examState.value == 42) {
    await props.parentTrainWsMethod.finishOneTest(examId);
  }
  //其他状态
  if (examState.value > 3) {
    await props.parentTrainWsMethod.closeOneTest(examId);
  }
  //重新走一次流程
  await props.parentTrainWsMethod.openOneTest(examId);
  await props.parentTrainWsMethod.startFace(examId);
  await props.parentTrainWsMethod.stopFace(examId);
  if (student.student_id) {
    getFaceConfirmOnly(student);
  }
};

/**
 * 重新识别
*/
const getAllRetestFace = async () => {
  if (area == null || area == "") {
    return false;
  }
  //测试中
  if (examState.value == 42) {
    await props.parentTrainWsMethod.finishOneTest(examId);
  }
  //其他状态
  if (examState.value > 3) {
    await props.parentTrainWsMethod.closeOneTest(examId);
  }
  //重新走一次流程
  await getOpenOneTestAndStartFace();
};

/**
 * 选择学生
*/
const getChooseStudent = () => {
  if (!area) {
    proxy?.$modal.msgWarning(`未启用`);
    return false;
  }
  console.log("examState.value", examState.value)
  if (examState.value == 0) {
    proxy?.$modal.msgWarning(`【${area}】当前状态：${examState.value}`);
    return false;
  }
  if (props.examState == 3 && (examState.value == 3 || examState.value == 40)) {
    if (props.needStart) {
      proxy?.$modal.msgWarning(`请点击右下角的【开始识别】，【${area}】当前状态：${examState.value}`);
    } else {
      proxy?.$modal.msgWarning(`【${area}】当前状态：${examState.value}`);
    }
    return false;
  }
  if (props.examState == 41 && (examState.value == 3 || examState.value == 40)) {
    proxy?.$modal.msgWarning(`【${area}】当前状态：${examState.value}`);
    return false;
  }
  if (examState.value == 41) {
    chooseStudent();
  }
  if (examState.value == 43) {
    getRetestFace();
  }
  if (props.examState == 42) {
    proxy?.$modal.msgWarning(`【${area}】正在测试请结束后再操作，当前状态：${examState.value}`);
    return false;
  }
};

/**
 * 选择学生
*/
const chooseStudent = () => {
  props.parentTrainWsMethod.stopFace(examId);
  emit('getChooseStudent', { area: area });
};

/**
 * 返回被选学生
*/
const returnStudent = (data: any) => {
  console.log("学生信息", data)
  faceCheckStu.value = data;
  getStopFace();
};

/**
 * 清除历史记录
*/
const cleanData = () => {
  faceCheckStu.value = {};
  currentResultObj.value = {};
  backReason.value = [];
};

/**
 * 自动初始化项目
*/
const initProject = () => {
  if (!area) {
    return false;
  }
  //自动项目定时进入下一步
  if (resultId.value) {
    if (props.needStart) {
      return false;
    }
    let time = 10000;
    setTimeout(() => {
      //再加一个判断以免和再测一次冲突
      if (examState.value == 3 || examState.value == 43) {
        console.log("执行了执行了执行了执行了执行了1")
        getOpenOneTestAndStartFace();
      }
    }, time)
  } else {
    if (props.needStart) {
      console.log("执行了执行了执行了执行了执行了2")
      getOpenOneTest();
    } else {
      console.log("执行了执行了执行了执行了执行了3")
      getOpenOneTestAndStartFace();
    }
  }
};

/**
 * 成绩
*/
const getAchievement = (data: any) => {
  //console.log("成绩", data);
  let dic: any = dataDictionary;
  let type = project;
  let count =
    data?.[dic.typeResultKey[type]]?.toFixed(0);
  if (["trijump", "solidball", "shotput", "longjump"].includes(type)) {
    count =
      data?.[dic.typeResultKey[type]]?.toFixed(2);
    count = Math.round(count) / 100;
  }
  data.count = count || "0";
  data.score = data.score || "0";
  currentResultObj.value = data;
  //成绩返回给列表
  emit('returnData', { count: data.count, area: area });
  //违规处理
  let arr = backReason.value;
  if (["situp", "pullup", "sidepullup", "jumprope", "jumpingjack", "highknees", "jump", "longjump", "verticaljump"]
    .indexOf(type) > -1) {
    if (["pullup", "situp", "jumprope", "jumpingjack", "highknees"].indexOf(type) > -1) {
      currentResultObj.value.back_num = data?.all_failed_num;
    }
    if (type === "sidepullup") {
      currentResultObj.value.back_num = data?.["0"]?.hip_failed_num;
    }
    if (['jump', 'longjump', 'verticaljump'].includes(type)) {
      if (data?.startline_check == 0) {
        let txt = "踩线违规";
        arr.push(txt)
      }
      if (data?.singleleg_jump_check == 0) {
        let txt = "单脚跳违规";
        arr.push(txt)
      }
      if (data?.outside_check == 0) {
        let txt = "跳出测试区违规";
        arr.push(txt)
      }
    }
    if (
      data?.elbow_check == false
    ) {
      let txt = "肘部违规";
      arr.push(txt);
    }
    if (
      ["situp", "pullup"].indexOf(type) > -1 &&
      data?.knee_check === false
    ) {
      let txt = "腿部违规";
      if (!arr.includes(txt)) {
        arr.push(txt);
      }
    }
    if (["situp"].indexOf(type) > -1 && data?.hand_check === false) {
      let txt = "手部违规";
      if (!arr.includes(txt)) {
        arr.push(txt);
      }
    }
    if (
      ["pullup"].indexOf(type) > -1 &&
      data?.["0"]?.elbow_check === false
    ) {
      let txt = "手部违规";
      if (!arr.includes(txt)) {
        arr.push(txt);
      }
    }
    if (["situp"].indexOf(type) > -1 && data?.["0"]?.back_check === false) {
      let txt = "背部违规";
      if (!arr.includes(txt)) {
        arr.push(txt);
      }
    }
    if (
      ["sidepullup", "situp"].indexOf(type) > -1 &&
      data?.["0"]?.hip_check === false
    ) {
      let txt = "臀部违规";
      if (!arr.includes(txt)) {
        arr.push(txt);
      }
    }
  }
  backReason.value = arr;
  if (data.isfinish) {
    // if (['jump'].includes(type) && backReason.value.length) {
    //   props.parentSpeechMethod.speckText("请重新测试");
    //   return false;
    // }
    // props.parentSpeechMethod.speckText(faceCheckStu?.value.name + "成绩为" + (chineseNumber(count) || 0) + unit.value + "，请下一位准备！" || "");
  }
};

/**
 * 状态抛给父组件
*/
watch(() => examState.value, (newVal, oldVal) => {
  console.log(area, examState.value)
  emit('returnData', { examState: examState.value, area: area });
}, { deep: true });

/**
 * 人脸信息抛给父组件
*/
watch(() => faceCheckStu.value, (newVal, oldVal) => {
  emit('returnData', { faceCheckStu: faceCheckStu.value, area: area });
}, { deep: true });

/**
 * 测试ID抛给父组件
*/
watch(() => resultId.value, (newVal, oldVal) => {
  emit('returnData', { resultId: resultId.value, area: area, count: 0 });
}, { deep: true });

/**
 * 如果总流程结束了个别区仍然在43就重新执行一次，用于没有开的区自动复位
*/
watch(() => props.examState, (newVal, oldVal) => {
  if (newVal == 3 && examState.value == 43) {
    setTimeout(() => {
      initProject();
    }, 10000)
  }
  //父状态已经进入41了就不要等子组件40清空数据了
  if (newVal == 41) {
    cleanData();
  }
}, { deep: true });

onMounted(() => {
  let dic: any = dataDictionary;
  unit.value = dic.unit[project];
  ctrl.value = route.query.ctrl;
  handcontroller.value = route.query.handcontroller;
})

//暴露给父组件用
defineExpose({
  getMessage,
  getOpenOneTestAndStartFace,
  getOpenOneTest,
  getStartFace,
  getStopFace,
  getStartOneTest,
  getAgain,
  getAllRetestFace,
  returnStudent
})
</script>

<style scoped lang="scss"></style>
