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

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

    <!-- 登陆时出错 -->
    <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,
      back:"",
      name:"",
      openid: "",
      isError: "",
      message: "",
      template:""
    }
  },
  async mounted() {
    this.back = getParameterByName("back")
    this.name = getParameterByName("name")
    await this.requestUserinfo()
    await this.initialTemplate()
    this.initialWechatConfig()
  },
  methods: {
    async initialTemplate(){
      this.loading = true
      const result = await asyncRequest.template();
      this.loading = false;
      this.template = result.data.map(({priTmplId}) => priTmplId).join(",")
    },
    async initialWechatConfig(){
      const url = window.location.href.split("#")[0]
      const result = await asyncRequest.config({ url })
      const { appid, noncestr, signature, timestamp } = result.data;

      wx.config({
        appId:appid,
        timestamp,
        nonceStr: noncestr,
        signature,
        jsApiList:['chooseImage'],
        openTagList:['wx-open-subscribe']
      })

      wx.ready(() => {
        this.isReady = true;
      })

      wx.error(function(err){ console.log(err,'---') })
    },
    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))
      window.location.href = this.back + "/#/accept?t=" + encData
    },
    async getTemplate(){
      const result = await asyncRequest.template()
      console.log(result)
    }
  }
};
</script>
