<template>
  <div class="v-component wx-login-ewm">
    <Spin size="large" fix class="loading" v-if="loading"></Spin>
    <wx-ewm :appid="appid" :redirect-uri="loginUrl" :href="href" v-else></wx-ewm>
  </div>
</template>

<script>
import wxEwm from './wx-ewm'
import { getPageQueryObject } from '../../utils/assist'
import login from '../../apis/login'
import storage from '../../utils/storage'
import helper from '../../utils/helper'
export default {
  name: 'WxLoginEwm',
  props: {
    appid: { // appid
      type: String,
      required: true
    },
    href: String // 二维码样式css地址
  },
  data () {
    return {
      loginUrl: window.$CONFIG.loginUrl,
      query: {},
      loading: true
    }
  },
  computed: {
    routeQuery () {
      return this.$route.query
    }
  },
  watch: {
    routeQuery () {
      this.checkIsLogin()
    }
  },
  created () {
    this.checkIsLogin()
  },
  methods: {
    checkIsLogin () {
      this.query = getPageQueryObject()
      let state = storage.getSession('state')
      if (this.query.code && this.query.state === state) {
        this.login()
      } else {
        this.loading = false
      }
    },
    async login () {
      try {
        this.loading = true
        let res = await login.login(this.query.code, this.appid)
        this.loading = false
        let { registerId, accessCode } = res.data
        if (registerId) {
          this.$emit('register', registerId)
        }
        if (accessCode) {
          this.$emit('access', accessCode)
        }
      } catch (e) {
        let res = e.response
        if (res && res.status === 403) {
          setTimeout(() => {
            this.loginError()
          }, 2000)
        } else {
          this.loginError()
        }
      }
    },
    loginError () {
      this.loading = false
      document.location.replace(`${this.loginUrl}`)
    }
  },
  components: {
    wxEwm
  }
}
</script>
