<!--<template>-->
<!--  <el-dialog title="微信扫码验证" :visible.sync="visible" width="300px">-->
<!--    <div class="flex flex-col items-center justify-center">-->
<!--      &lt;!&ndash; 直接用 qrcode-vue 生成二维码 &ndash;&gt;-->
<!--      <qrcode-vue :value="qrUrl" :size="200" v-if="qrUrl" />-->
<!--      <p v-if="status==='waiting'">请使用微信扫码确认</p>-->
<!--      <p v-if="status==='success'">验证成功，正在跳转...</p>-->
<!--    </div>-->
<!--  </el-dialog>-->
<!--</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>
