<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,
  },
  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}/qrcode/${this.qrcode}/scan`;
      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>
