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

<script>
import { createLog } from "@/utils/logger";
export default {
  name: "GeeTest",
  props: {
    reset: { type: Number, default: 0 },
  },
  data() {
    return { loading: true };
  },
  watch: {
    reset: {
      immediate: true,
      handler() {
        this.resetGee();
      },
    },
  },
  methods: {
    async resetGee() {
      const that = this;
      function handler(captchaObj) {
        that.$emit("on-load", captchaObj);
        // 将验证码加到id为captcha的元素里，同时会有三个input的值用于表单提交
        captchaObj.appendTo("#captcha");
        captchaObj.onReady(function () {
          that.loading = false;
        });
        captchaObj.onError((error) => {
          // 出错啦，可以提醒用户稍后进行重试
          // error 包含error_code、msg
          createLog({
            currentPage: "极验",
            errorCode: error.error_code,
            msg: error.msg,
          });
          that.$Message.error({
            content: "资源加载失败，请关闭程序，检查网络状况后重试。",
            duration: 1 * 60,
            closable: true,
          });
        });
      }

      let res = null;
      try {
        res = await this.$http.post("/api/ecs_core/verifyCode/register", {
          user_id: localStorage.getItem("uuidForEcs"),
          client_type: "Web",
        });
      } catch (error) {
        createLog({
          currentPage: "极验",
          action: "register接口调用失败",
          errorJSON: JSON.stringify(error, (key, value) =>
            key === "token" ? "" : value
          ),
          errorName: error.name,
          errorMessage: error.message,
          errorStack: error.stack,
        });
        this.$Message.error({
          content: "资源注册失败，请关闭程序，检查网络状况后重试。",
          duration: 5 * 60,
          closable: true,
        });
        return;
      }
      // console.log(res);
      const data = res.data;
      if (!data.success) {
        createLog({
          currentPage: "极验",
          error: "极验API宕机",
        });
      }
      window.initGeetest(
        {
          gt: data.gt,
          challenge: data.challenge,
          new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
          offline: !data.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
          product: "float", // 产品形式，包括：float，popup
          width: "100%",
        },
        handler
      );
    },
  },
};
</script>

<style>
/* .geetest_holder.geetest_wind {
  min-width: 220px !important;
} */
</style>
