<template>
  <div class="weChatQrCode" v-if="false"></div>
</template>

<script>
import wx from 'weixin-js-sdk'
import { getSignature } from '@/api/wechat'
export default {
  data() {
    return {
      show: false
    }
  },
  methods: {
    open() {
      if (this.show) return
      this.show = true
      this.onScan()
    },
    onScan() {
      this.getConfig()
      const that = this
      try {
        console.log('测试测试ready')
        console.log(wx.ready)
        wx.ready(function() {
          console.log('测试2222')
          wx.checkJsApi({
            // 需要使用的JS接口列表，在这里只需要用到scanQRCode
            jsApiList: ['scanQRCode'],
            success: function(res1) {
              if (res1.checkResult.scanQRCode) {
                // 当scanQRCode可使用时
                wx.scanQRCode({
                  needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                  scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                  success: function(res2) {
                    const result = res2.resultStr
                    that.$emit('success', result)
                    // console.log(res2.resultStr, '扫描的结果~')
                    // window.location.href = result
                  },
                  error: function(response) {
                    this.close()
                    this.$nextTick(() => {
                      that.$toast(response)
                    })
                  }
                })
              }
            }
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    async getConfig() {
      const that = this
      const res = await getSignature({ url: encodeURIComponent(window.location.href.split('#')[0]) })
      // console.log('res', res)
      that.wxConfig(res.data.appId, res.data.params.timestamp, res.data.params.nonceStr, res.data.signature)
    },
    // wx.config的配置
    wxConfig(appId, timestamp, nonceStr, signature) {
      const that = this
      try {
        const params = {
          debug: true, // 开启调试模式,
          appId: appId, // 必填，企业号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature, // 必填，签名
          jsApiList: ['scanQRCode', 'checkJsApi'] // 必填，需要使用的JS接口列表
        }
        wx.config(params)
        wx.error(function(res) {
          console.log('测试测试111')
          that.close()
          alert('出错了👉' + res.errMsg) // wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
        })
        console.log('测试测试wxConfig')
      } catch (error) {
        console.log(error)
      }
    },
    close() {
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.weChatQrCode {
  width: 100%;
  height: 100%;
  z-index: 9999;
  position: fixed;
  top: 0;
  left: 0;
  background: #000;
}
</style>
