import { httpApp } from "@/plugins/axiosApp";
import { useTimers } from "@/setups/useTimers";
import { store } from "@/store/store";
import { watch } from "vue";

export function useFaceLive(doSnap: () => void) {
  const { addTimeout } = useTimers();

  let showFaceId = $ref(false);

  watch(() => store.exam.faceLivenessEnabled, initData, { immediate: true });

  async function initData() {
    if (!store.exam.faceLivenessEnabled) {
      return;
    }

    const faceBiopsyBaseInfoData = await httpApp.get<{
      faceVerifyMinute: number;
      identificationOfLivingBodyScheme: "S1" | "S2";
    }>(
      "/api/ecs_oe_student/faceBiopsy/getFaceBiopsyBaseInfo?examRecordDataId=" +
        store.exam.examRecordDataId,
      { "axios-retry": { retries: 4 }, noErrorMessage: true }
    );

    const faceVerifyMinute = faceBiopsyBaseInfoData.data.faceVerifyMinute;
    const identificationOfLivingBodyScheme =
      faceBiopsyBaseInfoData.data.identificationOfLivingBodyScheme;

    // 仅在线上使用活体检测
    // if (process.env.NODE_ENV === "production" && faceVerifyMinute) {
    if (faceVerifyMinute) {
      // 活检定时，通过watch remain 来确定是否可行
      logger({
        cnl: ["server"],
        act: "活检定时",
        dtl:
          faceVerifyMinute * 60 * 1000 - store.exam.remainTime > 60 * 1000
            ? "活检时间可行"
            : "活检时间不可行",
        ext: { faceVerifyMinute, remainTime: store.exam.remainTime },
      });

      addTimeout(() => {
        logger({ cnl: ["server"], act: "活体检测前抓拍" });
        doSnap();
        // this.toggleSnapNow();
        $message.info("30秒后开始指定动作检测");
      }, faceVerifyMinute * 60 * 1000 - 30 * 1000 + 5 * 1000); // 活体检测提醒。加5秒，和整分抓拍错开。

      addTimeout(() => {
        if (identificationOfLivingBodyScheme === "S1") {
          showFaceId = true;
        }
      }, faceVerifyMinute * 60 * 1000 + 5 * 1000); // 定时做活体检测。加5秒，和整分抓拍错开。
      // }, 1 * 1000); // 定时做活体检测
    }

    // for test
    // setTimeout(() => {
    //   this.showFaceId = true;
    //   // this.$Modal.remove();
    //   // }, this.$route.query.faceVerifyMinute * 60 * 1000); // 定时做活体检测
    // }, 5 * 1000); // 定时做活体检测
  }

  return { showFaceId: $$(showFaceId) };
}
