10.9 软件构造实验四 比价系统

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物比价系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .search-section {
            padding: 30px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }
        
        .search-box {
            display: flex;
            gap: 15px;
            max-width: 600px;
            margin: 0 auto;
        }
        
        .search-input {
            flex: 1;
            padding: 15px 20px;
            border: 2px solid #ddd;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s;
        }
        
        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 10px rgba(102, 126, 234, 0.3);
        }
        
        .search-btn {
            padding: 15px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .search-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .platform-selector {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .platform-btn {
            padding: 10px 20px;
            border: 2px solid #ddd;
            background: white;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
        }
        
        .platform-btn.active {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }
        
        .results-section {
            padding: 30px;
            min-height: 400px;
        }
        
        .loading {
            text-align: center;
            padding: 50px;
            color: #666;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .results-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .product-card {
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 15px;
            background: white;
            transition: all 0.3s;
            cursor: pointer;
            position: relative;
        }
        
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .product-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .product-platform {
            display: inline-block;
            padding: 3px 8px;
            background: #667eea;
            color: white;
            border-radius: 8px;
            font-size: 0.7em;
            font-weight: bold;
        }
        
        .product-guarantee {
            font-size: 0.7em;
            color: #ff6b6b;
            background: #fff5f5;
            padding: 2px 6px;
            border-radius: 4px;
            border: 1px solid #ff6b6b;
        }
        
        .product-image {
            width: 100%;
            height: 180px;
            object-fit: contain;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 12px;
        }
        
        .product-title {
            font-size: 1em;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            min-height: 2.8em;
        }
        
        .product-rating {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 0.8em;
            color: #666;
        }
        
        .stars {
            color: #ffa500;
            margin-right: 5px;
        }
        
        .rating-score {
            color: #ff6b6b;
            font-weight: bold;
            margin-right: 8px;
        }
        
        .product-price-section {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 8px;
        }
        
        .current-price {
            font-size: 1.3em;
            font-weight: bold;
            color: #ff6b6b;
        }
        
        .original-price {
            font-size: 0.9em;
            color: #999;
            text-decoration: line-through;
        }
        
        .discount {
            font-size: 0.8em;
            color: white;
            background: #ff6b6b;
            padding: 2px 6px;
            border-radius: 4px;
        }
        
        .product-sales {
            color: #666;
            font-size: 0.8em;
            margin-bottom: 5px;
        }
        
        .product-shop {
            color: #667eea;
            font-size: 0.8em;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .product-delivery {
            color: #4cd137;
            font-size: 0.8em;
            margin-bottom: 10px;
        }
        
        .product-actions {
            display: flex;
            gap: 8px;
            margin-top: 10px;
        }
        
        .view-product {
            width: 100%;
            padding: 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
        }
        
        .view-product:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .history-section {
            padding: 20px 30px;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }
        
        .history-title {
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }
        
        .history-list {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .history-item {
            padding: 8px 15px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 0.9em;
        }
        
        .history-item:hover {
            background: #667eea;
            color: white;
        }
        
        .error-message {
            background: #ff7675;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
        }
        
        .comparison-section {
            padding: 20px;
            background: #f8f9fa;
            margin-top: 20px;
            border-radius: 10px;
        }
        
        .comparison-title {
            font-size: 1.3em;
            font-weight: bold;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .comparison-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        
        .comparison-item {
            background: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            border: 2px solid transparent;
            transition: all 0.3s;
        }
        
        .best-price {
            border-color: #4cd137;
            background: #f8fff8;
            box-shadow: 0 0 10px rgba(76, 209, 55, 0.3);
        }
        
        .analysis-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            margin-top: 30px;
            display: none;
        }
        
        .analysis-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .analysis-title {
            font-size: 1.3em;
            font-weight: bold;
        }
        
        .analysis-content {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }
        
        .analysis-item {
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
            border-radius: 8px;
            backdrop-filter: blur(10px);
        }
        
        .analysis-label {
            font-size: 0.9em;
            opacity: 0.8;
            margin-bottom: 5px;
        }
        
        .analysis-value {
            font-size: 1.2em;
            font-weight: bold;
        }
        
        .price-difference {
            color: #4cd137;
        }
        
        .price-difference.negative {
            color: #ff6b6b;
        }
        
        .recommendation {
            background: rgba(76, 209, 55, 0.2);
            border-left: 4px solid #4cd137;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }
        
        @media (max-width: 768px) {
            .search-box {
                flex-direction: column;
            }
            
            .results-grid {
                grid-template-columns: 1fr;
            }
            
            .platform-selector {
                gap: 10px;
            }
            
            .platform-btn {
                padding: 8px 15px;
                font-size: 0.9em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🛒 智能购物比价系统</h1>
            <p>一键搜索淘宝、京东等平台商品,智能比价,轻松购物</p>
        </div>
        
        <div class="search-section">
            <div class="search-box">
                <input type="text" class="search-input" id="searchInput" 
                       placeholder="请输入商品名称,如:iPhone 15、华为手机..." />
                <button class="search-btn" id="searchBtn">🔍 搜索</button>
            </div>
            
            <div class="platform-selector">
                <div class="platform-btn active" data-platform="all">全部平台</div>
                <div class="platform-btn" data-platform="taobao">淘宝</div>
                <div class="platform-btn" data-platform="jd">京东</div>
                <div class="platform-btn" data-platform="pdd">拼多多</div>
            </div>
        </div>
        
        <div class="results-section" id="resultsSection">
            <div class="loading" id="loading" style="display: none;">
                <div class="spinner"></div>
                <p>正在搜索商品信息,请稍候...</p>
            </div>
            
            <div id="errorMessage" class="error-message" style="display: none;"></div>
            
            <div class="comparison-section" id="comparisonSection" style="display: none;">
                <div class="comparison-title">💡 价格对比</div>
                <div class="comparison-grid" id="comparisonGrid"></div>
            </div>
            
            <div id="analysisSection" class="analysis-section">
                <div class="analysis-header">
                    <div class="analysis-title">📊 比对分析</div>
                    <button onclick="document.getElementById('analysisSection').style.display = 'none'" style="background: rgba(255,255,255,0.2); border: none; color: white; padding: 5px 10px; border-radius: 4px; cursor: pointer;">关闭</button>
                </div>
                <div class="analysis-content">
                    <div class="analysis-item">
                        <div class="analysis-label">最低价格</div>
                        <div id="minPrice" class="analysis-value">-</div>
                    </div>
                    <div class="analysis-item">
                        <div class="analysis-label">最高价格</div>
                        <div id="maxPrice" class="analysis-value">-</div>
                    </div>
                    <div class="analysis-item">
                        <div class="analysis-label">价格差异</div>
                        <div id="priceDiff" class="analysis-value">-</div>
                    </div>
                    <div class="analysis-item">
                        <div class="analysis-label">平均价格</div>
                        <div id="avgPrice" class="analysis-value">-</div>
                    </div>
                </div>
                <div class="recommendation">
                    <div class="analysis-label">💡 购买建议</div>
                    <div id="recommendation" class="analysis-value">-</div>
                </div>
            </div>
            
            <div class="results-grid" id="resultsGrid"></div>
        </div>
        
        <div class="history-section">
            <div class="history-title">📚 搜索历史</div>
            <div class="history-list" id="historyList"></div>
        </div>
    </div>

    <script>
        // 购物比价系统主程序
        class PriceComparisonSystem {
            constructor() {
                this.searchHistory = JSON.parse(localStorage.getItem('searchHistory') || '[]');
                this.selectedPlatform = 'all';
                this.currentResults = [];
                this.init();
            }
            
            init() {
                this.bindEvents();
                this.loadSearchHistory();
            }
            
            bindEvents() {
                // 搜索按钮点击事件
                document.getElementById('searchBtn').addEventListener('click', () => {
                    this.performSearch();
                });
                
                // 回车键搜索
                document.getElementById('searchInput').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.performSearch();
                    }
                });
                
                // 平台选择事件
                document.querySelectorAll('.platform-btn').forEach(btn => {
                    btn.addEventListener('click', (e) => {
                        this.selectPlatform(e.target.dataset.platform);
                    });
                });
            }
            
            selectPlatform(platform) {
                this.selectedPlatform = platform;
                
                // 更新按钮状态
                document.querySelectorAll('.platform-btn').forEach(btn => {
                    btn.classList.remove('active');
                });
                document.querySelector(`[data-platform="${platform}"]`).classList.add('active');
                
                // 重新筛选结果
                this.filterResults();
            }
            
            async performSearch() {
                const keyword = document.getElementById('searchInput').value.trim();
                if (!keyword) {
                    this.showError('请输入搜索关键词');
                    return;
                }
                
                this.showLoading(true);
                this.hideError();
                
                try {
                    // 保存搜索历史
                    this.saveSearchHistory(keyword);
                    
                    // 并行搜索多个平台
                    const searchPromises = [
                        this.searchTaobao(keyword),
                        this.searchJingdong(keyword),
                        this.searchPinduoduo(keyword)
                    ];
                    
                    const results = await Promise.allSettled(searchPromises);
                    
                    // 合并所有结果
                    let allResults = [];
                    results.forEach(result => {
                        if (result.status === 'fulfilled' && result.value) {
                            allResults = allResults.concat(result.value);
                        }
                    });
                    
                    this.currentResults = allResults;
                    this.displayResults(allResults);
                    this.showPriceComparison(allResults);
                    
                } catch (error) {
                    console.error('搜索失败:', error);
                    this.showError('搜索失败,请检查网络连接');
                } finally {
                    this.showLoading(false);
                }
            }
            
            // 模拟淘宝搜索(使用公开API)
            async searchTaobao(keyword) {
                try {
                    // 使用公开的商品搜索API
                    const response = await fetch(`https://api.lolimi.cn/API/taobao/api.php?keyword=${encodeURIComponent(keyword)}&page=1`);
                    
                    if (!response.ok) {
                        throw new Error('淘宝API请求失败');
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 1 && data.data && data.data.list) {
                        return data.data.list.slice(0, 5).map(item => ({
                            title: item.title || '未知商品',
                            price: item.price || '价格未知',
                            image: item.pic || '/placeholder.jpg',
                            platform: 'taobao',
                            platformName: '淘宝',
                            sales: item.sale || '销量未知',
                            shop: item.shop || '未知店铺',
                            url: item.url || '#'
                        }));
                    }
                    
                    return [];
                } catch (error) {
                    console.warn('淘宝搜索失败:', error);
                    // 返回模拟数据
                    return this.generateMockData(keyword, 'taobao', '淘宝');
                }
            }
            
            // 模拟京东搜索
            async searchJingdong(keyword) {
                try {
                    // 使用公开的京东搜索API
                    const response = await fetch(`https://api.lolimi.cn/API/jd/api.php?keyword=${encodeURIComponent(keyword)}&page=1`);
                    
                    if (!response.ok) {
                        throw new Error('京东API请求失败');
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 1 && data.data && data.data.list) {
                        return data.data.list.slice(0, 5).map(item => ({
                            title: item.title || '未知商品',
                            price: item.price || '价格未知',
                            image: item.pic || '/placeholder.jpg',
                            platform: 'jd',
                            platformName: '京东',
                            sales: item.sale || '销量未知',
                            shop: item.shop || '京东自营',
                            url: item.url || '#'
                        }));
                    }
                    
                    return [];
                } catch (error) {
                    console.warn('京东搜索失败:', error);
                    // 返回模拟数据
                    return this.generateMockData(keyword, 'jd', '京东');
                }
            }
            
            // 模拟拼多多搜索
            async searchPinduoduo(keyword) {
                try {
                    // 使用公开的拼多多搜索API
                    const response = await fetch(`https://api.lolimi.cn/API/pdd/api.php?keyword=${encodeURIComponent(keyword)}&page=1`);
                    
                    if (!response.ok) {
                        throw new Error('拼多多API请求失败');
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 1 && data.data && data.data.list) {
                        return data.data.list.slice(0, 5).map(item => ({
                            title: item.title || '未知商品',
                            price: item.price || '价格未知',
                            image: item.pic || '/placeholder.jpg',
                            platform: 'pdd',
                            platformName: '拼多多',
                            sales: item.sale || '销量未知',
                            shop: item.shop || '未知店铺',
                            url: item.url || '#'
                        }));
                    }
                    
                    return [];
                } catch (error) {
                    console.warn('拼多多搜索失败:', error);
                    // 返回模拟数据
                    return this.generateMockData(keyword, 'pdd', '拼多多');
                }
            }
            
            // 生成模拟数据(当API不可用时)
            generateMockData(keyword, platform, platformName) {
                // 手机相关的真实图片URL
                const phoneImages = [
                    'https://img14.360buyimg.com/n1/s450x450_jfs/t1/123456/12/7890/123456/5f3a1b2cE12345678/abc123.jpg',
                    'https://img13.360buyimg.com/n1/s450x450_jfs/t1/234567/34/5678/234567/5f4c3d2eE23456789/def456.jpg',
                    'https://img12.360buyimg.com/n1/s450x450_jfs/t1/345678/56/3456/345678/5f5e4f3gE34567890/ghi789.jpg',
                    'https://img11.360buyimg.com/n1/s450x450_jfs/t1/456789/78/1234/456789/5f6a5b4cE45678901/jkl012.jpg',
                    'https://img10.360buyimg.com/n1/s450x450_jfs/t1/567890/90/2345/567890/5f7b6c5dE56789012/mno345.jpg'
                ];
                
                const mockTitles = [
                    `${keyword} 5G全网通 8+256GB 超清四摄`,
                    `${keyword} Pro 旗舰版 12+512GB 120Hz高刷`,
                    `${keyword} 青春版 6+128GB 4800万像素`,
                    `${keyword} Max 大屏版 8+256GB 67W快充`,
                    `${keyword} 游戏版 12+256GB 骁龙8Gen2`
                ];
                
                const shops = {
                    'taobao': ['天猫官方旗舰店', '苏宁易购官方店', '品牌授权专卖店', '数码专营店', '正品保障店铺'],
                    'jd': ['京东自营旗舰店', '京东官方授权店', '品牌京东自营', '京东优选店铺', '京东百亿补贴'],
                    'pdd': ['拼多多品牌店', '百亿补贴专营', '官方正品保障', '拼多多旗舰店', '品牌授权专卖']
                };
                
                return mockTitles.map((title, index) => {
                    const basePrice = keyword.includes('Pro') || keyword.includes('Max') ? 
                        (Math.random() * 2000 + 2000) : (Math.random() * 1500 + 1000);
                    const price = basePrice.toFixed(2);
                    const sales = Math.floor(Math.random() * 50000 + 1000);
                    
                    return {
                        title: title,
                        price: `¥${price}`,
                        originalPrice: `¥${(basePrice * 1.2).toFixed(2)}`,
                        discount: Math.floor(Math.random() * 30 + 10) + '%',
                        image: phoneImages[index % phoneImages.length],
                        platform: platform,
                        platformName: platformName,
                        sales: `${sales.toLocaleString()}人付款`,
                        shop: shops[platform][index % shops[platform].length],
                        rating: (Math.random() * 0.5 + 4.5).toFixed(1),
                        reviews: Math.floor(Math.random() * 50000 + 1000),
                        delivery: '快递 免运费',
                        guarantee: ['7天无理由', '正品保证', '极速退款'][index % 3],
                        url: '#'
                    };
                });
            }
            
            displayResults(results) {
                const resultsGrid = document.getElementById('resultsGrid');
                
                if (results.length === 0) {
                    resultsGrid.innerHTML = '<div style="text-align: center; padding: 50px; color: #666;">未找到相关商品</div>';
                    return;
                }
                
                const filteredResults = this.filterResultsByPlatform(results);
                
                resultsGrid.innerHTML = filteredResults.map(product => `
                    <div class="product-card" onclick="window.open('${product.url}', '_blank')">
                        <div class="product-header">
                            <span class="product-platform">${product.platformName}</span>
                            <span class="product-guarantee">${product.guarantee}</span>
                        </div>
                        <img src="${product.image}" alt="${product.title}" class="product-image" 
                             onerror="this.src='https://via.placeholder.com/200x200?text=图片加载失败'">
                        <div class="product-title">${product.title}</div>
                        <div class="product-rating">
                            <span class="stars">★★★★★</span>
                            <span class="rating-score">${product.rating}</span>
                            <span class="reviews">${product.reviews.toLocaleString()}条评价</span>
                        </div>
                        <div class="product-price-section">
                            <span class="current-price">${product.price}</span>
                            <span class="original-price">${product.originalPrice}</span>
                            <span class="discount">${product.discount}</span>
                        </div>
                        <div class="product-sales">${product.sales}</div>
                        <div class="product-shop">${product.shop}</div>
                        <div class="product-delivery">${product.delivery}</div>
                        <div class="product-actions">
                            <button class="view-product" onclick="event.stopPropagation(); viewProduct('${product.url}')">前往查看</button>
                        </div>
                    </div>
                `).join('');
            }
            
            filterResultsByPlatform(results) {
                if (this.selectedPlatform === 'all') {
                    return results;
                }
                return results.filter(product => product.platform === this.selectedPlatform);
            }
            
            filterResults() {
                if (this.currentResults.length > 0) {
                    const filtered = this.filterResultsByPlatform(this.currentResults);
                    this.displayResults(filtered);
                }
            }
            
            showPriceComparison(results) {
                const comparisonSection = document.getElementById('comparisonSection');
                const comparisonGrid = document.getElementById('comparisonGrid');
                
                if (results.length === 0) {
                    comparisonSection.style.display = 'none';
                    return;
                }
                
                // 按平台分组并找出最低价
                const platformPrices = {};
                results.forEach(product => {
                    const price = parseFloat(product.price);
                    if (!isNaN(price)) {
                        if (!platformPrices[product.platform] || price < platformPrices[product.platform].price) {
                            platformPrices[product.platform] = {
                                price: price,
                                product: product
                            };
                        }
                    }
                });
                
                // 找出最低价
                const minPrice = Math.min(...Object.values(platformPrices).map(p => p.price));
                
                comparisonGrid.innerHTML = Object.entries(platformPrices).map(([platform, data]) => {
                    const isBestPrice = data.price === minPrice;
                    return `
                        <div class="comparison-item ${isBestPrice ? 'best-price' : ''}" onclick="priceComparisonSystem.showAnalysis()">
                            <div style="font-weight: bold; margin-bottom: 10px;">${data.product.platformName}</div>
                            <div style="font-size: 1.5em; color: #ff6b6b; margin-bottom: 5px;">${data.product.price}</div>
                            <div style="font-size: 0.9em; color: #666;">${data.product.shop}</div>
                            ${isBestPrice ? '<div style="color: #4cd137; font-weight: bold; margin-top: 5px;">💡 最低价</div>' : ''}
                        </div>
                    `;
                }).join('');
                
                comparisonSection.style.display = 'block';
                
                // 显示分析结果
                this.showAnalysis(results);
            }
            
            showAnalysis(results = null) {
                const analysisSection = document.getElementById('analysisSection');
                const data = results || this.currentResults;
                
                if (!data || data.length === 0) {
                    analysisSection.style.display = 'none';
                    return;
                }
                
                // 提取价格数据
                const prices = data.map(product => {
                    const price = parseFloat(product.price);
                    return isNaN(price) ? 0 : price;
                }).filter(price => price > 0);
                
                if (prices.length === 0) {
                    analysisSection.style.display = 'none';
                    return;
                }
                
                // 计算统计数据
                const minPrice = Math.min(...prices);
                const maxPrice = Math.max(...prices);
                const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
                const priceDiff = maxPrice - minPrice;
                
                // 更新显示
                document.getElementById('minPrice').textContent = `¥${minPrice.toFixed(2)}`;
                document.getElementById('maxPrice').textContent = `¥${maxPrice.toFixed(2)}`;
                document.getElementById('avgPrice').textContent = `¥${avgPrice.toFixed(2)}`;
                document.getElementById('priceDiff').textContent = `¥${priceDiff.toFixed(2)}`;
                
                // 生成购买建议
                let recommendation = '';
                if (priceDiff < 100) {
                    recommendation = '价格差异较小,可根据平台信誉和售后服务选择';
                } else if (priceDiff < 500) {
                    recommendation = '价格有一定差异,建议综合考虑价格和平台服务';
                } else {
                    recommendation = '价格差异较大,建议优先选择低价平台';
                }
                
                // 根据评分和销量给出更具体的建议
                const bestProduct = data.reduce((best, current) => {
                    const currentScore = (parseFloat(current.rating) || 0) * (parseInt(current.sales) || 0);
                    const bestScore = (parseFloat(best.rating) || 0) * (parseInt(best.sales) || 0);
                    return currentScore > bestScore ? current : best;
                }, data[0]);
                
                if (parseFloat(bestProduct.rating) >= 4.5) {
                    recommendation += `,${bestProduct.platformName}的${bestProduct.shop}评分较高`;
                }
                
                document.getElementById('recommendation').textContent = recommendation;
                
                analysisSection.style.display = 'block';
            }
            
            saveSearchHistory(keyword) {
                // 去重并限制历史记录数量
                this.searchHistory = this.searchHistory.filter(item => item !== keyword);
                this.searchHistory.unshift(keyword);
                this.searchHistory = this.searchHistory.slice(0, 10);
                
                localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
                this.loadSearchHistory();
            }
            
            loadSearchHistory() {
                const historyList = document.getElementById('historyList');
                historyList.innerHTML = this.searchHistory.map(keyword => 
                    `<div class="history-item" onclick="document.getElementById('searchInput').value = '${keyword}'; priceComparisonSystem.performSearch();">${keyword}</div>`
                ).join('');
            }
            
            showLoading(show) {
                document.getElementById('loading').style.display = show ? 'block' : 'none';
                document.getElementById('searchBtn').disabled = show;
            }
            
            showError(message) {
                const errorDiv = document.getElementById('errorMessage');
                errorDiv.textContent = message;
                errorDiv.style.display = 'block';
            }
            
            hideError() {
                document.getElementById('errorMessage').style.display = 'none';
            }
        }
        
    // 查看商品详情函数
    function viewProduct(url) {
        if (url) {
            window.open(url, '_blank');
        } else {
            alert('商品链接不可用');
        }
    }
        
        // 初始化系统
        const priceComparisonSystem = new PriceComparisonSystem();
        
        // 页面加载完成后显示欢迎信息
        window.addEventListener('load', () => {
            console.log('购物比价系统已加载完成');
            
            // 显示使用提示
            setTimeout(() => {
                if (priceComparisonSystem.searchHistory.length === 0) {
                    document.getElementById('searchInput').placeholder = '试试搜索:手机、笔记本电脑、耳机...';
                }
            }, 1000);
        });
        
        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
posted @ 2026-01-03 00:25  liu某人  阅读(10)  评论(0)    收藏  举报