<script setup lang="ts">
import { httpApp } from "@/plugins/axiosApp";
import { watch } from "vue";

const props = defineProps<{ reset: number }>();

const emit = defineEmits<{ (e: "onLoad", value: Captcha): void }>();

watch(
  () => [props.reset],
  () => resetGee(),
  { immediate: true }
);

let loading = $ref(true);

type Captcha = {
  appendTo(sel: string): void;
  onReady(cb: () => void): void;
  onError(cb: (error: any) => void): void;
  destroy(): void;
  getValidate(): any;
};
async function resetGee() {
  function handler(captchaObj: Captcha) {
    emit("onLoad", captchaObj);
    // console.log("emited", captchaObj);
    // 将验证码加到id为captcha的元素里，同时会有三个input的值用于表单提交
    captchaObj.appendTo("#captcha");
    captchaObj.onReady(() => (loading = false));
    captchaObj.onError((error: any) => {
      // 出错啦，可以提醒用户稍后进行重试
      // error 包含error_code、msg
      logger({
        key: "极验",
        cnl: ["local", "server"],
        pgu: "AUTO",
        ext: {
          errorCode: error.error_code,
          msg: error.msg,
        },
      });
      $message.error("资源加载失败，请关闭程序，检查网络状况后重试。", {
        duration: 24 * 60 * 60 * 1000,
      });
    });
  }

  let res = null;
  try {
    res = await httpApp.post("/api/ecs_core/verifyCode/register", {
      user_id: localStorage.getItem("uuidForEcs"),
      client_type: "Web",
    });
  } catch (error: any) {
    logger({
      key: "极验",
      cnl: ["local", "server"],
      act: "register接口调用失败",
      stk: error.stack,
      dtl: error.message,
      ext: { errorName: error.name },
    });
    $message.error("资源注册失败，请关闭程序，检查网络状况后重试。", {
      duration: 24 * 60 * 60 * 1000,
    });
    return;
  }
  // console.log(res);
  const data = res.data;
  if (!data.success) {
    logger({
      key: "极验",
      cnl: ["local", "server"],
      dtl: "极验API宕机",
    });
  }
  // @ts-ignore
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call
  window.initGeetest(
    {
      gt: data.gt,
      challenge: data.challenge,
      new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
      offline: !data.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
      product: "float", // 产品形式，包括：float，popup
      width: "100%",
    },
    handler
  );
}
</script>

<template>
  <div>
    <!-- <label>完成验证：</label> -->
    <div id="captcha">
      <p v-if="loading" class="show">正在加载验证码......</p>
      <!-- 重新获取验证码 -->
    </div>
  </div>
</template>
