// src/utils/sse.js
// import store from "../store";
import tool from "@/utils/tool";
import systemConfig from '@/config';
import {eventBus} from "@/utils/eventBus";

let eventSource = null;
let reconnectTimer = null;
const reconnectDelay = 5000;
let isConnected = false;
let lockReconnect = false;
const callbacks = new Map();
const url = systemConfig.SSE_URL;

// 改进的连接管理
function createSSE(token) {
	if (isConnected && eventSource) return;

	closeSSE();

	try {
		let reToken = token === undefined ? tool.cookie.get('TOKEN') : token;
		if(!reToken) return;
		eventSource = new EventSource(`${url}?token=${reToken}`);

		// 使用具名函数以便于移除监听器
		eventSource.onopen = onOpen;
		eventSource.onmessage = onMessage;
		eventSource.onerror = onError;

	} catch (error) {
		console.error('创建SSE连接失败:', error);
		handleDisconnect();
	}
}

// 具名事件处理函数
function onOpen() {
	isConnected = true;
	console.log('SSE连接已建立');
}

function onMessage(event) {
	try {
		const res = JSON.parse(event.data);
		// store.commit('set_sse_msg', data);
		if(res && res.data){
			eventBus.$emit('sseBack',res.data);
		}
	} catch (error) {
		console.error('解析SSE数据失败:', error);
	}
}

function onError() {
	// error
	// console.error('SSE连接错误:', error);
	handleDisconnect();
}

// 改进的注册方法
function registerCallback(callback, identifier = 'default') {
	// 清理同名的旧回调
	if (callbacks.has(identifier)) {
		callbacks.delete(identifier);
	}

	callbacks.set(identifier, {
		fn: callback,
		// 存储调用栈信息便于调试
		_debug: new Error().stack.split('\n').slice(1, 4).join('\n')
	});

	return () => {
		callbacks.delete(identifier);
		console.log(`SSE回调 ${identifier} 已取消注册`);
	};
}

function handleDisconnect() {
	if (!isConnected) return;

	isConnected = false;
	// console.log('SSE连接断开，尝试重连...');

	if (!lockReconnect) {
		lockReconnect = true;
		clearTimeout(reconnectTimer);
		reconnectTimer = setTimeout(() => {
			lockReconnect = false;
			// 重连时保留现有回调
			createSSE();
		}, reconnectDelay);
	}
}
function restartSSE(token) {
	closeSSE();
	createSSE(token);
}

function closeSSE() {
	if (eventSource) {
		// 移除所有监听器
		eventSource.onopen = null;
		eventSource.onmessage = null;
		eventSource.onerror = null;

		eventSource.close();
		eventSource = null;
	}
	isConnected = false;
	clearTimeout(reconnectTimer);
	console.log('SSE连接已关闭');
}

// 添加调试方法
function debugCallbacks() {
	callbacks.forEach((value, key) => {
		console.log(`回调标识: ${key}`);
	});
	console.groupEnd();
}

export default {
	connect: createSSE,
	onMessage: registerCallback,
	close: closeSSE,
	restart: restartSSE,
	debug: debugCallbacks,
	get isConnected() {
		return isConnected;
	}
};
