import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import { useNoticeStore } from '@/store/modules/notice';

function triggerAlarmFlash() {
  document.body.classList.remove('ems-alarm-flash');
  void document.body.offsetWidth;
  document.body.classList.add('ems-alarm-flash');
  window.setTimeout(() => {
    document.body.classList.remove('ems-alarm-flash');
  }, 8000);
}

function handleAlarmMessage(payload: any) {
  const alarm = payload.data || {};
  const messageLines = [
    alarm.alarmDeviceName ? `报警设备：${alarm.alarmDeviceName}` : '',
    alarm.alarmPosition ? `报警位置：${alarm.alarmPosition}` : '',
    alarm.alarmTime ? `报警时间：${alarm.alarmTime}` : '',
    alarm.alarmLevel ? `报警等级：${alarm.alarmLevel}` : '',
    alarm.alarmDetail || payload.message || ''
  ].filter(Boolean);
  const message = messageLines.join('\n');

  triggerAlarmFlash();
  useNoticeStore().addNotice({
    message: payload.message || '设备告警',
    read: false,
    time: new Date().toLocaleString()
  });
  ElNotification({
    title: '设备告警',
    message: messageLines.length ? messageLines.join('<br />') : '设备发生告警',
    type: 'error',
    position: 'top-right',
    duration: 0,
    showClose: true,
    dangerouslyUseHTMLString: true
  });
}

export const initAlarmWebSocket = (url: string) => {
  // if (import.meta.env.VITE_APP_WEBSOCKET === 'false') {
  //   return;
  // }

  const alarmUrl = `${url}?Authorization=Bearer ${getToken()}&clientid=${import.meta.env.VITE_APP_CLIENT_ID}&channel=alarm`;
  useWebSocket(alarmUrl, {
    autoReconnect: {
      retries: 3,
      delay: 1000,
      onFailed() {
        console.log('alarm websocket重连失败');
      }
    },
    heartbeat: {
      message: JSON.stringify({ type: 'ping' }),
      interval: 10000,
      pongTimeout: 2000
    },
    onConnected() {
      console.log('alarm websocket已经连接');
    },
    onDisconnected() {
      console.log('alarm websocket已经断开');
    },
    onMessage: (_, e) => {
      if (String(e.data).includes('ping') || String(e.data).includes('pong')) {
        return;
      }
      try {
        const payload = JSON.parse(e.data);
        if (payload.type === 'alarm') {
          handleAlarmMessage(payload);
        }
      } catch (error) {
        // 报警 WS 只处理 JSON 格式的 alarm 消息。
      }
    }
  });
};
