<template>
  <div class="mine">
    <div class="qr-code">
      <div id="qrCode" ref="qrCodeDiv"></div>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import api from "../../server/home";
export default {
  components: {},
  data() {
    return {
      qrcode_string: "",
      ticket: "",
      checkCodeInterval: null,
      checkCodeTimeout: null
    };
  },
  computed: {},
  watch: {},

  methods: {
    getAuthCode() {
      api.getAuthCode().then(res => {
        this.qrcode_string = res.data.qrcode_string;
        this.ticket = res.data.ticket;
        this.$nextTick(() => {
          this.bindQRCode();
          this.checkCode();
        });
      });
    },
    checkCode() {
      this.checkCodeInterval = setInterval(e => {
        api.checkCode({ ticket: this.ticket }).then(res => {
          if (res.data.status == 1) {
            clearInterval(this.checkCodeInterval);
            this.getOrderByCode();
          }
        });
      }, 1000);
      //十分钟强制清除，防止页面崩溃
      this.checkCodeTimeout = setTimeout(() => {
        clearTimeout(this.checkCodeTimeout);
      }, 360000); 
    },
    getOrderByCode() {
      api.getOrderByCode({ ticket: this.ticket }).then(res => {
        if (res.code == 200) {
          // 无订单入口
          if (res.data.order_id == 0) {
            this.$router.push({
              path: "/confirmOrder/addOrder",
              query: {   //user_id
                data: JSON.stringify(res.data),
                // user_id:res.data.user.user_id
              }
            });
          return
          }

          this.$router.push({
            path: "/confirmOrder/details",
            query: {
              id: res.data.order_id
            }
          });
        }
      });
    },
    bindQRCode() {
      new QRCode(this.$refs.qrCodeDiv, {
        text: this.qrcode_string,
        width: 200,
        height: 200,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L //容错率，L/M/H
      });
    }
  },

  created() {
    this.getAuthCode();
  },

  mounted() {},
  destroyed() {
    if (this.checkCodeInterval) {
      clearInterval(this.checkCodeInterval);
      clearTimeout(this.checkCodeTimeout);
    }
  }
};
</script>

<style lang='less' scoped>
.mine {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(184, 191, 198, 0.2);
  border-radius: 8px;
  .qr-code {
    width: 200px;
    img {
      width: 100%;
    }
  }
}
</style>
