<template>
  <view>
    <u-toast ref="uToast" />
  </view>
</template>
<script>
export default {
  data() {
    return {
      text: "",
      // 确保websocket是打开状态
      is_open_socket: false,
      timer: 10000,
      alertList: [],
      num: 0,
      isClose: false,
      showMian: false,
      is_open_socket: false,
      objData: {},
      host: "",
    };
  },
  props: {
    isBack: {
      type: [Boolean, String],
      default: false,
    },
  },
  onLaunch: function () {
    console.warn(
      "当前组件仅支持 uni_modules 目录结构 ，请升级 HBuilderX 到 3.1.0 版本以上！"
    );
    console.log("App Launc11h");
  },

  onShow() {},
  onHide: function () {
    console.log("App Hide");
    let that = this;
    that.isClose = true;
    uni.getStorage({
      key: "isBackShow",
      success(res) {
        console.log("退出", res.data);
        if (res.data == true) {
          that.isClose = true;
          uni.closeSocket();
          that.socketTask = null;
          return clearInterval(that.timer);
        }
      },
    });
  },
  created() {
    console.log("创建");
    console.log("路径", this.$route.path);
  },
  mounted() {
    let _this = this;
    uni.getStorage({
      key: "hostappst",
      success(res) {
        console.log("获取成功", res.data);
        _this.host = res.data;
        uni.showToast({
          title: _this.host,
          icon: "none",
        });
      },
    });
    uni.getStorage({
      key: "num",
      success(res) {
        console.log("获取成功", res.data);
        if (res.data != "") {
          _this.num = res.data;
          _this.getStort();
        }
      },
    });

    console.log("渲染1");
  },
  beforeDestroy() {
    console.log("退出0");
    let that = this;
    that.isClose = true;
    uni.getStorage({
      key: "isBackShow",
      success(res) {
        console.log("退出", res.data);
        uni.closeSocket();

        that.socketTask = null;
        return (that.isClose = true);
        clearInterval(that.timer);
      },
    });
    //
  },
  methods: {
    getStort() {
      let _this = this;
      uni.getStorage({
        key: "num",
        success(res) {
          console.log("获取成功", res.data);
          _this.num = res.data;
          _this.connectSocket();
        },
      });
    },
    //连接websocket
    connectSocket() {
      let that = this;
      console.log("调用连接websocket", this.socketTas, "this.num", this.num);
      this.socketTask = uni.connectSocket({
        url: `ws://${that.host}/websocket/device/` + this.num,
        success(res) {
          console.log("res", res);
          console.log("websocket连接成功");
        },
        fail(err) {
          console.log("报错", err);
        },
      });
      this.socketTask.onOpen(function (res) {
        console.log("WebSocket连接已打开！");
        that.isSuccess = true;
        that.heart();
      });
      this.socketTask.onMessage(function (res) {
        that.objData = JSON.parse(JSON.stringify(JSON.parse(res.data)));
        console.log("收到服务器内容：", that.objData.type);
        console.log("未解析:收到服务器内容：", res.data);
        if (that.objData.type == "notify") {
          console.log("进", that.objData.content.content);
          if (that.objData.content.status == 1) {
            uni.showToast({
              title:
                that.objData.content.deviceName + that.objData.content.content,
              icon: "none",
            });
          } else {
            that.showMian = true;
            if (that.$store.state.alertList.length < 16) {
              console.log("长度");
              that.$store.state.alertList.unshift(that.objData.content);
              that.$store.commit("setalertList", that.$store.state.alertList);
            } else {
              // 使用filter和findIndex进行去重
              let uniqueDataList = that.$store.state.alertList.filter(
                (item, index, self) => {
                  console.log("进到里面---------------");
                  // 返回第一个匹配项的索引，用于判断当前项是否为第一个匹配项
                  const firstIndex = self.findIndex(
                    (obj) => obj.deviceId === item.deviceId
                  );
                  // 如果当前项是第一个匹配项，则保留，否则过滤掉
                  return index === firstIndex;
                }
              );
              that.$store.state.alertList = "";
              console.log("uniqueDataList", uniqueDataList);
              that.$store.state.alertList = [...uniqueDataList];
              that.$store.commit("setalertList", that.$store.state.alertList);
            }
            console.log(
              "数组",
              that.$store.state.alertList,
              "$store.state.name"
            );
          }
        }
      });

      this.socketTask.onError(function (res) {
        console.log("WebSocket连接打开失败，请检查！");
        console.log(res);
        //进入重新连接
        setTimeout(() => {
          if (that.$route.path != "/") {
            that.reconnect();
          }
        }, 5000);
      });
      // // 监听连接关闭 -
      this.socketTask.onClose((e) => {
        console.log("WebSocket连接关闭！");
        clearInterval(that.timer);
        that.timer = "";
        console.log("that.isClose", this.isClose);
        setTimeout(() => {
          if (that.$route.path != "/") {
            that.reconnect();
          }
        }, 5000);
      });
      console.log(this.socketTask);
    },
    //进入重新连接
    reconnect() {
      console.log("进入断线重连");

      this.socketTask = null;
      setTimeout(() => {
        this.connectSocket();
      }, 5000);
    },
    //发送消息
    sendSocketMessage(msg) {
      console.log("发送信息", msg);
      console.log(msg);
      return new Promise((reslove, reject) => {
        this.socketTask.send({
          data: msg,
          success(res) {
            console.log("发送成功");
            reslove(res);
          },
          fail(res) {
            console.log("发送失败");
            console.log(res);
            reject(res);
          },
        });
      });
    },

    //心跳
    heart() {
      console.log("this.timer", this.timer);
      let that = this;
      clearInterval(this.timer);
      this.timer = "";
      let msg = {
        type: "heartbeat",
      };
      this.timer = setInterval(() => {
        that
          .sendSocketMessage(JSON.stringify(this.num))
          .then((res) => {
            console.log("心跳成功");
          })
          .catch((res) => {
            console.log("发送失败");
            console.log(res);
          });
      }, 10000);
    },
    closeSocket() {
      this.socketTask.close({
        success(res) {
          this.is_open_socket = false;
          console.log("关闭成功", res);
        },
        fail(err) {
          console.log("关闭失败", err);
        },
      });
    },
  },
};
</script>

<style lang="scss"></style>
