<template>
  <view class="container">
    <div>微信公众号-授权认证中</div>
  </view>
</template>

<script>
const {Base64} = require('js-base64');
export default {
  data() {
    return {
      openId: null,
      code: null
    }
  },
  created() {
    this.handleAuthorization();
  },
  methods: {
    handleAuthorization() {
      this.code = this.getParameters('code');
      this.getOpenId(this.code);
    },
    getOpenId(code) {
      let that = this;
      this.$api.loginApi.getWechatOpenId(code).then(res => {
        console.log("res", res);
        if (res.openid) {
          that.openId = res.openid;
          //首次登录未绑定账号去登录页登录后触发绑定
          console.log("获取openId", that.openId);
          uni.setStorageSync('openId', this.openId)
          uni.navigateTo({
            url: '/pages/login'
          })
        } else {
          //已经绑定直接缓存token 跳转到主页
          this.$store.dispatch('wxAuthLogin', res).then(e => {
            uni.switchTab({
              url: '/pages/home/home'
            });
          }).catch(err => {
            uni.$u.toast(err)
          })
        }
      });
    },
    //获取url中的参数
    getParameters(name) {
      var locUrl = decodeURI(window.location.search.substr(1))
      var aryParams = locUrl.split('&')
      var rtn = ''
      for (var i = 0; i < aryParams.length; i++) {
        var pair = aryParams[i]
        var aryEnt = pair.split('=')
        var key = aryEnt[0]
        var val = aryEnt[1]
        if (key != name) continue
        if (rtn == '') {
          rtn = val
        } else {
          rtn += ',' + val
        }
      }
      return rtn
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
</style>
