<template>
  <!-- <div>小程序-授权认证中</div> -->
  <div>
    <van-empty
      :description="loginFail ? tips : '小程序-授权认证中...'"
      image="network"
    >
      <van-button
        v-if="loginFail"
        type="primary"
        class="bottom-button"
        to="login"
      >
        前往登录页
      </van-button>
    </van-empty>
    <van-overlay :show="showOverlay" @click="showOverlay = false">
      <div class="wrapper" @click.stop>
        <van-loading text-color="#0094ff" vertical type="spinner">
          {{ tips }}
        </van-loading>
      </div>
    </van-overlay>
  </div>
</template>
<script>
  import req from '@/request.js'
  import utils from '@/jump.js'
  export default {
    data() {
      return {
        code: '',
        showOverlay: false,
        tips: '',
        loginFail: false,
      }
    },
    created() {
      if (sessionStorage.getItem('currentUser')) {
        this.$router.push({ path: '/home' })
        return
      }
      let _this = this
      let code = utils.getParameters('code')
      if (!code) {
        this.showOverlay = true
        this.tips = '无code参数，将跳转至登录页。。。'
        setTimeout((e) => {
          _this.showOverlay = false
          _this.$router.push('/login')
        }, 2000)
        return
      }
      this.code = code
      this.proxyLogin()
    },
    methods: {
      proxyLogin() {
        this.showOverlay = true
        this.tips = '小程序授权认证中...'
        let _this = this
        let url = window.context.auth + '/sso/miniprogram?code=' + _this.code
        req
          .get(url, null, false)
          .then((resp) => {
            if (resp.data.state) {
              sessionStorage.setItem(
                'currentUser',
                JSON.stringify(resp.data.value)
              )
              // sessionStorage.setItem('token', resp.data.value.token)
              // sessionStorage.setItem('username', resp.data.value.username)
              // sessionStorage.setItem('account', resp.data.value.account)
              // sessionStorage.setItem('userId', resp.data.value.userId)
              _this.$router.push('/home')
            } else {
              sessionStorage.setItem('mpOpenid', resp.data.value)
              _this.$router.push('/login')
              // _this.showOverlay = true
              // _this.tips = '未绑定小程序，跳转登录页'
              // setTimeout(e => {
              //   _this.showOverlay = false
              // }, 1000)
            }
          })
          .catch((e) => {
            this.showOverlay = false
            this.loginFail = true
            this.tips = e.response.data.message
          })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    background-color: #fff;
  }
</style>
