import config from '@/config'
const baseUrl = config.baseUrl
import store from '@/store'
class WebSocketManager {
    constructor(userId) {
        // 1用户 2志愿者
        this.system = uni.getStorageSync('userType') === 1 ? '1' : '2';
        this.userId = userId;
        const url = baseUrl.split('/')[2];
        const header = baseUrl.split('/')[0] === 'https:' ? 'wss' : 'ws';
		// console.log("TCL: WebSocketManager -> constructor -> url",header, url)
        this.url = `${header}://${url}/websocket/${this.system}/${this.userId}`;

        this.socketTask = null;
        this.heartbeatInterval = null;
        this.reconnectTimer = null;
        this.isConnecting = false;
        this.onMessageCallback = null;

    }

    /**
     * 建立连接
     */
    connect() {
        if (this.isConnecting || !this.userId) {
            console.warn('正在连接或缺少用户ID');
            return;
        }
         // 如果已有连接，先关闭旧连接
        if (this.isConnected) {
            console.log('已存在连接，正在关闭旧连接...');
            this.socketTask.close();
        }
        this.isConnecting = true;
        console.log('建立 WebSocket 连接:', this.url);
        this.socketTask = uni.connectSocket({
            url: this.url,
            success: () => console.log('WebSocket 连接创建成功'),
        });

        this._setupEventListeners();
    }

    /**
     * 设置事件监听器
     */
    _setupEventListeners() {
        this.socketTask.onOpen(() => {
            console.log('WebSocket 已打开');
            this.isConnecting = false;
            this.startHeartbeat();
        });

        this.socketTask.onMessage(res => {
            console.log('收到 WebSocket 消息:', res.data);
            try {
                const data = JSON.parse(res.data);
				// console.log("TCL: WebSocketManager -> _setupEventListeners -> data", data)
                if (typeof this.onMessageCallback === 'function') {
                    this.onMessageCallback(data); // 回调通知外部
                }
                if (data.type === 'msgUnreadCount') {
					console.log("TCL: WebSocketManager -> _setupEventListeners -> msgUnreadCount", data.data)
                    store.dispatch('handleMessageCount', data.data)
                 }
            } catch (e) {
                console.error('消息解析失败:', res.data);
            }
        });

        this.socketTask.onError(err => {
            console.error('WebSocket 发生错误:', err);
        });

        this.socketTask.onClose(() => {
            console.log('WebSocket 已关闭');
            this.stopHeartbeat();
            this.reconnect(); // 自动重连
        });
    }

    /**
     * 启动心跳机制
     */
    startHeartbeat() {
        // this.stopHeartbeat();
        // this.heartbeatInterval = setInterval(() => {
        //     uni.sendSocketMessage({
        //         data: 'heartbeat',
        //         success: () => console.log('心跳包已发送'),
        //         fail: err => {
        //             console.error('心跳包发送失败:', err);
        //             this.stopHeartbeat();
        //         }
        //     });
        // }, 5000);
    }

    /**
     * 停止心跳机制
     */
    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }

    /**
     * 重新连接
     */
    reconnect() {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = setTimeout(() => {
            console.log('尝试重新连接...');
            this.connect();
        }, 3000);
    }

    /**
     * 主动发送消息
     */
    sendMessage(message) {
        if (this.socketTask && typeof message !== 'undefined') {
            uni.sendSocketMessage({
                data: typeof message === 'object' ? JSON.stringify(message) : message,
                success: () => console.log('消息发送成功:', message),
                fail: err => console.error('消息发送失败:', err)
            });
        } else {
            console.warn('尚未建立连接，消息发送失败');
        }
    }

    /**
     * 主动关闭连接
     */
    closeConnection() {
        console.log('主动关闭连接',this.socketTask);
        
        this.socketTask.close();
        this.socketTask = null;
        // this.stopHeartbeat();
    }

    /**
     * 设置消息回调
     */
    onMessage(callback) {
		// console.log("TCL: WebSocketManager -> onMessage -> callback", callback)
        this.onMessageCallback = callback;
    }
}

export default WebSocketManager;