<template>
  <div id="qrcode">
    <img :src="dataUrl" />
  </div>
</template>

<script>
import Vue from 'vue';
import QRCode from 'qrcode';
export default {
  name: 'qrcode',
  props: {
    qrcode: null,
    uri: { type: String },
  },
  components: {},
  data: () => ({
    dataUrl: null,
    token: null,
  }),
  async mounted() {
    await this.initQrcode();
  },
  created() {},
  computed: {},
  methods: {
    async initQrcode() {
      // 创建二维码
      if (!this.qrcode) return;
      //二维码地址应该是变量,不过这里需要处理
      let uri = `${Vue.config.weixin.baseUrl}${this.uri}`;
      if (uri.startsWith('/')) {
        uri = `${location.protocol}//${location.host}${uri}`;
      }
      this.dataUrl = await QRCode.toDataURL(uri);
      this.$stomp({
        [`/exchange/qrcode.login/${this.qrcode}`]: this.onMessage,
      });
    },
    onMessage(message) {
      console.log('receive a message: ', message.body);
      if (message.body == 'scaned') {
        try {
          this.$emit('toReturn', message);
          console.log('扫码登录成功');
        } catch (err) {
          console.log('扫码登录失败');
          console.error(err);
        }
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
