import local from "@/utils/local";
import moment from "moment";
function createError() {
  let dom;
  return function (err) {
    if (dom) {
      dom.innerText = err || "MQ通讯异常";
      return dom;
    } else {
      let createdDom = document.createElement("div");
      createdDom.style.position = "absolute";
      createdDom.style.left = "0";
      createdDom.style.bottom = "10px";
      createdDom.style.width = "100%";
      createdDom.style.textAlign = "center";
      createdDom.style.fontSize = "12px";
      createdDom.style.color = "red";
      createdDom.style.zIndex = 10;
      createdDom.style.display = "none";
      createdDom.innerText = err || "MQ通讯异常";
      document.body.appendChild(createdDom);
      dom = createdDom;
      return dom;
    }
  };
}
const errorFn = createError();

// 解密BASE64
function BASE64Decode(t) {
  return JSON.parse(Base64.decode(t));
}

export default {
  data() {
    return {
      settimer: null, //定时器添加心跳
      StompObj: null,
      ws: null,
    };
  },
  mounted() {
    // 调用安卓获取mq数据 JS 重新封装sdk
    setTimeout(() => {
      this.fnAndroidJsSdk();
    }, 1000);
  },
  methods: {
    fnAndroidJsSdk() {
      let _this = this;
      try {
        androidJsSdk(
          { action: "query", msg: "index" },
          {
            success: function (d) {
              _this.WebSocketMq(d);
            },
            fail: function (d) {
              alert(d.msg + "，查询本地数据失败");
            },
          }
        );
      } catch (error) {
        setTimeout(() => {
          this.fnAndroidJsSdk();
        }, 1000);
        console.log(error);
      }
    },
    clientMp(obj) {
      var StompObj = this.StompObj;
      if (StompObj == null || !StompObj.connected) {
        var _this = this;
        var downTopicFilter = obj.downTopicFilter.replace(/\//g, "%2F");
        var uploadTopicFilter = obj.uploadTopicFilter.replace(/\//g, "%2F");
        this.ws = new WebSocket(`ws://${obj.host}:15674/ws`);
        var ws = this.ws;
        this.StompObj = Stomp.over(ws);
        var client = this.StompObj;
        var conditions = {
          durable: true,
          "x-message-ttl": parseInt(obj.messageTtl),
        };
        client.connect(
          obj.username,
          obj.password,
          function (x) {
            client.subscribe(
              "/queue/" + downTopicFilter,
              function (data) {
                var msg = data.body;

                if (msg) {
                  var json = JSON.parse(msg);
                  // 解密后数据
                  //   var mqOBJ = BASE64Decode(json.data);
                  switch (json.headers.data.messageType) {
                    case "restartapp":
                      // 重启软件
                      try {
                        androidJsSdk(
                          { action: "restartapp", msg: "" },
                          {
                            success: function (d) {},
                            fail: function (d) {},
                          }
                        );
                      } catch (error) {
                        console.log(error);
                      }
                      break;
                    case "restartdevice":
                      // 重启设备
                      try {
                        androidJsSdk(
                          { action: "restartdevice", msg: "" },
                          {
                            success: function (d) {},
                            fail: function (d) {},
                          }
                        );
                      } catch (error) {
                        console.log(error);
                      }
                      break;
                    case "sitechange":
                      // 站点名称变更
                      _this.getHomeInfo();
                      break;
                    case "edition":
                      // 皮肤换肤通知
                      _this.getSetinfo();
                      break;
                    case "UPGREAD":
                      // 跟新软件
                      try {
                        androidJsSdk(
                          { action: "update", msg: "" },
                          {
                            success: function (d) {},
                            fail: function (d) {
                              _this.$message.error("调用升级异常");
                            },
                          }
                        );
                      } catch (error) {
                        console.log(error);
                      }
                      break;
                  }
                }
              },
              conditions
            );
            // 心跳上行消息
            _this.settimer = setInterval(() => {
              let beatObj = {
                data: "=",
                headers: {
                  data: {
                    protocol: "json",
                    messageType: "HEART_BEAT",
                    deviceCode: _this.devicenum,
                    sign: "abcd1234",
                    timestamp: moment().format("YYYY-MM-DD H:mm:ss"),
                  },
                },
                key: new Date().getTime() + "-" + _this.devicenum,
              };
              client.send(
                "/queue/" + uploadTopicFilter,
                { "x-message-ttl": parseInt(obj.messageTtl) },
                JSON.stringify(beatObj)
              );
            }, 1000 * 60);
            errorFn().style.display = "none";
          },
          function (e) {
            errorFn(`MQ通讯异常：${e}`).style.display = "block";
            _this.settimer && clearInterval(_this.settimer);
            _this.StompObj = null;
            _this.ws = null;
            setTimeout(() => {
              _this.clientMp(obj);
            }, 1000);
          },
          obj.virtualHost
        );
      }
    },
    // mq通讯
    WebSocketMq(objc) {
      var obj = objc.rabbmitInfo; //mq信息
      var serviceInfo = objc.serviceInfo; //服务器信息
      var deviceInfo = objc.deviceInfo; //设备信息
      var serverUrl = serviceInfo.serverUrl; //系统地址
      var siteId = deviceInfo.siteId; //站点id
      // 保存地址
      local.setLocal("serverUrl", serverUrl);
      local.setLocal("siteId", siteId);
      // 初始化接口
      setTimeout(() => {
        // 查询站点信息
        this.getHomeInfo();
        // 查询皮肤
        this.getSetinfo();
      });
      // mq连接
      this.clientMp(obj);
    },
  },
};
