/**
 * AI助手模块 - 智能婚礼顾问
 * 支持多种AI引擎切换：硅基流动、OpenAI、Gemini、本地模型
 */

let chatMessages = [];
let isLoading = false;

// AI引擎配置
const aiEngines = {
    siliconflow: {
        name: '硅基流动',
        apiUrl: 'api/siliconflow_api.php',
        model: 'deepseek-ai/DeepSeek-V4-Flash'
    },
    doubao: {
        name: '豆包',
        apiUrl: 'api/doubao_api.php',
        model: 'doubao'
    },
    local: {
        name: '本地模型',
        apiUrl: null,
        model: 'knowledge-base'
    }
};

let currentEngine = 'siliconflow';

// 本地知识库
const weddingKnowledgeBase = {
    "如何策划婚礼": "婚礼策划主要包括：确定预算、选择日期、场地预订、婚庆公司选择、四大金刚（司仪、摄影、摄像、化妆）、婚纱礼服准备等步骤。建议提前6-12个月开始筹备。",
    "婚礼预算分配": "合理的婚礼预算分配：婚宴场地40%-50%、婚庆策划15%-20%、四大金刚15%-20%、婚纱礼服10%-15%、其他费用5%-10%。阳泉中等规模婚礼预算约3-8万元。",
    "阳泉婚庆公司": "阳泉本地推荐婚庆公司：阳泉喜洋洋婚庆（老字号）、盛世良缘（创意策划）、花嫁喜事（性价比高）、金玉满堂（高端定制）。",
    "传统婚俗": "阳泉传统婚俗：提亲（男方请媒人）、定亲（交换彩礼）、送日子（选择吉日）、迎娶（迎亲仪式）、拜堂（一拜天地、二拜高堂、夫妻对拜）、闹洞房。",
    "婚礼日期选择": "选择婚礼日期考虑：黄历吉日（避开忌日）、季节因素（春秋季是旺季）、节假日（方便亲友但价格高）、双方生辰（结合八字择日）。",
    "电子请柬制作": "制作电子请柬步骤：登录系统 → 选择模板 → 填写新人信息、日期、地点 → 上传照片 → 预览效果 → 分享给亲友。点击导航栏\"请柬\"即可使用。",
    "婚礼流程": "婚礼当天流程：上午（08:00新娘化妆、10:00迎亲出发、11:00堵门游戏、11:30接亲仪式）；下午（14:00酒店彩排、17:00宾客签到）；晚上（19:00仪式开始、21:00婚宴结束）。",
    "父母致辞": "父母致辞要点：感谢来宾（欢迎亲朋好友）、回顾成长（回忆新人点滴）、表达祝福（期望和祝福）、再次感谢（感谢支持）。时间控制在3-5分钟为宜。",
    "婚纱选择": "选择婚纱技巧：根据身材选款式（A字裙适合大多数人）、考虑婚礼场地（户外选轻便款，室内可选华丽款）、试穿时要走动测试舒适度、预算充足可定制。",
    "伴郎伴娘": "伴郎伴娘职责：协助新人处理婚礼事务、保管物品、引导宾客、活跃气氛。人数通常为双数，与新人关系密切为佳。",
    "婚礼摄影": "婚礼摄影要点：提前沟通拍摄风格、列出必拍镜头清单、准备备用电池和存储卡、安排专门时间拍摄合影、婚礼后及时备份照片。",
    "婚宴菜单": "婚宴菜单搭配：冷盘4-6道、热菜8-12道、汤品1道、主食2道、甜点2道。考虑宾客口味差异，提供素食选择。",
    "婚车安排": "婚车安排：主婚车选豪华车型，跟车数量为双数（6辆或8辆），统一装饰风格，提前规划路线，安排专人负责调度。"
};

