<template>
  <el-dialog title="公众号二维码" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="420px" @close="close" v-dialogDrag>
    <div class="box" style="width: 400px; height: 400px;  background-color: #FFF;">
      <el-image style="width: 100%; height: 100%" :src="qrCode" fit="fill" v-if="codeNumber===1"></el-image>
      <div class="img" v-if="codeNumber===2||codeNumber===3">
        <img style="width:100px; height: 100px;" src="../../../../../image/check.png" fit="fill" v-if="codeNumber===2&&openid">
        <img style="width:100px; height: 100px;" src="../../../../../image/close.png" fit="fill" v-if="codeNumber===3">
        <div class="title">{{codeNumber===2?'扫码关注成功':'二维码失效'}}</div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
var getOpenid = null;
import {
  getJavaQrCode,
  getJavaOpenid,
  doDeleteJavaOpenid,
} from "@/api/weixin/index.js";
export default {
  name: "qrCode",
  data() {
    return {
      qrCode: "",
      openid: "",
      dialogFormVisible: false,
      codeNumber: 1, //1为刚打开弹窗，2为扫码成功/关注成功，3为超时
    };
  },
  created() {
    // this.fetchJavaQrCode()
  },
  methods: {
    // ============================ 弹窗 ============================ //
    show(row) {
      let that = this;
      this.codeNumber = 1;
      this.openid = "";
      this.dialogFormVisible = true;
      this.handleDeleteJavaOpenid();
    },
    close() {
      this.qrCode = "";
      this.openid = "";
      this.dialogFormVisible = false;
    },
    // ============================== 查询 ============================== //
    // 通过后台获取公众号图片
    fetchJavaQrCode() {
      let that = this;
      getJavaQrCode().then((res) => {
        this.qrCode = window.URL.createObjectURL(res);
        getOpenid = setInterval(() => {
          that.fetchJavaOpenid();
        }, 2000);
        setTimeout(() => {
          clearInterval(getOpenid);
          that.codeNumber = 3;
        }, 60000);
      });
    },
    // 通过后台获取用户扫描的openid
    fetchJavaOpenid() {
      getJavaOpenid().then((res) => {
        if (res.data[0]) {
          this.codeNumber = 2;
          this.openid = res.data[0];
          this.$emit("call-back-qrCode", res.data[0]);
          clearInterval(getOpenid);
        }
      });
    },
    // 清除后台获取的openid
    handleDeleteJavaOpenid() {
      doDeleteJavaOpenid().then((res) => {
        if (res.code == "000000") {
          this.fetchJavaQrCode();
        }
      });
    },
  },
};
</script>
<style >
</style>
<style scoped>
.box {
  position: relative;
}
.img {
  position: absolute;
  top: 27px;
  left: 27px;
  width: 346px;
  height: 346px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.title {
  font-size: 28px;
  /* color: #fff; */
  margin-top: 30px;
}
</style>
