<template>
  <div id="login-text">飞书扫码登录</div>
  <div id="login-container"></div>
</template>

<script lang="ts">
  import {config} from "./config";

  export default {
    name: 'FeishuLoginQR',
    data() {
      return {
        appId: 'cli_a8bc3f675078900c',
      };
    },
    mounted() {
      this.initQRCodeLogin();
    },
    methods: {
      initQRCodeLogin() {
        const redirectUri = encodeURIComponent(config.FEISHU_REDIRECTURI);
        const gotoUrl = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${config.FEISHU_APPID}&redirect_uri=${redirectUri}&response_type=code&state=STATE`;
        const QRLoginObj = window.QRLogin({
          id: 'login-container',
          goto: gotoUrl,
          width: '300',
          height: '300',
        });

        const handleMessage = (event) => {
          // 使用 matchOrigin 和 matchData 方法来判断 message 和来自的页面 url 是否合法
          if (QRLoginObj.matchOrigin(event.origin) && QRLoginObj.matchData(event.data)) {
            const loginTmpCode = event.data.tmp_code;
            // 在授权页面地址上拼接上参数 tmp_code，并跳转
            window.location.href = `${gotoUrl}&tmp_code=${loginTmpCode}`;
          }
        };
        if (typeof window.addEventListener != 'undefined') {
          window.addEventListener('message', handleMessage, false);
        } else if (typeof window.attachEvent != 'undefined') {
          window.attachEvent('onmessage', handleMessage);
        }
        // window.addEventListener('message', handleMessage, false);
      },
    },
  };
</script>

<style lang="less" scoped>
  #login-container {
    width: 300px;
    height: 300px;
    margin: 0 auto;
  }
  #login-text {
    font-weight: bold;
    text-align: center;
    margin-top: 10px;
    font-size: 14px;
  }
</style>
