const AIReport = (() => { // 添加样式 const addStyles = () => { if (document.getElementById('ai-report-styles')) return; const style = document.createElement('style'); style.id = 'ai-report-styles'; style.textContent = ` @keyframes spin { to { transform: rotate(360deg); } } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } @keyframes aiPulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } } .thinking-content > div:last-child::after { content: ''; position: absolute; right: 8px; top: 50%; transform: translateY(-50%); width: 6px; height: 6px; background: #667eea; border-radius: 50%; animation: pulse 1.5s infinite; } `; document.head.appendChild(style); }; return `
🤖 智能报表
点击生成智能报表
AI将为您分析生产数据并生成洞察
`; }; // 生成报表 const generateReport = async () => { const placeholderEl = document.getElementById('ai-report-placeholder'); const loadingEl = document.getElementById('ai-report-loading'); const resultEl = document.getElementById('ai-report-result'); const thinkingEl = document.getElementById('ai-report-thinking'); const timeEl = document.getElementById('ai-report-time'); // 显示加载状态 if(placeholderEl) placeholderEl.style.display = 'none'; if(loadingEl) loadingEl.style.display = 'flex'; if(resultEl) resultEl.style.display = 'none'; // 显示思考过程容器 if(thinkingEl) thinkingEl.style.display = 'block'; // 模拟思考过程的逐步展示 const showThinkingProcess = () => { const thinkingSteps = [ { title: '数据概览', content: '正在读取最近30天的生产数据...', delay: 500 }, { title: '数据概览', content: '发现总产量数据,正在分析良品率...', delay: 800 }, { title: '规律发现', content: '正在分析平台分布规律...', delay: 1200 }, { title: '规律发现', content: '发现产量趋势,正在计算增长率...', delay: 1600 }, { title: '原因推断', content: '正在分析质量问题和根本原因...', delay: 2000 }, { title: '结论形成', content: '正在生成生产建议和预测...', delay: 2400 }, { title: '结论形成', content: '整合分析结果,准备输出报告...', delay: 2800 } ]; let currentStep = 0; const thinkingContent = thinkingEl.querySelector('.thinking-content') || thinkingEl; const updateThinking = () => { if (currentStep < thinkingSteps.length) { const step = thinkingSteps[currentStep]; const stepHtml = `
${currentStep + 1}. ${step.title}
${step.content}
`; if (currentStep === 0) { thinkingContent.innerHTML = stepHtml; } else { thinkingContent.innerHTML += stepHtml; } currentStep++; setTimeout(updateThinking, step.delay); } }; updateThinking(); }; // 开始展示思考过程 showThinkingProcess(); try { // 调用后端AI分析API const response = await fetch('/api/ai/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const reportData = await response.json(); // 隐藏加载和思考过程 if(loadingEl) loadingEl.style.display = 'none'; if(thinkingEl) thinkingEl.style.display = 'none'; // 渲染报表 renderReport(reportData); // 更新时间 const now = new Date(); timeEl.textContent = `更新于 ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`; } catch (error) { console.error('生成报表失败:', error); // 如果API调用失败,使用模拟数据作为后备 try { console.log('使用模拟数据作为后备...'); const reportData = await analyzeProductionData(); // 隐藏加载和思考过程 if(loadingEl) loadingEl.style.display = 'none'; if(thinkingEl) thinkingEl.style.display = 'none'; renderReport(reportData); const now = new Date(); timeEl.textContent = `更新于 ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')} (模拟)`; } catch (fallbackError) { console.error('模拟数据也失败:', fallbackError); if(loadingEl) loadingEl.style.display = 'none'; if(thinkingEl) thinkingEl.style.display = 'none'; if(resultEl) { resultEl.style.display = 'block'; resultEl.innerHTML = `
😞
生成失败
请检查AI服务配置或稍后重试
`; } } } }; // 模拟AI分析数据 const analyzeProductionData = async () => { // 这里应该调用实际的AI API // 现在返回模拟数据 return { summary: { totalProduction: 15423, goodRate: '98.5%', trend: 'up', insights: [ '本周产量较上周增长12%,主要得益于圆通订单的增加', '良品率保持在98%以上,质量管控效果显著', '建议:继续保持当前生产节奏,关注设备维护' ] }, platforms: { pdd: { count: 8934, percentage: 57.9, trend: '+5.2%' }, yt: { count: 6489, percentage: 42.1, trend: '+18.7%' } }, quality: { topIssues: [ { issue: '外观划痕', count: 23, percentage: '0.15%' }, { issue: '功能异常', count: 12, percentage: '0.08%' }, { issue: '包装破损', count: 8, percentage: '0.05%' } ] }, prediction: { tomorrow: 2250, weekRange: '15500-16500', confidence: '92%' } }; }; // 渲染报表内容 const renderReport = (data) => { const loadingEl = document.getElementById('ai-report-loading'); const resultEl = document.getElementById('ai-report-result'); if(loadingEl) loadingEl.style.display = 'none'; // 格式化思考过程 const formatThinking = (thinking) => { if (!thinking) return ''; // 按步骤分割 const steps = thinking.split(/第[一二三四五]步[::]/).filter(s => s.trim()); const stepTitles = ['数据概览', '规律发现', '原因推断', '结论形成']; let html = ''; steps.forEach((step, index) => { if (step.trim()) { html += `
${index + 1}. ${stepTitles[index] || `步骤${index + 1}`}
${step.trim()}
`; } }); return html; }; const html = `
${data.thinking ? `

🤔 AI思考过程 了解AI如何分析数据

${formatThinking(data.thinking)}
` : ''}

📊 生产总览

总产量
${data.summary.totalProduction.toLocaleString()}
${data.summary.trend === 'up' ? '↑' : '↓'} vs 上周
良品率
${data.summary.goodRate}
稳定

📈 平台分布

拼多多 ${data.platforms.pdd.count.toLocaleString()} (${data.platforms.pdd.percentage}%)
圆通 ${data.platforms.yt.count.toLocaleString()} (${data.platforms.yt.percentage}%)

🔍 质量分析

主要不良项:
${data.quality.topIssues.map(issue => `
${issue.issue} ${issue.count} (${issue.percentage})
`).join('') || '
暂无不良记录
'}

💡 AI洞察

🎯 产量预测

明日预测
${data.prediction.tomorrow.toLocaleString()}
本周范围
${data.prediction.weekRange}
置信度: ${data.prediction.confidence}
`; if(resultEl) { resultEl.innerHTML = html; resultEl.style.display = 'block'; } }; // 导出报表 const exportReport = () => { const content = document.getElementById('ai-report-result'); if (!content || content.style.display === 'none') { alert('请先生成报表'); return; } // 创建导出内容 const text = content.innerText; const blob = new Blob([`智能生产报表\n\n生成时间: ${new Date().toLocaleString()}\n\n${text}`], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `智能报表_${new Date().toISOString().slice(0, 10)}.txt`; a.click(); URL.revokeObjectURL(url); }; // 刷新报表 const refreshReport = () => { generateReport(); }; // 添加CSS动画 const addStyles = () => { if (document.getElementById('ai-report-styles')) return; const style = document.createElement('style'); style.id = 'ai-report-styles'; style.textContent = ` @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .thinking-content > div:last-child { position: relative; } .thinking-content > div:last-child::after { content: ''; position: absolute; right: 8px; top: 50%; transform: translateY(-50%); width: 6px; height: 6px; background: #667eea; border-radius: 50%; animation: pulse 1.5s infinite; } @keyframes aiPulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } } @keyframes spin { to { transform: rotate(360deg); } } .ai-pulse { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4); } `; document.head.appendChild(style); }; // ... // 初始化 const init = () => { addStyles(); }; // 暴露方法 return { init, generateReport, exportReport, refreshReport, generateAICard }; })(); // 初始化 AIReport.init();