<template>
  <div id="app" v-cloak v-loading="loading">
    <!-- 未绑定账号 -->
    <div v-if="!isError && !isBound && !loading">
        <Binding :isWx="isWx" :openid="openid" :template="template" @bind="jumpToSystem" />
    </div>

    <!-- 已绑定账号 -->
    <div 
      v-if="!isError && isBound && !loading" 
      v-loading="true" 
      style="height:100vh" 
      :element-loading-text="` 正在登录至系统...`"
      />

    <!-- 登陆时出错 -->
    <UnusualState v-if="isError && !loading" :message="message" />
  </div>
</template>
<script>
import asyncRequest from "@/api"
import { getParameterByName } from "@/utils/auth"
import UnusualState from "@/components/unusual/index.vue"
import Binding from "@/components/binding/index.vue"
import CryptoJS from "crypto-js"

export default {
  name: 'report',
  components: { UnusualState, Binding },
  data() {
    return {
      loading: false,
      isBound: false,
      isReady:false,
      message: "",
      template:"",
      isError: "",
      openid: "",
      back:"",
      name:"",
      isWx:false
    }
  },
  created(){
    const ua = window.navigator.userAgent.toLowerCase();
    this.isWx = ua.match(/micromessenger/i) == 'micromessenger' && window.location.search !== "?from=authorization"
  },
  async mounted() {
    this.back = getParameterByName("back")
    this.name = getParameterByName("name")
    if(this.isWx) await this.requestUserinfo()
  },
  methods: {
    async requestUserinfo() {
      const code = getParameterByName("code")
      this.loading = true
      const result = await asyncRequest.userinfo({ code })
      this.loading = false

      if (result.data === null) {
        this.isError = true;
        this.message = result.message;
      }

      const { wxinfo, isLogin, userinfo } = (result.data || {})
      this.isBound =  Number(isLogin) === 1;
      this.openid = wxinfo.openid;

      if (!this.isBound) return;
      this.jumpToSystem(userinfo.token)
    },
    jumpToSystem(token = "") {
      const encJson = CryptoJS.AES.encrypt(JSON.stringify({ token }), "key123")
      const encData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encJson))
      console.log(this.back + "/#/accept?t=" + encData);
      window.location.href = this.back + "/#/accept?t=" + encData
    },
    async getTemplate(){
      const result = await asyncRequest.template()
      console.log(result)
    }
  }
};
</script>
