<template>
  <a-config-provider :locale="locale">
    <div id="app">
      <router-view />
      <!-- <div id="" v-else>授权中....</div> -->
    </div>
  </a-config-provider>
</template>

<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import { wechatJssdk, getExternalUserInfo, getExternalUserInfoByCode } from './api/common'

export default {
  data() {
    return {
      locale: zhCN,
      loading: true,
      status: 'hahaha'
    }
  },
  mounted() {
    this.getUserId()
  },
  methods: {
    async getUserId() {
      const that = this
      localStorage.setItem('externalUserid', '') //每次进入时先清空客户id，以免出现各个客户之间id错误
      const { origin, pathname, search } = window.location
      const url = encodeURIComponent(origin + pathname + search)
      const res = await wechatJssdk(url)
      // const ua = window.navigator.userAgent
      // var version = ua.match(/wxwork\/([\d.]+)/)[1]
      window.wx.agentConfig({
        corpid: res.data.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
        agentid: res.data.agentid, // 必填，企业微信的应用id （e.g. 1000247）
        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
        signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
        jsApiList: ['getCurExternalContact', 'getContext', 'sendChatMessage'], //必填，传入需要使用的接口名称
        success: async function(res) {
          try {
            const code = new URLSearchParams(window.location.search).get('code')
            // const localUserId = ''
            const localUserId = localStorage.getItem('userId')
            const previousCode = localStorage.getItem('code')
            let res2
            // let res={userId:'wmdnmdCAAAccCBzpxlUDlDUc9Hkymcrw'}
            // if (true) {
            if (localUserId && code === previousCode) {
              that.loading = false
              return
            } else {
              res2 = await getExternalUserInfoByCode({
                code: code
              })
            }
            if (res2.data && res2.data.userId) {
              localStorage.setItem('userId', res2.data.userId)
              localStorage.setItem('code', code)
              that.loading = false
            }
          } catch (error) {
            alert('失败了')
            console.log(error)
            alert(JSON.stringify(error))
            localStorage.removeItem('userId')
          }
        },
        fail: function(res) {
          // alert(JSON.stringify(res))
          console.log(res)
          if (res.errMsg.indexOf('function not exist') > -1) {
            alert('版本过低请升级')
          }
        }
      })
    }
  }
}
</script>
