<template>
  <el-dialog
    title="微信支付"
    :visible.sync="dialogVisible"
    width="520px"
    top="0"
    :close-on-click-modal="false"
    @open="confirm()"
    @close="cancelBtn()"
  >
    <div class="pay_code">
      <div v-show="isShowqr == 1">
        <!-- <div class="pay_time">支付剩余时间<span>15分30秒</span></div> -->
        <div class="money">￥{{ has_amount }}</div>
        <div class="img_qr">
          <div class="qrcode" ref="qrCodeUrl"></div>
        </div>
        <div>请使用<span>微信</span>扫一扫，扫描二维码支付</div>
        <div>
          付款码为动态码，仅支持通过本页面进行扫描付款操作，不支持另存图片后扫描支付。
        </div>
      </div>
      <div v-show="isShowqr == 2">
        <div class="info_2" style="color: #000; font-size: 18px">
          <i class="el-icon-warning"></i>{{ message }}
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <div class="btn">
        <el-button @click="updateCode()">刷新二维码</el-button>
        <!-- <el-button class="cancel" @click="cancelBtn()">取 消</el-button> -->
      </div>
    </span>
  </el-dialog>
</template>

<script>
/* eslint-disable */
import { getWxConfig } from "r/index/pay";
import { SERVER_WS_URL } from "config/server";
import QRCode from "qrcodejs2";
export default {
  name: "ConfirmSignUp",
  props: {
    confirmSignUpDialogFu: Boolean,
  },
  data() {
    return {
      dialogVisible: this.confirmSignUpDialogFu,
      message: "",
      isShowqr: 0, // 展示支付二维码
      token: "",
      websocket: null, //websocket连接
      lockReconnect: false, //是否真正建立连接
      timeout: 28 * 1000, //30秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      has_amount: "",
    };
  },
  created() {
    this.token = window.localStorage.getItem(
      "index-token" + this.$store.state.indexIdentity
    );
    this.has_amount = window.localStorage.getItem(
      "has_amount" + this.$store.state.indexIdentity
    );
  },
  methods: {
    async confirm() {
      // console.log(SERVER_WS_URL);
      let { data: res } = await getWxConfig({
        pay_type: 3,
      });
      // console.log(res);

      if (res.code !== 200) {
        if (res.code == 400801) {
          return this.cancelBtn();
        }
        this.isShowqr = 2;
        this.message = res.message;

        return;
      }
      this.isShowqr = 1;
      console.log(res.code_url);
      this.createQrCode(res.code_url);
      //初始化 websocket 链接
      this.initWebSocket();
    },
    updateCode() {
      this.confirm();
    },
    createQrCode(qrCode) {
      this.removeQr();
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: qrCode, // 需要转换为二维码的内容
        width: 140,
        height: 140,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    },
    // 删除二维码img标签
    removeQr() {
      if (this.$refs.qrCodeUrl) {
        // 获取 父 标签下的所有子节点
        let pObjs = this.$refs.qrCodeUrl.childNodes;
        // console.log(pObjs);
        for (var i = pObjs.length - 1; i >= 0; i--) {
          // 一定要倒序，正序是删不干净的，可自行尝试
          this.$refs.qrCodeUrl.removeChild(pObjs[i]);
        }
      }
    },
    // 确认,关闭弹框，修改父组件的值
    cancelBtn() {
      // 关闭时，删除二维码img标签
      this.removeQr();
      this.closeWebSocket();
      this.dialogVisible = false;
      this.$emit("closeCFSUDialog", this.dialogVisible, false);
    },
    // 初始化 webSocket
    initWebSocket() {
      if (typeof WebSocket == "undefined") {
        this.$message({
          showClose: true,
          message: "您的浏览器不支持WebSocket",
          type: "error",
        });
      } else if (!this.dialogVisible) {
        return;
      } else {
        let code = this.$store.state.indexIdentity;
        if (!this.token || this.token == "") {
          this.token = window.localStorage.getItem("index-token" + code);
        }
        let token = this.token;
        const wssURL = SERVER_WS_URL + "/order?token=" + token + "&channel=pc";
        this.websocket = new WebSocket(wssURL);
        // console.log(this.websocket)
        // 连接发生错误的回调方法
        this.websocket.onerror = this.websocketOnerror;
        // 连接成功建立的回调方法
        this.websocket.onopen = this.websocketOnopen;
        // 接收到消息的回调方法
        this.websocket.onmessage = this.websocketOnmessage;
        // 连接关闭的回调方法
        this.websocket.onclose = this.websocketOnclose;
        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        this.websocket.onbeforeunload = this.websocketOnbeforeunload;
        // this.websocketSend();
        // setTimeout(() => {
        //   this.websocketSend();
        // }, 1000);
      }
    },
    reconnect() {
      //重新连接
      let that = this;
      if (!that.dialogVisible) {
        return;
      }
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    reset() {
      //重置心跳
      let that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {
      //开启心跳
      let self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.websocket.readyState == 1) {
          //如果连接正常
          self.websocket.send("heartCheck");
        } else {
          //否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          //超时关闭
          self.websocket.close();
        }, self.timeout);
      }, self.timeout);
    },
    // 连接发生错误的回调方法
    websocketOnerror() {
      this.$message.error("WebSocket连接发生错误");
      //重连
      this.reconnect();
    },
    // 连接成功建立的回调方法
    websocketOnopen() {
      this.websocketSend();
      // console.log("连接成功建立的回调方法");
      //开启心跳
      this.start();
    },
    websocketSend() {
      //数据发送
      let sendData = {
        order_no: window.localStorage.getItem(
          "order_no" + this.$store.state.indexIdentity
        ),
        cam_id: window.localStorage.getItem(
          "campsite_id" + this.$store.state.indexIdentity
        ),
        token: this.token,
      };
      this.websocket.send(JSON.stringify(sendData));
    },
    // 接收到消息的回调方法
    websocketOnmessage(event) {
      // console.log(event, "event");
      if (event.data !== "Opened") {
        //const data = JSON.parse(event.data);
        // console.log("接收到消息的回调方法", event.data);
        if (event.data == 1) {
          this.lockReconnect = false;

          this.closeWebSocket();
          this.dialogVisible = false;
          this.$emit("closeCFSUDialog", this.dialogVisible, true);
          // status=6，跳转到报名成功页面
          // this.$emit("getstatus", res.data.status.status);
          let code = this.$store.state.indexIdentity;
          this.$router.push("/signUp/success?code=" + code);
        } else {
          //收到服务器信息，心跳重置
          this.reset();
        }
      }
    },
    // 连接关闭的回调方法
    websocketOnclose() {
      // console.log("连接关闭的回调方法");
      //重连
      this.reconnect();
    },
    // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
    websocketOnbeforeunload() {
      this.closeWebSocket();
      // console.log('监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常');
    },
    // 关闭WebSocket连接
    closeWebSocket() {
      this.websocket && this.websocket.close();
    },
  },
  // 页面注销时候调用 避免连接错误
  // destroyed() {
  //   this.closeWebSocket();
  // },
  watch: {
    confirmSignUpDialogFu() {
      this.dialogVisible = this.confirmSignUpDialogFu;
    },
  },
};
</script>

<style scoped lang="scss">
.btn {
  text-align: center;
  padding-bottom: 24px;
}
.el-button {
  width: 200px;
  height: 50px;
  background: var(--color);
  border-radius: 4px;
  opacity: 0.8;
  line-height: 50px;
  text-align: center;
  color: #fff;
  font-size: 16px;
  padding: 0;
}
.pay_code {
  text-align: center;

  .money {
    font-size: 20px;
    font-weight: 500;
    color: var(--color);
    line-height: 24px;
  }
}

.img_qr {
  width: 140px;
  height: 140px;
  padding: 10px;
  // border: 1px solid #000;
  margin: 0 auto;
}
</style>
