<template>
  <div style="display:none"></div>
</template>

<script>
import { getWechatQrCode, checkWechatScan } from "@/api/login";


export default {
  name: "WechatLoginDialog",
  props: {
    visible: Boolean,
    username: String,
    redirect: String
  },
  data() {
    return {
      qrUrl: "",     // 微信扫码登录URL（用来生成二维码内容）
      ticket: "",
      status: "waiting",
      timer: null,
      errorShown: false
    };
  },
  watch: {
    visible(newVal) {
      if (newVal && this.username) this.open(this.username);
    }
  },
  methods: {
    open(username) {
      getWechatQrCode({ username }).then(res => {
        this.ticket = res.data.state;
        const win = window.open(res.data.url); // 新开窗口扫码
        this.startPolling(win); // 传入窗口对象
      });
    },
    startPolling(win) {
      this.timer = setInterval(() => {
        checkWechatScan(this.ticket)
          .then(res => {
            if (res.code === 200 && res.data) {
              this.status = "success";
              clearInterval(this.timer);
              console.log("扫码成功，准备 emit 事件", res.data);

              this.$emit("update:visible", false);
              this.$emit("loginSuccess", res.data);

              if (win && !win.closed) {
                win.close(); // 扫码完成后自动关闭窗口
              }
            }
          })
          .catch(err => {
            clearInterval(this.timer);
            this.$emit("update:visible", false);

            if (!this.errorShown) {
              this.errorShown = true;
              this.$message.error(err.response?.data?.msg);
            }

            if (win && !win.closed) {
              win.close(); // 异常也关闭窗口
            }
          });
      }, 800);
    }

  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
  }
};
</script>
