<template>
  <div id="app">
    <watercom ref="watercom"></watercom>
    <router-view />
    <system-notify ref="notify" :msgData="msgData" @showDialog="showDialog" />
    <alarm-deal ref="alarmDeal"  @removeMessage="removeMessage"/>
  </div>
</template>
<script>
// import watercom from '@/components/waterCom.vue'
import SystemNotify from '@/components/SystemNotify/index.vue';
import AlarmDeal from '@/components/AlarmDeal/index.vue';
import config from "@/config";
import {mapGetters} from "vuex";
import {getToken} from '@/utils/auth'

export default {
  name: 'App',
  data() {
    return {
      messages:[],
      socket: null,
      msgData:{},
      currentIndex: 0,
      timer:null,
      heartBeatTimer:null,
    }
  },
  components: {
    SystemNotify,AlarmDeal
  },
  mounted() {
    //this.initWebSocket();
  },
  provide() {
    return {
      initWebSocket: this.initWebSocket,
    }
  },
  computed: {
    ...mapGetters(['userName', 'messageShow']),
  },
  methods: {
    showDialog(obj){
      this.$refs.alarmDeal.show = true;
      this.$refs.alarmDeal.data = obj;
    },
    removeMessage(iotAlarmDataId){
      console.log("处理报警id:"+iotAlarmDataId)
      let index = this.messages.findIndex(item => item.iotAlarmDataId+'' === iotAlarmDataId+'');
      if (index !== -1){
        this.messages.splice(index, 1)
      }
      this.currentIndex = 0;

      if (this.messages.length === 0){
        //无消息就不显通知
        clearInterval(this.timer);
        this.$refs.notify.show = false;
      }
    },
    startLoop() {
      this.$refs.notify.show = false;
      this.timer = setInterval(() => {
        if(this.messageShow){
          this.$refs.notify.show = true;
          this.nextItem();
        }
      }, 15 * 1000); // 每 15 秒切换一次
    },
    nextItem() {
      this.currentIndex = (this.currentIndex + 1) % this.messages.length;
      this.msgData = this.messages[this.currentIndex];
    },
    getWeSocketUrl(){
      let protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
      let url = "";
      if (config.baseApi === "/"){
        url = url + protocol + window.location.host + '/system/websocket';
      }else {
        url = url + protocol + window.location.host + config.baseApi + '/system/websocket';
      }
      url = url + '?Authorization=Bearer ' + getToken() + '&clientId=' + config.VITE_APP_CLIENT_KEY;
      return url;
    },
    initWebSocket() {
      if(!config.VITE_APP_WEBSOCKET || !getToken()){
        return;
      }

      // 使用浏览器提供的 WebSocket 对象
      this.socket = new WebSocket(this.getWeSocketUrl());

      // 监听 WebSocket 连接打开事件
      this.socket.addEventListener('open', (event) => {
        console.log('WebSocket 连接已建立:', event);
      });

      // 接收消息
      this.socket.addEventListener('message', (event) => {
        console.log('收到消息:', event.data);
        this.dealMessage(event.data);
        if(this.messages.length > 0){
          this.startLoop();
        }
      });

      // 连接关闭事件
      this.socket.addEventListener('close', (event) => {
        console.log('WebSocket 连接已关闭:', event);
        this.reconnect();
      });

      // 错误处理
      this.socket.addEventListener('error', (error) => {
        console.error('WebSocket 错误:', error);
        this.reconnect();
      });

      this.startSocketHeartBeat();
    },
    dealMessage(msg) {
      //收到消息首先清除显示
      clearInterval(this.timer);
      this.$refs.notify.show = false;

      let alarm =  JSON.parse(msg);
      //如果消息已经被处理了，就从队列中移除
      if(alarm.isDo && alarm.isDo === 1){
        this.removeMessage(alarm.iotAlarmDataId);
      }else {
        this.messages.push(alarm);
      }
    },
    clearMessage(){
      //websocket 清空消息
    },
    reconnect(){
      //定义重新连接的时间间隔
      const reconnectInterval = 30;
      setTimeout(() => {
        this.initWebSocket();
      }, reconnectInterval * 1000);
    },

    startSocketHeartBeat(){
      this.heartBeatTimer = setInterval(() => {
        if (this.socket.readyState === WebSocket.OPEN) {
          this.socket.send('ping');
          console.log('发送websocket心跳');
        }
      },30 * 1000);
    },
    stopHeartBeat(){
      console.log('停止websocket心跳');
      clearInterval(this.heartBeatTimer);
    }

  },
  beforeDestroy() {
    // 页面卸载前关闭 WebSocket 连接
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.close();
    }
    clearInterval(this.timer);
    this.stopHeartBeat();
  },

}

</script>
<style lang="scss">
html,body,div,h1,h2,h3,h4,h5,p{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  user-select: none;
  -moz-user-select:none; /* Firefox私有属性 */
  -webkit-user-select:none; /* WebKit内核私有属性 */
  -ms-user-select:none; /* IE私有属性(IE10及以后) */
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-size: 25px;
  user-select: none;
  -moz-user-select:none; /* Firefox私有属性 */
  -webkit-user-select:none; /* WebKit内核私有属性 */
  -ms-user-select:none; /* IE私有属性(IE10及以后) */
}
.fieldset{
  border: none;
  padding: 0;
  margin: 0;
}
pre{
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
