// 聊天处理模块
import {getCurrentSessionId} from './dom-utils.js';
import {addMessage} from './message.js';
import {
    getConnection,
    setIsLoading,
    setCurrentAssistantMessage,
    setCurrentAssistantRaw,
    getCancelBtn,
    setCancelBtn
} from './connection.js';

export async function sendMessage(messageInput, modelSelect, chatArea, updateInputState) {
    const content = messageInput.value.trim();
    const connection = getConnection();
    const isConnected = connection && connection.state === signalR.HubConnectionState.Connected;

    if (!content || !isConnected) return;

    let selectedModel = 1;
    if (modelSelect) {
        selectedModel = parseInt(modelSelect.value) || 1;
    }

    addMessage(chatArea, 'user', content);
    messageInput.value = '';
    setIsLoading(true);
    updateInputState();

    const responseEl = addMessage(chatArea, 'assistant', '');
    setCurrentAssistantMessage(responseEl);
    setCurrentAssistantRaw('');
    const currentSessionId = getCurrentSessionId();

    const loader = document.createElement('div');
    loader.className = 'loading-dots';
    loader.innerHTML = '<span></span><span></span><span></span>';
    responseEl.appendChild(loader);

    let actionRow = responseEl.querySelector('.message-actions');
    if (!actionRow) {
        actionRow = document.createElement('div');
        actionRow.className = 'message-actions';
        responseEl.appendChild(actionRow);
    }

    const cancelBtn = document.createElement('button');
    cancelBtn.className = 'cancel-btn';
    cancelBtn.title = '取消生成';
    cancelBtn.innerHTML = '<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="6" width="12" height="12" rx="2" ry="2"></rect></svg>';
    cancelBtn.onclick = async () => {
        try {
            const response = await fetch(`/AiChat/CancelMessage?sessionId=${currentSessionId}&connectionId=${connection.connectionId}`, {method: 'POST'});
            if (!response.ok) {
                console.error('❌ 取消请求失败');
            }
        } catch (err) {
            console.error('❌ 取消请求失败:', err);
        }
    };

    actionRow.insertBefore(cancelBtn, actionRow.firstChild);
    responseEl.appendChild(actionRow);
    setCancelBtn(cancelBtn);

    try {
        // noinspection JSCheckFunctionSignatures
        await connection.invoke('SendStreamMessageToChatGpt', content, selectedModel, currentSessionId || '');
        loader.remove();
    } catch (err) {
        console.error('❌ 发送失败:', err);
        setIsLoading(false);
        setCurrentAssistantMessage(null);
        updateInputState();
        loader.remove();
        const currentCancelBtn = getCancelBtn();
        if (currentCancelBtn) {
            currentCancelBtn.remove();
            setCancelBtn(null);
        }
        addMessage(chatArea, 'error', `错误: ${err.message}`);
    }
}

export async function onModelChange(modelSelect, getCurrentSessionId, customAlert) {
    if (!modelSelect) return;
    const newModelValue = modelSelect.value;
    console.log('📝 模型已切换至:', modelSelect.options[modelSelect.selectedIndex].text);
    const sessionId = getCurrentSessionId();

    if (sessionId) {
        try {
            const form = new FormData();
            form.append("sessionId", sessionId);
            form.append("modelType", newModelValue);
            const response = await fetch('/AiChat/UpdateSessionModelType', {
                method: 'PUT',
                body: form
            });
            const result = await response.json();
            if (!result.success) {
                console.error('❌ 更新会话模型类型失败:', result.message);
                await customAlert('❌ 更新会话模型类型失败');
            } else {
                console.log('✅ 已更新会话模型类型:', sessionId, newModelValue);
            }
        } catch (err) {
            console.error('❌ 更新会话模型类型失败:', err);
        }
    }
}

评论加载中...