function initAI() {
    const chatInput = document.getElementById('chatInput');
    const sendBtn = document.getElementById('sendBtn');
    
    if (!chatInput || !sendBtn) return;
    
    // 引擎切换监听
    document.querySelectorAll('input[name="aiProvider"]').forEach(radio => {
        radio.addEventListener('change', function() {
            currentEngine = this.value;
            showEngineNotification(aiEngines[currentEngine].name);
        });
    });
    
    chatInput.addEventListener('input', function() {
        sendBtn.disabled = !this.value.trim();
    });
    
    chatInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    
    sendBtn.addEventListener('click', sendMessage);
    
    document.getElementById('clearChatBtn').addEventListener('click', clearChat);
    document.getElementById('exportChatBtn').addEventListener('click', exportChat);
    document.getElementById('voiceBtn').addEventListener('click', toggleVoiceInput);
    document.getElementById('suggestBtn').addEventListener('click', showSuggestions);
    
    document.querySelectorAll('.quick-question-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            chatInput.value = this.dataset.question;
            sendBtn.disabled = false;
            sendMessage();
        });
    });
}

function showEngineNotification(engineName) {
    const container = document.getElementById('chatMessages');
    const notification = document.createElement('div');
    notification.className = 'engine-notification';
    notification.innerHTML = `<span>已切换到 <strong>${engineName}</strong> 引擎</span>`;
    container.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 3000);
    
    scrollToBottom();
}

async function sendMessage() {
    const input = document.getElementById('chatInput');
    const message = input.value.trim();
    
    if (!message || isLoading) return;

    addMessage(message, 'user');
    chatMessages.push({ type: 'user', content: message });
    input.value = '';
    document.getElementById('sendBtn').disabled = true;
    
    showLoading();
    
    try {
        const response = await callAIAPI(message);
        addMessage(response, 'ai');
        chatMessages.push({ type: 'ai', content: response });
    } catch (error) {
        console.error('AI请求失败:', error);
        const errMsg = '抱歉，暂时无法回答您的问题，请稍后再试。';
        addMessage(errMsg, 'ai');
        chatMessages.push({ type: 'ai', content: errMsg });
    }
    
    hideLoading();
    scrollToBottom();
}

async function callAIAPI(message) {
    const engine = aiEngines[currentEngine];
    
    // 如果是本地模型，直接使用知识库
    if (currentEngine === 'local' || !engine.apiUrl) {
        const kbAnswer = getKnowledgeBaseAnswer(message);
        if (kbAnswer) {
            return kbAnswer;
        }
        return '感谢您的提问！关于"' + message + '"，我可以为您提供婚礼相关的帮助。';
    }
    
    // 调用远程API
    try {
        const response = await fetch(engine.apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                message: message,
                model: engine.model
            })
        });
        
        const data = await response.json();
        
        if (data.success && data.response) {
            return data.response;
        } else {
            // 回退到本地知识库
            const kbAnswer = getKnowledgeBaseAnswer(message);
            if (kbAnswer) {
                return kbAnswer;
            }
            return '感谢您的提问！关于"' + message + '"，我可以为您提供婚礼相关的帮助。';
        }
    } catch (error) {
        // 网络错误时回退到本地知识库
        const kbAnswer = getKnowledgeBaseAnswer(message);
        if (kbAnswer) {
            return kbAnswer;
        }
        throw error;
    }
}

function getKnowledgeBaseAnswer(question) {
    // 精确匹配
    if (weddingKnowledgeBase[question]) {
        return weddingKnowledgeBase[question];
    }
    
    // 模糊匹配
    for (const [key, answer] of Object.entries(weddingKnowledgeBase)) {
        if (question.includes(key) || key.includes(question)) {
            return answer;
        }
    }
    
    return null;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function addMessage(content, type) {
    const container = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message ' + type + '-message';
    
    const avatar = type === 'ai' ? '🤖' : '👤';
    const avatarClass = type === 'ai' ? 'ai-avatar' : 'user-avatar';
    const safeContent = escapeHtml(content).replace(/\n/g, '<br>');
    
    messageDiv.innerHTML = `
        <div class="message-avatar ${avatarClass}">${avatar}</div>
        <div class="message-content">
            <div class="message-bubble">${safeContent}</div>
            <div class="message-time">${getCurrentTime()}</div>
        </div>
    `;
    
    container.appendChild(messageDiv);
    scrollToBottom();
}

function showLoading() {
    isLoading = true;
    const container = document.getElementById('chatMessages');
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'message ai-message loading-message';
    loadingDiv.innerHTML = `
        <div class="message-avatar ai-avatar">🤖</div>
        <div class="message-content">
            <div class="message-bubble">
                <div class="loading-indicator">
                    <span class="loading-dot"></span>
                    <span class="loading-dot"></span>
                    <span class="loading-dot"></span>
                </div>
            </div>
        </div>
    `;
    container.appendChild(loadingDiv);
}

function hideLoading() {
    isLoading = false;
    const loadingMessage = document.querySelector('.loading-message');
    if (loadingMessage) {
        loadingMessage.remove();
    }
}

function scrollToBottom() {
    setTimeout(function() {
        const container = document.getElementById('chatMessages');
        container.scrollTop = container.scrollHeight;
    }, 100);
}

function getCurrentTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    return hours + ':' + minutes;
}

