<template>
  <div class="container">
    <ConfigPopup v-model="isShowConfig"></ConfigPopup>
    <ForcePopup v-model="isShowForce"></ForcePopup>
    <PreconditionPopup v-model="isShowPrecondition"></PreconditionPopup>
    <slot>
      <router-view></router-view>
    </slot>
  </div>
</template>
<script>
import Bus from '@/utils/Bus'
import { mapActions } from 'vuex'
import loginAction from '@/plugins/UserAction/login'
import { ENV_CONFIG } from "@/config";
import UserAgents from '@/utils/UserAgents'
import ConfigPopup from '../components/Common/ConfigPopup'
import ForcePopup from '../components/Common/ForcePopup'
import action from '@/plugins/pvStatisticalService'
import dmsService from '@/plugins/dmsService'
import PreconditionPopup from '../components/Common/PreconditionPopup'
export default {
  components: {
    ConfigPopup,
    ForcePopup,
    PreconditionPopup
  },
  data() {
    return {
      loginInstance: null,
      isShowConfig: false,
      isShowForce: false,
      isShowPrecondition: false
    }
  },
  mounted() {
    document.addEventListener('visibilitychange', this.handleVisibilityChange, false)
    this.initLoginCenter()
    Bus.$on('showLogin', this.toggleLogin)
    Bus.$on('showConfig', () => {
      this.isShowConfig = true
    })
    Bus.$on('showForce', () => {
      this.isShowForce = true
    })
    Bus.$on('showPrecondition', () => {
      this.isShowPrecondition = true
    })
    const route = this.$route
    const store = this.$store
    action({ route, store })
    dmsService({ route })
    const { id, uin } = this.$route.query
    // 抽奖前置条件
    if (id && uin) {
      this.checkPremise({ id, uin })
    }
  },
  destroyed() {
    Bus.$off('showLogin')
  },
  methods: {
    ...mapActions({
      jumpToLogin: 'users/jumpToLogin',
      checkPremise: 'lottery/check_premise',
    }),
    handleVisibilityChange() {
      const { uin = 0 } = this.$route.query
      if (document.hidden) {
        return 0
      } else {
        // page has focus, begin running task
        this.$store.dispatch('users/getUerInfo', { uin })
      }
    },
    // 云平台登录模块初始化
    initLoginCenter() {
      if (!window.LoginCenter) return
      const isCname = !window.location.href.includes(
        `//${ENV_CONFIG.CUSTOMER_DOMAIN}`
      )
      const state = isCname ? document.domain : ''
      const wxPcRedirect = isCname
        ? window.location.href.replace(
          /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}|(:[0-9]{1,4}))+\.?/,
          `${ENV_CONFIG.CUSTOMER_DOMAIN}`
        )
        : window.location.href
      const that = this
      // eslint-disable-next-line no-undef
      this.loginInstance = LoginCenter({
        target: document.body,
        props: {
          uin: this.$route.query.uin,
          zIndex: 100000,
          backUrl: encodeURIComponent(window.location.href),
          wxPcRedirect,
          state,
          serviceAgreement: `//${ENV_CONFIG.OSS_DOMAIN}/staticPages/agreement_user.html`,
          privacyAgreement: `//${ENV_CONFIG.OSS_DOMAIN}/staticPages/agreement_privacy.html`,
          successCallback: ({ type, response }) => {
            if (type === 'recover'){
              this.$toast("密码修改成功!");
              setTimeout(() => {
                this.loginInstance.hide()
              }, 500);
              return
            }
            this.$toast("登录成功!");
            if (type === 'phone'){
              this.loginInstance.hide()
            }
            if (type === 'password'){
              this.loginInstance.hide()
            }
            const query = this.$route.query
            const onFinished = () => {
              delete query.token
              if (type === 'weixinPc' && 'code' in query){
                delete query.code
                this.$router.replace({
                  path: this.$route.path,
                  query
                })
              }
              if (type === 'alipay' && 'auth_code' in query){
                delete query.auth_code
                this.$router.replace({
                  path: this.$route.path,
                  query
                })
              }
            }
            // const loginAction = require("@/plugins/UserAction/login").default;
            loginAction.call(that, { token: response.data, onFinished })
          },
          failCallback: ({ response }) => {
            this.$toast(response.errorMessage)
          },
        },
        onMount: () => {
          console.log('已挂载')
        },
      })
    },
    // 登录判断
    toggleLogin() {
      if (!this.loginInstance) {
        this.$toast('登录模块加载失败，3秒后为您跳转到登录页')
        setTimeout(() => {
          this.jumpToLogin()
        }, 3000)
        return
      }
      if (UserAgents.isMobile) {
        this.loginInstance.show('entry')
      } else {
        this.loginInstance.show('pc-entry')
      }
    }
  },
}
</script>
<style lang="less" scoped>
.container {
  margin: 0 auto;
  width: 100%;
  height: 100vh;
}
</style>
