import { ref } from 'vue';
import { ElMessage, ElNotification } from 'element-plus';
import eventBus from '@/utils/eventBus';

const websocket = ref<WebSocket | null>(null);
const isWebSocketConnected = ref(false);
let heartbeatInterval: number | null = null;

// 连接 WebSocket
const connectWebSocket = () => {
  websocket.value = new WebSocket(`ws://192.168.28.33:8080/ws/event`);
  websocket.value.onopen = () => {
    ElMessage.success('全局 WebSocket 连接成功');
    isWebSocketConnected.value = true;
  };
  websocket.value.onmessage = (event) => {
    const data = JSON.parse(event.data);

    // 显示通知，并在点击时通过 eventBus 触发全局弹窗事件
    showNotification(data);
  };
  websocket.value.onclose = handleClose;
  websocket.value.onerror = handleError;
};

// 关闭 WebSocket
const closeWebSocket = () => {
  if (websocket.value) {
    websocket.value.close();
    ElMessage.info('全局 WebSocket 已关闭');
    stopHeartbeat();
    isWebSocketConnected.value = false;
  }
};

// 启动心跳
const startHeartbeat = () => {
  if (heartbeatInterval) return;
  heartbeatInterval = window.setInterval(() => {
    if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
      websocket.value.send('ping');
    }
  }, 5000);
};

// 停止心跳
const stopHeartbeat = () => {
  if (heartbeatInterval) {
    clearInterval(heartbeatInterval);
    heartbeatInterval = null;
  }
};

// 处理连接关闭
const handleClose = () => {
  ElMessage.warning('WebSocket 连接已关闭');
  isWebSocketConnected.value = false;
  stopHeartbeat();
};

// 处理错误
const handleError = () => {
  ElMessage.error('WebSocket 连接出错');
  isWebSocketConnected.value = false;
  stopHeartbeat();
};

// 显示自定义通知
const showNotification = (data: any) => {
  ElNotification({
    title: '新告警',
    message: `
      <div style="max-height: 200px; overflow-y: auto;">
        <p><strong>告警编号：</strong>${data.id || '未知'}</p>
        <p><strong>摄像头编号：</strong>${data.camera_id || '未知'}</p>
        <p><strong>摄像头名称：</strong>${data.camera.name || '未知'}</p>
      </div>
    `,
    dangerouslyUseHTMLString: true,
    duration: 5000,
    customClass: 'custom-notification',
    onClick: () => {
      // 触发全局事件总线的 showDialog 事件
      eventBus.emit('showDialog', data);      
    }
  });
};

// 导出类型和方法
export interface GlobalWebSocket {
  connectWebSocket: () => void;
  closeWebSocket: () => void;
  isWebSocketConnected: typeof isWebSocketConnected;
}

export const useGlobalWebSocket = (): GlobalWebSocket => ({
  connectWebSocket,
  closeWebSocket,
  isWebSocketConnected,
});
