components.js 17.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
/**
 * UI 组件库
 */

const Components = {
    /**
     * 格式化金额
     */
    formatAmount(value) {
        if (value === null || value === undefined) return '-';
        return ${Number(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    },

    /**
     * 格式化数字
     */
    formatNumber(value, decimals = 2) {
        if (value === null || value === undefined) return '-';
        return Number(value).toLocaleString('zh-CN', { 
            minimumFractionDigits: decimals, 
            maximumFractionDigits: decimals 
        });
    },

    /**
     * 格式化库销比
     */
    formatRatio(value) {
        if (value === null || value === undefined || value === 999) return '-';
        if (value === 0) return '0.00';
        return Number(value).toFixed(2);
    },

    /**
     * 获取配件标签
     * 呆滞:有库存,滚动90天没有销量
     * 低频:无库存,滚动90天有出库,月均销量<1
     * 缺货:无库存,滚动90天有出库,月均销量≥1
     */
    getPartTag(validStorage, avgSales) {
        const storage = Number(validStorage) || 0;
        const sales = Number(avgSales) || 0;
        
        if (storage > 0 && sales === 0) {
            return { type: 'stagnant', text: '呆滞', class: 'tag-stagnant' };
        }
        if (storage <= 0 && sales > 0 && sales < 1) {
            return { type: 'low-freq', text: '低频', class: 'tag-low-freq' };
        }
        if (storage <= 0 && sales >= 1) {
            return { type: 'shortage', text: '缺货', class: 'tag-shortage' };
        }
        return null;
    },

    /**
     * 渲染配件标签HTML
     */
    renderPartTag(validStorage, avgSales) {
        const tag = this.getPartTag(validStorage, avgSales);
        if (!tag) return '';
        return `<span class="part-tag ${tag.class}">${tag.text}</span>`;
    },

    /**
     * 获取步骤名称显示
     */
    getStepNameDisplay(stepName) {
        const stepMap = {
            'fetch_part_ratio': '获取配件数据',
            'sql_agent': 'AI分析建议',
            'allocate_budget': '分配预算',
            'generate_report': '生成报告',
        };
        return stepMap[stepName] || stepName;
    },

    /**
     * 获取日志状态徽章
     */
    getLogStatusBadge(status) {
        const statusMap = {
            0: { class: 'badge-info', text: '运行中' },
            1: { class: 'badge-success', text: '成功' },
            2: { class: 'badge-danger', text: '失败' },
            3: { class: 'badge-warning', text: '跳过' },
        };
        const config = statusMap[status] || { class: 'badge-neutral', text: '未知' };
        return `<span class="badge ${config.class}"><span class="badge-dot"></span>${config.text}</span>`;
    },

    /**
     * 格式化时长
     */
    formatDuration(seconds) {
        if (!seconds) return '-';
        seconds = Math.floor(seconds);
        if (seconds < 60) return `${seconds}秒`;
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${minutes}${secs}秒`;
    },

    /**
     * 获取状态徽章 HTML
     */
    getStatusBadge(status, statusText) {
        const statusMap = {
            0: { class: 'badge-info', icon: 'loader-2', text: statusText || '运行中' },
            1: { class: 'badge-success', icon: 'check-circle', text: statusText || '成功' },
            2: { class: 'badge-danger', icon: 'x-circle', text: statusText || '失败' },
        };
        const config = statusMap[status] || statusMap[0];
        return `
            <span class="badge ${config.class}">
                <span class="badge-dot"></span>
                ${config.text}
            </span>
        `;
    },

    /**
     * 获取优先级徽章 HTML
     */
    getPriorityBadge(priority) {
        const priorityMap = {
            1: { class: 'priority-high', text: '高' },
            2: { class: 'priority-medium', text: '中' },
            3: { class: 'priority-low', text: '低' },
        };
        const config = priorityMap[priority] || priorityMap[2];
        return `<span class="priority-badge ${config.class}">${config.text}</span>`;
    },

    /**
     * 获取库销比指示器 HTML
     */
    getRatioIndicator(current, base) {
        if (current === null || current === undefined || current === 999) {
            return '<span class="text-muted">-</span>';
        }
        
        const percentage = Math.min((current / (base || 1.5)) * 100, 100);
        let className = 'ratio-normal';
        if (current < 0.5) className = 'ratio-low';
        else if (current > 2) className = 'ratio-high';
        
        return `
            <div class="ratio-indicator ${className}">
                <span>${this.formatRatio(current)}</span>
                <div class="ratio-bar">
                    <div class="ratio-bar-fill" style="width: ${percentage}%"></div>
                </div>
            </div>
        `;
    },

    /**
     * 渲染分页控件
     */
    renderPagination(current, total, pageSize, onChange) {
        const totalPages = Math.ceil(total / pageSize);
        const start = (current - 1) * pageSize + 1;
        const end = Math.min(current * pageSize, total);

        return `
            <div class="pagination">
                <div class="pagination-info">
                    显示 ${start}-${end} 条,共 ${total} 
                </div>
                <div class="pagination-controls">
                    <button class="pagination-btn" ${current <= 1 ? 'disabled' : ''} data-page="${current - 1}">
                        <i data-lucide="chevron-left"></i>
                    </button>
                    ${this.getPaginationNumbers(current, totalPages)}
                    <button class="pagination-btn" ${current >= totalPages ? 'disabled' : ''} data-page="${current + 1}">
                        <i data-lucide="chevron-right"></i>
                    </button>
                </div>
            </div>
        `;
    },

    /**
     * 获取分页数字
     */
    getPaginationNumbers(current, total) {
        const pages = [];
        const maxVisible = 5;
        
        let start = Math.max(1, current - Math.floor(maxVisible / 2));
        let end = Math.min(total, start + maxVisible - 1);
        start = Math.max(1, end - maxVisible + 1);
        
        for (let i = start; i <= end; i++) {
            pages.push(`
                <button class="pagination-btn ${i === current ? 'active' : ''}" data-page="${i}">
                    ${i}
                </button>
            `);
        }
        
        return pages.join('');
    },

    /**
     * 渲染统计卡片
     */
    renderStatCard(icon, label, value, iconClass = 'primary', change = null) {
        let changeHtml = '';
        if (change !== null) {
            const changeClass = change >= 0 ? 'positive' : 'negative';
            const changeIcon = change >= 0 ? 'trending-up' : 'trending-down';
            changeHtml = `
                <div class="stat-change ${changeClass}">
                    <i data-lucide="${changeIcon}"></i>
                    ${Math.abs(change)}%
                </div>
            `;
        }

        return `
            <div class="stat-card">
                <div class="stat-icon ${iconClass}">
                    <i data-lucide="${icon}"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-label">${label}</div>
                    <div class="stat-value">${value}</div>
                    ${changeHtml}
                </div>
            </div>
        `;
    },

    /**
     * 渲染空状态
     */
    renderEmptyState(icon = 'inbox', title = '暂无数据', description = '') {
        return `
            <div class="empty-state">
                <i data-lucide="${icon}"></i>
                <div class="empty-state-title">${title}</div>
                ${description ? `<div class="empty-state-description">${description}</div>` : ''}
            </div>
        `;
    },

    /**
     * 渲染信息列表项
     */
    renderInfoItem(label, value) {
        return `
            <div class="info-item">
                <span class="info-label">${label}</span>
                <span class="info-value">${value || '-'}</span>
            </div>
        `;
    },

    /**
     * 渲染 Markdown 内容
     */
    renderMarkdown(content) {
        if (!content) return '';
        if (typeof marked !== 'undefined') {
            let html = marked.parse(content);
            html = html.replace(/<pre>\s*<code[^>]*>[\s\\n]*<\/code>\s*<\/pre>/gi, '');
            html = html.replace(/<pre>[\s\\n]*<\/pre>/gi, '');
            html = html.replace(/<pre>\s*<code[^>]*>\n<\/code>\s*<\/pre>/gi, '');
            return `<div class="markdown-content">${html}</div>`;
        }
        return `<div class="markdown-content"><pre>${content}</pre></div>`;
    },

    /**
     * 渲染结构化报告 Section
     */
    renderReportSection(section) {
        if (!section) return '';
        
        const iconMap = {
            'executive_summary': { icon: 'file-text', class: 'summary' },
            'inventory_analysis': { icon: 'bar-chart-2', class: 'analysis' },
            'risk_assessment': { icon: 'alert-triangle', class: 'risk' },
            'purchase_recommendations': { icon: 'shopping-cart', class: 'recommendation' },
            'optimization_suggestions': { icon: 'lightbulb', class: 'optimization' },
        };
        
        const config = iconMap[section.type] || { icon: 'file', class: 'summary' };
        
        let contentHtml = '';
        
        switch (section.type) {
            case 'executive_summary':
                contentHtml = this.renderSummarySection(section);
                break;
            case 'inventory_analysis':
                contentHtml = this.renderAnalysisSection(section);
                break;
            case 'risk_assessment':
                contentHtml = this.renderRiskSection(section);
                break;
            case 'purchase_recommendations':
                contentHtml = this.renderRecommendationSection(section);
                break;
            case 'optimization_suggestions':
                contentHtml = this.renderSuggestionSection(section);
                break;
            default:
                contentHtml = `<div class="summary-text">${JSON.stringify(section)}</div>`;
        }
        
        return `
            <div class="card">
                <div class="report-section-header">
                    <div class="report-section-icon ${config.class}">
                        <i data-lucide="${config.icon}"></i>
                    </div>
                    <div class="report-section-title">${section.title || ''}</div>
                </div>
                <div class="report-section-content">
                    ${contentHtml}
                </div>
            </div>
        `;
    },

    /**
     * 渲染执行摘要
     */
    renderSummarySection(section) {
        const items = section.items || [];
        const text = section.text || '';
        
        const itemsHtml = items.length > 0 ? `
            <div class="summary-items">
                ${items.map(item => `
                    <div class="summary-item status-${item.status || 'normal'}">
                        <div class="summary-item-label">${item.label || ''}</div>
                        <div class="summary-item-value">${item.value || ''}</div>
                    </div>
                `).join('')}
            </div>
        ` : '';
        
        const textHtml = text ? `<div class="summary-text">${text}</div>` : '';
        
        return itemsHtml + textHtml;
    },

    /**
     * 渲染库存分析
     */
    renderAnalysisSection(section) {
        const paragraphs = section.paragraphs || [];
        const highlights = section.highlights || [];
        
        const highlightsHtml = highlights.length > 0 ? `
            <div class="analysis-highlights">
                ${highlights.map(h => `
                    <div class="analysis-highlight-card">
                        <span class="highlight-label">${h.label || ''}</span>
                        <span class="highlight-value">${h.value || ''}</span>
                    </div>
                `).join('')}
            </div>
        ` : '';
        
        const paragraphsHtml = paragraphs.length > 0 ? `
            <div class="analysis-paragraphs">
                ${paragraphs.map(p => `
                    <div class="analysis-paragraph">
                        ${p}
                    </div>
                `).join('')}
            </div>
        ` : '';
        
        // Put highlights first for better visibility
        return highlightsHtml + paragraphsHtml;
    },

    /**
     * 渲染风险评估
     */
    renderRiskSection(section) {
        const risks = section.risks || [];
        
        if (risks.length === 0) {
            return '<div class="summary-text">暂无风险评估</div>';
        }
        
        const levelText = { high: '高', medium: '中', low: '低' };
        
        // 按风险等级排序:high > medium > low
        const sortOrder = { high: 0, medium: 1, low: 2 };
        const sortedRisks = [...risks].sort((a, b) => {
            const orderA = sortOrder[a.level] || 99;
            const orderB = sortOrder[b.level] || 99;
            return orderA - orderB;
        });
        
        return `
            <div class="risk-grid">
                ${sortedRisks.map(risk => `
                    <div class="risk-card level-${risk.level || 'medium'}">
                        <div class="risk-card-header">
                            <span class="risk-badge ${risk.level || 'medium'}">${levelText[risk.level] || '中'}风险</span>
                            <span class="risk-category-tag">${risk.category || '通用'}</span>
                        </div>
                        <div class="risk-card-content">
                            <div class="risk-description">${risk.description || ''}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    },

    /**
     * 渲染采购建议
     */
    renderRecommendationSection(section) {
        const recommendations = section.recommendations || [];
        
        if (recommendations.length === 0) {
            return '<div class="summary-text">暂无采购建议</div>';
        }
        
        return `
            <div class="recommendation-list">
                ${recommendations.map(rec => `
                    <div class="recommendation-item">
                        <div class="recommendation-priority priority-${rec.priority || 3}">${rec.priority || 3}</div>
                        <div class="recommendation-content">
                            <div class="recommendation-action">${rec.action || ''}</div>
                            <div class="recommendation-reason">${rec.reason || ''}</div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    },

    /**
     * 渲染优化建议
     */
    renderSuggestionSection(section) {
        const suggestions = section.suggestions || [];
        
        if (suggestions.length === 0) {
            return '<div class="summary-text">暂无优化建议</div>';
        }
        
        return `
            <div class="suggestion-list">
                ${suggestions.map(s => `
                    <div class="suggestion-item">
                        <div class="suggestion-icon"><i data-lucide="check-circle"></i></div>
                        <div class="suggestion-text">${s}</div>
                    </div>
                `).join('')}
            </div>
        `;
    },

    /**
     * 显示 Toast 通知
     */
    showToast(message, type = 'info') {
        const container = document.getElementById('toast-container');
        const icons = {
            success: 'check-circle',
            error: 'x-circle',
            warning: 'alert-triangle',
            info: 'info',
        };

        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.innerHTML = `
            <i data-lucide="${icons[type]}" class="toast-icon"></i>
            <span class="toast-message">${message}</span>
        `;

        container.appendChild(toast);
        lucide.createIcons({ icons: { [icons[type]]: lucide.icons[icons[type]] }, attrs: {} });

        setTimeout(() => {
            toast.style.animation = 'slideIn 0.25s ease reverse';
            setTimeout(() => toast.remove(), 250);
        }, 3000);
    },

    /**
     * 显示加载遮罩
     */
    showLoading() {
        document.getElementById('loading-overlay').classList.add('active');
    },

    /**
     * 隐藏加载遮罩
     */
    hideLoading() {
        document.getElementById('loading-overlay').classList.remove('active');
    },

    /**
     * 显示模态框
     */
    showModal(title, content) {
        document.getElementById('modal-title').textContent = title;
        document.getElementById('modal-body').innerHTML = content;
        document.getElementById('modal-overlay').classList.add('active');
        lucide.createIcons();
    },

    /**
     * 关闭模态框
     */
    closeModal() {
        document.getElementById('modal-overlay').classList.remove('active');
    },
};

// 导出到全局
window.Components = Components;