// @ts-nocheck
import { debugLog } from './common';

export const messageMethods = {
    handleSendOrStop() {
        if (this.composerBusy) {
            this.stopTask();
        } else {
            this.sendMessage();
        }
    },

    async sendMessage() {
        if (this.streamingUi) {
            return;
        }
        if (this.mediaUploading) {
            this.uiPushToast({
                title: '上传中',
                message: '请等待图片/视频上传完成后再发送',
                type: 'info'
            });
            return;
        }

        const text = (this.inputMessage || '').trim();
        const images = Array.isArray(this.selectedImages) ? this.selectedImages.slice(0, 9) : [];
        const videos = Array.isArray(this.selectedVideos) ? this.selectedVideos.slice(0, 1) : [];
        const hasText = text.length > 0;
        const hasImages = images.length > 0;
        const hasVideos = videos.length > 0;

        if (!hasText && !hasImages && !hasVideos) {
            return;
        }

        const quotaType = this.thinkingMode ? 'thinking' : 'fast';
        if (this.isQuotaExceeded(quotaType)) {
            this.showQuotaToast({ type: quotaType });
            return;
        }

        if (hasImages && !['qwen3-vl-plus', 'kimi-k2.5'].includes(this.currentModelKey)) {
            this.uiPushToast({
                title: '当前模型不支持图片',
                message: '请切换到 Qwen3.5 或 Kimi-k2.5 再发送图片',
                type: 'error'
            });
            return;
        }

        if (hasVideos && !['qwen3-vl-plus', 'kimi-k2.5'].includes(this.currentModelKey)) {
            this.uiPushToast({
                title: '当前模型不支持视频',
                message: '请切换到 Qwen3.5 或 Kimi-k2.5 后再发送视频',
                type: 'error'
            });
            return;
        }

        if (hasVideos && hasImages) {
            this.uiPushToast({
                title: '请勿同时发送',
                message: '视频与图片需分开发送，每条仅包含一种媒体',
                type: 'warning'
            });
            return;
        }

        if (hasVideos) {
            this.uiPushToast({
                title: '视频处理中',
                message: '读取视频需要较长时间，请耐心等待',
                type: 'info',
                duration: 5000
            });
        }

        const message = text;
        const isCommand = hasText && !hasImages && !hasVideos && message.startsWith('/');
        if (isCommand) {
            if (this.socket && this.isConnected) {
                this.socket.emit('send_command', { command: message });
            }
            this.inputClearMessage();
            this.inputClearSelectedImages();
            this.inputClearSelectedVideos();
            this.autoResizeInput();
            return;
        }

        const wasBlank = this.isConversationBlank();
        if (wasBlank) {
            this.blankHeroExiting = true;
            this.blankHeroActive = true;
            setTimeout(() => {
                this.blankHeroExiting = false;
                this.blankHeroActive = false;
            }, 320);
        }

        // 标记任务进行中，直到任务完成或用户手动停止
        this.taskInProgress = true;
        this.chatAddUserMessage(message, images, videos);

        // 使用 REST API 创建任务（轮询模式）
        try {
            const { useTaskStore } = await import('../../stores/task');
            const taskStore = useTaskStore();

            await taskStore.createTask(message, images, videos, this.currentConversationId);

            debugLog('[Message] 任务已创建，开始轮询');
        } catch (error) {
            console.error('[Message] 创建任务失败:', error);
            this.uiPushToast({
                title: '发送失败',
                message: error.message || '创建任务失败，请重试',
                type: 'error'
            });
            this.taskInProgress = false;
            return;
        }

        if (typeof this.monitorShowPendingReply === 'function') {
            this.monitorShowPendingReply();
        }
        this.inputClearMessage();
        this.inputClearSelectedImages();
        this.inputClearSelectedVideos();
        this.inputSetImagePickerOpen(false);
        this.inputSetVideoPickerOpen(false);
        this.inputSetLineCount(1);
        this.inputSetMultiline(false);
        if (hasImages) {
            this.conversationHasImages = true;
            this.conversationHasVideos = false;
        }
        if (hasVideos) {
            this.conversationHasVideos = true;
            this.conversationHasImages = false;
        }
        if (this.autoScrollEnabled) {
            this.scrollToBottom();
        }
        this.autoResizeInput();

        // 发送消息后延迟更新当前上下文Token（关键修复：恢复原逻辑）
        setTimeout(() => {
            if (this.currentConversationId) {
                this.updateCurrentContextTokens();
            }
        }, 1000);
    },

    // 新增：停止任务方法
    async stopTask() {
        const canStop = this.composerBusy && !this.stopRequested;
        if (!canStop) {
            return;
        }

        const shouldDropToolEvents = this.streamingUi;
        this.stopRequested = true;
        this.dropToolEvents = shouldDropToolEvents;

        // 使用 REST API 取消任务
        try {
            const { useTaskStore } = await import('../../stores/task');
            const taskStore = useTaskStore();

            if (taskStore.currentTaskId) {
                await taskStore.cancelTask();
                debugLog('[Message] 任务已取消');
            }
        } catch (error) {
            console.error('[Message] 取消任务失败:', error);
        }

        // 兼容 WebSocket 模式
        if (this.socket && this.isConnected) {
            this.socket.emit('stop_task');
            debugLog('发送停止请求（WebSocket）');
        }

        // 立即清理前端状态，避免出现"不可输入也不可停止"的卡死状态
        this.clearPendingTools('user_stop');
        this.streamingMessage = false;
        this.taskInProgress = false;
        this.forceUnlockMonitor('user_stop');
    },

    async clearChat() {
        const confirmed = await this.confirmAction({
            title: '清除对话',
            message: '确定要清除所有对话记录吗？该操作不可撤销。',
            confirmText: '清除',
            cancelText: '取消'
        });
        if (confirmed) {
            this.socket.emit('send_command', { command: '/clear' });
        }
    },

    async compressConversation() {
        if (!this.currentConversationId) {
            this.uiPushToast({
                title: '无法压缩',
                message: '当前没有可压缩的对话。',
                type: 'info'
            });
            return;
        }

        if (this.compressing) {
            return;
        }

        const confirmed = await this.confirmAction({
            title: '压缩对话',
            message: '确定要压缩当前对话记录吗？压缩后会生成新的对话副本。',
            confirmText: '压缩',
            cancelText: '取消'
        });
        if (!confirmed) {
            return;
        }

        this.compressing = true;

        try {
            const response = await fetch(`/api/conversations/${this.currentConversationId}/compress`, {
                method: 'POST'
            });

            const result = await response.json();

            if (response.ok && result.success) {
                const newId = result.compressed_conversation_id;
                if (newId) {
                    this.currentConversationId = newId;
                }
                debugLog('对话压缩完成:', result);
            } else {
                const message = result.message || result.error || '压缩失败';
                this.uiPushToast({
                    title: '压缩失败',
                    message,
                    type: 'error'
                });
            }
        } catch (error) {
            console.error('压缩对话异常:', error);
            this.uiPushToast({
                title: '压缩对话异常',
                message: error.message || '请稍后重试',
                type: 'error'
            });
        } finally {
            this.compressing = false;
        }
    },

    sendAutoUserMessage(text) {
        const message = (text || '').trim();
        if (!message || !this.isConnected) {
            return false;
        }
        const quotaType = this.thinkingMode ? 'thinking' : 'fast';
        if (this.isQuotaExceeded(quotaType)) {
            this.showQuotaToast({ type: quotaType });
            return false;
        }
        this.taskInProgress = true;
        this.chatAddUserMessage(message, []);
        if (this.socket) {
            this.socket.emit('send_message', {
                message,
                images: [],
                conversation_id: this.currentConversationId
            });
        }
        if (typeof this.monitorShowPendingReply === 'function') {
            this.monitorShowPendingReply();
        }
        if (this.autoScrollEnabled) {
            this.scrollToBottom();
        }
        this.autoResizeInput();
        setTimeout(() => {
            if (this.currentConversationId) {
                this.updateCurrentContextTokens();
            }
        }, 1000);
        return true;
    },

    autoResizeInput() {
        this.$nextTick(() => {
            const textarea = this.getComposerElement('stadiumInput');
            if (!textarea || !(textarea instanceof HTMLTextAreaElement)) {
                return;
            }
            const previousHeight = textarea.offsetHeight;
            textarea.style.height = 'auto';
            const computedStyle = window.getComputedStyle(textarea);
            const lineHeight = parseFloat(computedStyle.lineHeight || '20') || 20;
            const maxHeight = lineHeight * 6;
            const targetHeight = Math.min(textarea.scrollHeight, maxHeight);
            this.inputSetLineCount(Math.max(1, Math.round(targetHeight / lineHeight)));
            this.inputSetMultiline(targetHeight > lineHeight * 1.4);
            if (Math.abs(targetHeight - previousHeight) <= 0.5) {
                textarea.style.height = `${targetHeight}px`;
                return;
            }
            textarea.style.height = `${previousHeight}px`;
            void textarea.offsetHeight;
            requestAnimationFrame(() => {
                textarea.style.height = `${targetHeight}px`;
            });
        });
    }
};
