window.g_domainSafeVaild = function () {
  var isNeedVaild = $("#isBehaviorWayDomain").val() == 0
  var isZK = $("#captchaMode").val() == 'zkeys'
  var isJY = $("#captchaMode").val() == 'geetest'
  var $captchaDomainpPopup = $("#captchaDomainpPopup")
  return {
    isZK: isZK,
    isJY: isJY,
    isNeedVaild: isNeedVaild,
    isNeedZK: isNeedVaild && isZK,
    isNeedJY: isNeedVaild && isJY,
    queryParams: '', //返回参数
    queryMethod: '',

    triggerZkVaild: function (options) { //触发验证
      this.setSubmitParams(options)
      if (this.isPending && this.isJY) {
        return
      }
      if (this.isNeedZK) {
        !$(".z-verify-container").length && $('#zkeysDomainSendCode').trigger('click')
      } else if (this.isNeedJY) {
        this.openJyCaptcha()
      }
    },
    setSubmitParams: function (options) {
      options = options || {}
      if (options.getParams) {
        this.queryParams = options.getParams()
      } else if (options.getMethod) {
        this.queryMethod = options.getMethod
      }
    },
    setNeedVaild: function (status) { //设置验证
      if (isZK) {
        this.isNeedZK = Boolean(status)
        return
      }
      if (isJY) {
        this.isNeedJY = Boolean(status)
      }
    },
    getIsNeedVaild: function () {
      if (isZK) {
        return this.isNeedZK
      }
      if (isJY) {
        return this.isNeedJY
      }
    },
    inferNeedVaild: function (status) {
      if (isZK) {
        this.isNeedZK = status == 0
        return this.isNeedZK
      }
      if (isJY) {
        this.isNeedJY = status == 0
        return this.isNeedJY
      }
    },
    jyDialog: null,
    openJyCaptcha: function () {
      if (!$.dialog) { //手机端
        $captchaDomainpPopup.show()
        $("#captchaDomainCancel").off('click').on('click', function () {
          $captchaDomainpPopup.hide()
        })
        return
      }
      this.jyDialog = $.dialog({
        title: '\u00A0',
        content: $('#jyDomainCaptcha')[0],
        width: 340,
        height: 100,
        padding: 0,
        init: function () {
          var that = $(this)
          $("#captchaDomainCancel").off('click').on('click', function () {
            that[0].close()
          })
        },
        skin: 'captcha-dialog',
      });
    },
    bindZKVaild: function (option) {
      option = option || {}
      var bindId = option.bindId //触发zkeys验证id
      var response = option.response //zkeys验证token、csrf
      var onSuccess = option.onSuccess
      var onVaildSuccess = option.onVaildSuccess
      if (!bindId) {
        return console.warn('id不为空')
      }
      var name = $("#g_zkVaildTitle").val() || '云引擎验证';
      var container = document.getElementById(bindId)
      if (typeof ZkeysVerify == 'undefined') return
      var mydialog = new ZkeysVerify({
        tmpId: container,
        hasOwnNodes: true,
        host: response.data.host,
        token: response.data.token,
        verifyName: name,
      });

      mydialog.on('cancel', function (e) {
        // console.log(e,"test event")
      })

      mydialog.on('success', function (e) {
        if (onVaildSuccess) {
          return onVaildSuccess(e.data)
        }
        var data = e.data;
        var params = option.getParams ? option.getParams() : '' //查询参数
        onSuccess && onSuccess()
      })
    },
    isPending: false,
    getVaildToken: function (options) {
      options = options || {}
      var isTrigger = options.isTrigger
      var that = this
      if (this.isNeedZK) {
        $.ajax({
          url: '/slideGetToken',
          dataType: 'json',
          data: {
            t: +new Date()
          },
          async: false,
          success: function (responseData) {
            if (responseData.result) {
              that.bindZKVaild(Object.assign({}, {
                bindId: "zkeysDomainSendCode",
                onVaildSuccess: function (data) {
                  that.setNeedVaild()
                  if (that.queryMethod) {
                    that.queryMethod(data)
                    that.queryMethod = ''
                    return
                  }
                  window.location.href = '/domain/search?' + that.queryParams + "&csrf_id=" + data.csrf_id + "&v_token=" + data.v_token;
                }
              }, {
                response: responseData
              }))
              isTrigger && that.triggerZkVaild(options)
            }
          }
        })

      }
      if (this.isNeedJY) {
        this.isPending = true
        $.ajax({
          url: '/crossVerify?t=' + new Date().getTime(), // 加随机数防止缓存
          type: 'get',
          dataType: 'json',
          async: false,
          success: function (data) {
            // $('#text').hide();
            // $('#wait').show();
            // 调用 initGeetest 进行初始化
            // 参数1：配置参数
            // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它调用相应的接口
            setTimeout(function () {
              initGeetest(
                {
                  // 以下 4 个配置参数为必须，不能缺少
                  gt: data.gt,
                  challenge: data.challenge,
                  offline: !data.success, // 表示用户后台检测极验服务器是否宕机
                  new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
                  product: 'popup', // 产品形式，包括：float，popup
                  width: '300px',
                  https: true,
                  // 更多配置参数说明请参见：/install/client/web-front/
                },
                handler
              );
              isTrigger && that.triggerZkVaild(options)
            })
          },
          complete: function () {
            that.isPending = false
          }
        });
        // 极验验证
        var handler = function (captchaObj) {
          $("#captchaDomainTwo").html('')
          captchaObj.appendTo('#captchaDomainTwo');
          captchaObj.onReady(function () {
            // $('#wait').hide();
          });

          captchaObj.onSuccess(function () {
            var result = captchaObj.getValidate();
            if (!result) {
              return NY.warn('请完成验证', 1.5);
            }
            that.setNeedVaild()
            if (that.queryMethod) {
              that.jyDialog && that.jyDialog.close()
              captchaObj.destroy()
              if (!$.dialog) { //手机端
                $captchaDomainpPopup.hide()
              }
              that.queryMethod(result)
              that.queryMethod = ''
              return
            }
            window.location.href = '/domain/search?' + that.queryParams + "&geetest_challenge=" + result.geetest_challenge + "&geetest_validate=" + result.geetest_validate + "&geetest_seccode=" + result.geetest_seccode;

          });

          captchaObj.onError(function () {
            // 出错啦，可以提醒用户稍后进行重试
            NY.warn('验证失败请重试', 1.5);
          });
        };
      }
    }
  }
}();
$(function () {
  g_domainSafeVaild.getVaildToken()
})
