<template>
  <div>
    <Transition :enter-active-class="proxy?.animate.mask.enter">
      <div class="mask" v-if="faceState"></div>
    </Transition>
    <Transition :enter-active-class="proxy?.animate.rankingWindow.enter"
      :leave-active-class="proxy?.animate.rankingWindow.leave">
      <div class="confirmDiaBg" v-if="faceState">
        <div class="confirmDiaWindow">
          <div class="confirmDiaWindow-con">
            <div class="name">
              请举右手看摄像头进行人脸识别
            </div>
            <div class="pic">
              <img src="@/assets/images/common/onlineFace.png" />
            </div>
          </div>
        </div>
        <div @click="getCloseFace" class="close"></div>
      </div>
    </Transition>
  </div>

</template>
<script setup lang="ts">
import { initSpeech, speckText, playMusic, controlMusic, speckCancel, chineseNumber } from '@/utils/speech';
import { useWebSocket } from '@/utils/faceWs';
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const { faceWs, startDevice, checkFace, openFace, terminateFace, suspendFace, resumeFace, getFaceState } = useWebSocket();

const data = reactive<any>({
  faceCheckStu: {},//人脸信息
  faceState: false,//人脸识别窗口状态
  direction: "",//动画方向
  parameter: {},//参数
  deviceInfo: {},//设备信息
  againNum: 0,//再次启动次数
  againTimer: null,//定时状态
  wsState: false,//WS状态
});

const { faceCheckStu, faceState, direction, parameter, deviceInfo, againNum, againTimer, wsState } = toRefs(data);

onBeforeMount(() => {
})

onMounted(() => {
})

/**
 * 初始化
 */
const getInit = async () => {
  console.log("触发人脸识别")
  let deviceid = localStorage.getItem('deviceid') || '';
  if (!deviceid) {
    proxy?.$modal.msgError(`请重新登录绑定设备号后使用`);
    return false;
  }
  faceState.value = true;
  if (wsState.value) {
    proxy?.$modal.msgWarning(`操作过快，请稍后重试`);
    setTimeout(() => {
      faceState.value = false;
    }, 1000)
    return false;
  }
  speckText("请举右手看摄像头进行人脸识别");
  faceWs((e: any) => {
    console.log("faceWS", e)
    if (e?.wksid) {
      wsState.value = true;
      //获取设备信息
      startDevice({ deviceid: deviceid });
      console.log("获取设备信息")
    }
    if (e?.type == 'fe_device_init_result') {
      //接收设备信息并发送请求
      if (e?.device_info) {
        deviceInfo.value = e.device_info;
        getCheckFace();
        console.log("返回设备信息，检查是否支持人脸识别")
      } else {
        proxy?.$modal.msgError(`设备信息缺失，请重新登录绑定设备号后使用`);
      }
    }
    if (e?.cmd == 'check_facecontroller_available') {
      let handcontroller_id = deviceInfo.value.handcontroller_id;
      if (e?.code == 0) {
        //查看人脸识别状态，如果不处于关闭就先关闭再重新启动（可能会APP退出然后工作站还在运行的可能性）
        getFaceState(handcontroller_id);
        againNum.value = 0;
        againTimer.value = null;
        clearTimeout(againTimer.value);
        console.log("查看人脸识别状态")
      } else {
        //尝试多次查询人脸识别状态
        if (againNum.value <= 10) {
          againTimer.value = setTimeout(() => {
            getCheckFace();
          }, 100)
          againNum.value++;
        } else {
          let msg = "";
          if (e.code == 102402) {
            msg = `多次连接失败请重试，人脸识别模块被占用`;
          } else {
            msg = `多次连接失败请重试，人脸识别模块不可用，code：${e.code}`;
          }
          proxy?.$modal.msgWarning(msg);
          againNum.value = 0;
          againTimer.value = null;
          clearTimeout(againTimer.value);
          getCloseFace();//直接关闭 
        }

      }
    }
    if (e?.cmd == 'get_facecontroller_state') {
      let handcontroller_id = deviceInfo.value.handcontroller_id;
      //state说明: 0：关闭，3：空闲，36：工作中
      if ([3, 36].includes(e.state)) {
        getCloseFace();
        proxy?.$modal.msgWarning(`请重新人脸识别`);
      } else {
        openFace(handcontroller_id);
      }
    }
    if (e?.type == 'facecontroller_result') {
      if (e?.data?.student_id) {
        //返回人脸信息然后跳转
        let id = e.data.student_id;
        let name = e.data.student_name;
        let pic = e.data.student_icon;
        let obj = { id, name, pic }
        faceCheckStu.value = obj;
        getCloseFace();
        router.push({ path: '/score', query: obj });
      }
    }
    if (e?.cmd == 'terminate_facecontroller') {
      if (e?.code == 0) {
        faceState.value = false;
      }
    }
    if (e?.type == 'disconnect') {
      wsState.value = false;
    }
  });
};


/**
 * 查询人脸识别状态
*/
const getCheckFace = () => {
  let handcontroller_id = deviceInfo.value.handcontroller_id;
  //检查是否支持人脸识别
  checkFace(handcontroller_id);
};

/**
 * 关闭人脸识别
*/
const getCloseFace = () => {
  let handcontroller_id = deviceInfo.value.handcontroller_id;
  terminateFace(handcontroller_id);
  faceState.value = false;
  speckCancel(); //停止播报
};

//暴露给父组件用
defineExpose({
  getInit
})
</script>
<style lang="scss" scoped>
.mask {
  position: fixed;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 998;
}

.confirmDiaBg {
  width: 70rem;
  position: fixed;
  left: 50%;
  top: 50%;
  margin-left: calc(70rem / -2);
  margin-top: calc(((70rem / 2) + 3.2rem) / -2);
  display: flex;
  flex-direction: column;
  z-index: 999;

  .confirmDiaWindow {
    border-radius: 1.6rem;
    opacity: 1;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    background: linear-gradient(62deg, #092941 -85%, #2A484B 96%);

    .confirmDiaWindow-con {
      padding: 25px;

      .pic {

        width: 100%;

        img {
          width: 100%;
        }
      }

      .name {
        width: 100%;
        color: #ffffff;
        font-size: 2.8vh;
        margin-bottom: 30px;
      }
    }
  }

  .close {
    margin: 0 auto;
  }
}
</style>
