<template>
  <div class="v-component wx-login">
    <wx-login-ewm v-if="!step || step === '1'" :appid="appid" :href="href" @register="toRegister" @access="getUserInfo"></wx-login-ewm>
    <wx-login-bind v-if="step === '2'" :register-id="registerId" @send-code="setRegisterId" @register-success="getUserInfo"></wx-login-bind>
    <wx-login-setpwd v-if="step === '3'" @set-pwd-success="complete"></wx-login-setpwd>
    <Spin size="large" fix class="loading" v-if="loading"></Spin>
  </div>
</template>

<script>
import storage from '../../utils/storage'
import helper from '../../utils/helper'
import login from '../../apis/login'
import { getPageQueryObject } from '../../utils/assist'
export default {
  props: {
    appid: { // appid
      type: String,
      required: true
    },
    href: String, // 二维码样式css地址
    successUrl: { // 扫码已注册用户跳转地址url
      type: String,
      required: true
    }
  },
  data () {
    return {
      loginUrl: window.$CONFIG.loginUrl,
      step: '1',
      registerId: storage.getSession('registerId', ''),
      loading: false
    }
  },
  created () {
    this.checkStep()
  },
  methods: {
    checkStep () {
      let query = getPageQueryObject()
      this.step = query.step || '1'
      if (this.step === '1') {
        helper.clearUserInfo()
        return
      }
      if (this.step === '2' && !this.registerId) {
        this.changeStep('1')
        return
      }
    },
    toRegister (registerId) {
      this.setRegisterId(registerId)
      this.changeStep('2')
    },
    async getUserInfo (accessCode) {
      try {
        this.loading = true
        let res = await login.getUserInfo(accessCode)
        helper.saveUserInfo(res.data)
        if (res.data.pwdSet) { // 需要设置密码
          this.changeStep('3')
          this.loading = false
        } else {
          this.complete()
        }
      } catch (e) {
        this.changeStep(1)
      }
    },
    setRegisterId (registerId = '') {
      this.registerId = registerId
      storage.setSession('registerId', registerId)
    },
    changeStep (step) {
      this.step = step
      if (step === '1') {
        document.location.replace(`${this.loginUrl}`)
      } else {
        document.location.replace(`${this.loginUrl}?step=${step}`)
      }
    },
    complete () {
      this.loading = true
      document.location.replace(`${this.successUrl}`)
    }
  }
}
</script>