import { ref, computed } from 'vue';
import { EventSourcePolyfill } from 'event-source-polyfill';
import { generateUUID } from './uuidUtils';
import { getToken } from '@/utils/auth';

const defaultServerUrl = import.meta.env.VITE_APP_BASE_URL + '/sse';

interface EventData {
  timestamp: string;
  message: string;
  data: any;
  code: 200 | 201 | 300 | 400 | 500;
}

export interface logItem {
  message: string;
  type?: "success" | "error" | "log";
}

export interface SSEOptions {
  /** SSE服务器地址 */
  serverUrl?: string;
  /** 连接超时时间(毫秒) */
  timeout?: number;
  /** 客户端ID，不传则自动生成 */
  clientId?: string;
  /** 消息处理函数 */
  onMessage?: (data: string) => void;
  /** 连接成功回调 */
  onConnect?: () => void;
  /** 连接错误回调 */
  onError?: (error: Event | Error) => void;
  /** L1事件处理回调 */
  onL1Event?: (data: EventData) => void;
  /** L4事件处理回调 */
  onL4Event?: (data: EventData) => void;
  /** MES事件处理回调 */
  onMesEvent?: (data: EventData) => void;
}

function addSSEListener(eventSource: EventSource, type: string, handler: (data: any, event: MessageEvent) => void) {
  eventSource.addEventListener(type, (event) => {
    try {
      const data = JSON.parse(event.data);
      handler(data, event);
    } catch (err) {
      console.error('解析 SSE 数据失败:', err, event.data);
    }
  });
}

/**
 * SSE连接管理工具
 * @param options SSE连接选项
 */
export function useSSE(options: SSEOptions) {
  // 状态变量
  const logs = ref<logItem[]>([]);
  const isConnecting = ref(false);
  const isConnected = ref(false);
  const clientId = ref(options.clientId || generateUUID());
  const serverUrl = ref(options.serverUrl || defaultServerUrl);
  
  // 存储EventSource实例
  let eventSource: EventSource | null = null;
  let connectionTimeout: number | null = null;
  
  // 计算属性
  const sseStatus = computed(() => {
    if (isConnecting.value) return '连接中';
    if (isConnected.value) return '已连接';
    return '未连接';
  });
  
  const sseStatusClass = computed(() => {
    if (isConnecting.value) return 'connecting warning';
    if (isConnected.value) return 'connected success';
    return 'disconnected error';
  });
  
  // 添加日志
  const addLog = (message: string, type: 'success' | 'error' | 'log' = 'log') => {
    const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });
    const logEntry = `${timestamp} - ${message}`;
    logs.value.push({ message: logEntry, type });
    return logEntry;
  };
  
  // 连接SSE
  const connect = () => {    
    // 先断开可能存在的连接
    if (eventSource) {
      disconnect();
    }
    
    isConnecting.value = true;
    
    try {
      // 确保URL不为空
      if (!serverUrl.value) {
        throw new Error('SSE服务器地址不能为空');
      }
      
      const connectUrl = `${serverUrl.value}/connect`;
      addLog(`开始连接到 ${connectUrl}...`);
      
      // 设置连接超时
      if (connectionTimeout) {
        clearTimeout(connectionTimeout);
      }
      
      connectionTimeout = window.setTimeout(() => {
        if (isConnecting.value) {
          addLog('连接超时，请检查服务器地址或网络连接', 'error');
          isConnecting.value = false;
          if (eventSource) {
            eventSource.close();
            eventSource = null;
          }
          
          // 调用错误回调
          if (options.onError) {
            options.onError(new Error('连接超时'));
          }
        }
      }, options.timeout || 10000); // 默认10秒超时
      
      // 创建EventSource
      const eventSourceOptions = {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
        heartbeatTimeout: 90 * 60 * 1000,
      };
      eventSource = new EventSourcePolyfill(connectUrl, eventSourceOptions);
      
      eventSource.onopen = () => {
        if (connectionTimeout) {
          clearTimeout(connectionTimeout);
          connectionTimeout = null;
        }
        
        isConnected.value = true;
        isConnecting.value = false;
        addLog('SSE 连接已建立', 'success');
        
        // 调用连接成功回调
        if (options.onConnect) {
          options.onConnect();
        }
      };
      
      eventSource.onmessage = (event) => {
        addLog(`收到消息: ${ JSON.parse(event.data).message }`);
        console.log(event)
        
        // 调用消息处理回调
        if (options.onMessage) {
          options.onMessage(event.data);
        }
      };
      
      // 添加事件监听器
      addSSEListener(eventSource, 'L1_EVENT', (data) => {
        console.log('收到 L1_EVENT:', data);
        if (options.onL1Event) {
          options.onL1Event(data);
        }
      });
      addSSEListener(eventSource, 'L4_EVENT', (data) => {
        console.log('收到 L4_EVENT:', data);
        if (options.onL4Event) {
          options.onL4Event(data);
        }
      });
      addSSEListener(eventSource, 'MES_EVENT', (data) => {
        console.log('收到 MES_EVENT:', data);
        if (options.onMesEvent) {
          options.onMesEvent(data);
        }
      });
      
      eventSource.onerror = (err) => {
        if (connectionTimeout) {
          clearTimeout(connectionTimeout);
          connectionTimeout = null;
        }
        
        addLog('SSE 连接错误，请检查服务器地址或网络连接', 'error');
        isConnected.value = false;
        isConnecting.value = false;
        
        if (eventSource) {
          eventSource.close();
          eventSource = null;
        }
        
        // 调用错误回调
        if (options.onError) {
          options.onError(err);
        }
      };
    } catch (error) {
      addLog(`连接失败: ${error}`, 'error');
      isConnecting.value = false;
      
      // 调用错误回调
      if (options.onError && error instanceof Error) {
        options.onError(error);
      }
    }
  };
  
  // 断开连接
  const disconnect = () => {
    if (connectionTimeout) {
      clearTimeout(connectionTimeout);
      connectionTimeout = null;
    }
    
    if (eventSource) {
      eventSource.close();
      eventSource = null;
    }
    
    addLog('已断开连接', 'log');
    isConnected.value = false;
  };
  

  
  return {
    logs,
    isConnecting,
    isConnected,
    clientId,
    serverUrl,
    sseStatus,
    sseStatusClass,
    connect,
    disconnect,
    addLog
  };
}