function clearChat() {
    if (confirm('确定清空聊天记录吗？')) {
        const container = document.getElementById('chatMessages');
        container.innerHTML = `
            <div class="message ai-message">
                <div class="message-avatar ai-avatar">🤖</div>
                <div class="message-content">
                    <div class="message-bubble">
                        <p>您好！我是您的AI婚礼顾问 💒</p>
                        <p>请问有什么可以帮助您的？您可以：</p>
                        <ul>
                            <li>询问婚礼策划相关问题</li>
                            <li>了解阳泉本地婚俗文化</li>
                            <li>获取预算分配建议</li>
                            <li>了解婚礼流程安排</li>
                        </ul>
                    </div>
                    <div class="message-time">刚刚</div>
                </div>
            </div>
        `;
        chatMessages = [];
    }
}

function exportChat() {
    if (chatMessages.length === 0) {
        alert('暂无聊天记录');
        return;
    }
    
    let content = 'AI婚礼顾问 - 聊天记录\n' + '='.repeat(40) + '\n\n';
    
    chatMessages.forEach(function(msg) {
        const prefix = msg.type === 'user' ? '👤 您' : '🤖 AI';
        content += prefix + ': ' + msg.content + '\n\n';
    });
    
    const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ai_chat_' + new Date().toISOString().split('T')[0] + '.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

let currentRecognition = null;

function toggleVoiceInput() {
    const btn = document.getElementById('voiceBtn');
    
    if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
        alert('浏览器不支持语音输入');
        return;
    }
    
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    
    if (btn.classList.contains('recording')) {
        if (currentRecognition) {
            currentRecognition.stop();
            currentRecognition = null;
        }
        btn.classList.remove('recording');
        btn.innerHTML = '<i class="fas fa-microphone"></i>';
    } else {
        const recognition = new SpeechRecognition();
        currentRecognition = recognition;
        recognition.lang = 'zh-CN';
        
        btn.classList.add('recording');
        btn.innerHTML = '<i class="fas fa-microphone-slash"></i>';
        recognition.start();
        
        recognition.onresult = function(event) {
            document.getElementById('chatInput').value = event.results[0][0].transcript;
            document.getElementById('sendBtn').disabled = false;
            btn.classList.remove('recording');
            btn.innerHTML = '<i class="fas fa-microphone"></i>';
            currentRecognition = null;
        };
        
        recognition.onerror = function() {
            btn.classList.remove('recording');
            btn.innerHTML = '<i class="fas fa-microphone"></i>';
            currentRecognition = null;
        };
        
        recognition.onend = function() {
            if (btn.classList.contains('recording')) {
                btn.classList.remove('recording');
                btn.innerHTML = '<i class="fas fa-microphone"></i>';
            }
            currentRecognition = null;
        };
    }
}

function showSuggestions() {
    const suggestions = [
        '如何制定婚礼预算？',
        '阳泉有哪些好的婚庆公司？',
        '婚礼当天流程怎么安排？',
        '父母致辞怎么写？',
        '电子请柬怎么制作？'
    ];
    
    document.getElementById('chatInput').value = suggestions[Math.floor(Math.random() * suggestions.length)];
    document.getElementById('sendBtn').disabled = false;
}
