import { getUserInfo } from '@/service/userInfo.service';
import { smTrackEvent } from '@/service/shumei.service';
import localStorage from '@/service/localStorage.service';
import {
  jverificationInit,
  isJverificationInitSuccess,
  getJverificationToken,
  jverificationLogin
} from '@/service/Jverify.service';
import { oneKeyLogin } from '@/api/user.api';
export default {
  data() {
    return {
      operater: '', // 运营商标识，CM 代表中国移动，CU 代表中国联通，CT 代表中国电信
      DOMObserver: null, // 用于监听运营商一键登录弹窗
      jverificationLoopMaxTime: 10000, // 最大允许极光轮询时间，当累计轮询时间达到最大允许极光轮询时间，终止轮询，避免过度消耗手机内存
      jverificationLoopSingelTime: 200, // 单次轮询时间
      jverificationLoopCurrentTime: 0, // 累计轮询时间
      jverificationLoopTimer: null // 存储极光sdk初始化windows.JVerificationInterface的轮询计时器
    };
  },
  destroyed() {
    this.DOMObserver = null;
  },
  methods: {
    saUploadOneKeyLoginEvent(loginSuccess, failCode, failMessage) {
      this.$track.registeredEvents('H5_LoginEvent', {
        le_is_login_success: loginSuccess,
        le_channel_code: localStorage.get('vccChannel') || '',
        le_login_type: '一键登录',
        le_failure_code: failCode || '',
        le_failure_message: failMessage || ''
      });
    },
    createObserver() {
      // 开始监听运营商一键登录弹窗展示情况
      this.DOMObserver = null;
      const _that = this;
      this.DOMObserver = new MutationObserver(function(mutations) {
        // 用户注册协议和隐私协议
        const fillHtmlContent = `<span>、</span><a id="agreement-1" href="${_that.$config.privacyRreaty.url}" class="link">《${_that.$config.privacyRreaty.label}》</a><span>和</span><a href="${_that.$config.registerRreaty.url}" class="link">《${_that.$config.registerRreaty.label}》</a>`;
        mutations.forEach(function(mutation) {
          if (mutation.addedNodes && mutation.addedNodes[0] && mutation.addedNodes[0].id) {
            const id = mutation.addedNodes[0].id;
            if (id == 'YDRZLayer') {
              // 中国移动弹窗, 增加注册、登录协议
              // eslint-disable-next-line no-undef
              const originAgreement = $('#YDRZ_Agreement')
                .find('p')
                .find('a');
              if (
                // eslint-disable-next-line no-undef
                $('#YDRZ_Agreement')
                  .html()
                  .indexOf('agreement-1') == -1
              ) {
                originAgreement.after(fillHtmlContent);
              }
            }
            if (id == 'authxwLoginBox') {
              // 中国移动弹窗, 增加注册、登录协议
              if (
                // eslint-disable-next-line no-undef
                $('.xw-agreeement-txt')
                  .html()
                  .indexOf('agreement-1') == -1
              ) {
                // eslint-disable-next-line no-undef
                $('.xw-agreeement-txt').append(fillHtmlContent);
              }
            }
          }
        });
      });
      this.DOMObserver.observe(document.body, { childList: true });
    },
    async jVerify(manual) {
      if (manual) {
        this.$store.dispatch('change_loading', true);
      }
      this.createObserver();
      // 极光认证开始
      this.jverificationLoopTimer = null;
      clearInterval(this.jverificationLoopTimer);
      try {
        this.jverificationLoopTimer = setInterval(async () => {
          if (window.JVerificationInterface) {
            clearInterval(this.jverificationLoopTimer);
            this.jverificationLoopTimer = null;
            await jverificationInit();
            // 判断极光sdk是否初始化成功，如初始化成功，则不进行后续操作
            const JverificationInitSuccess = isJverificationInitSuccess();
            if (!JverificationInitSuccess) {
              this.$store.dispatch('change_loading', false);
              return console.log('极光sdk初始化失败');
            }
            // 判断当前网络环境是否可用，如不可用，不进行后续操作
            const verifyEnable = window.JVerificationInterface.checkVerifyEnable();
            if (!verifyEnable) {
              this.$store.dispatch('change_loading', false);
              return console.log('当前网络环境不支持认证');
            }
            // 获取网络通信商token
            const tokenResult = await getJverificationToken();
            if (tokenResult.code !== 0 && tokenResult.operater != 'CT') {
              console.log(tokenResult.message || '获取运营商token失败');
              this.$store.dispatch('change_loading', false);
              return;
            }
            if (tokenResult.operater) {
              this.operater = tokenResult.operater;
            }
            // 当运营商为中国联通时，设置logo及应用名
            if (tokenResult?.operater === 'CU') {
              window.JVerificationInterface.setCustomUIWithConfig({
                logo: 'https://img.lkbang.net/auth-logo.1c5fddec.png',
                appName: '羊小咩商城'
              });
            }
            // 中国电信因隐私协议无法修改的问题，禁止调起一键登录
            if (tokenResult?.operater === 'CT') {
              this.$store.dispatch('change_loading', false);
              return;
            }
            // 调起认证登录弹窗
            this.$store.dispatch('change_loading', false);
            const { operater, content, message, code } = await jverificationLogin();
            if (content && content[this.operater] && code !== 0 && manual) {
              if (content[this.operater].indexOf('105025') > -1) {
                // 中国移动输入超过3次错误中间四位，进行24小时封禁
                this.$toast('输入错误次数过多，请24小时后再操作');
              } else {
                this.$toast('请稍后重试');
              }
              return this.$store.dispatch('change_loading', false);
            }
            if (operater && content && message === 'success') {
              // 认证成功，调kdsp接口进行登录
              const [res, err] = await oneKeyLogin({
                operator: 'operatorWeb', // 用于区分H5终端类型
                verifyToken: content
              });
              if (err) return;
              // 上报数美风控
              const phoneNo = res.phoneNo || '';
              if (phoneNo) {
                smTrackEvent({
                  eventId: 'login',
                  phone: phoneNo,
                  type: 'phoneOneLogin'
                });
              }
              this.$toast.success('登录成功');
              this.CHANGE_TOKEN(res.token);
              this.$track.run('loginSa', res.uuid);
              // 上报神策登录事件
              // this.saUploadLoginEvent(true, '一键登录');
              this.saUploadOneKeyLoginEvent(true);
              await getUserInfo();
              setTimeout(() => {
                if (this.backUrl) {
                  location.replace(this.backUrl);
                  return;
                }
                this.$router.go(-1);
              }, 1000);
              return;
            }
            this.saUploadOneKeyLoginEvent(false);
          } else {
            // 当轮询时间达到上限的时候，不再轮询，终止调起一键登录(短时间且多次轮询会严重导致低端机型内存消耗)
            this.jverificationLoopCurrentTime += this.jverificationLoopSingelTime;
            if (this.jverificationLoopCurrentTime >= this.jverificationLoopMaxTime) {
              clearInterval(this.jverificationLoopTimer);
            }
          }
        }, this.jverificationLoopSingelTime);
      } catch (err) {
        this.$store.dispatch('change_loading', false);
      }
      // 极光认证结束
    }
  }
};
