// 当前选中的产品 ID,用于后续操作
let currentProductName = null;
let currentPage = 0;
const itemsPerPage = 10; // 每页显示10个有效产品
let totalOnlineProducts = 0; // 有效产品总数
let bannerInterval; // Banner自动轮播定时器
let currentSlide = 0; // 当前显示的轮播项索引
let currentFilter = 'all'; // 当前选中的筛选条件
let offlineProductsData = []; // 已下架产品数据
let offlineGroupCreated = false; // 已下架分组是否已创建
let isLoading = false; // 防止重复加载
let loadedOnlineCount = 0; // 记录已加载的有效产品数量
// 存储所有产品数据用于搜索
let allProductsData = [];
let isSearching = false;
let currentSearchTerm = '';
// 在 DOMContentLoaded 事件中初始化加载更多提示
document.addEventListener('DOMContentLoaded', function () {
// 初始化轮播图自动轮播
initBannerSlider();
// 获取标签按钮和区域
const tabButtons = document.querySelectorAll('.tab-button');
const sections = document.querySelectorAll('.section');
// 为每个标签按钮添加点击事件监听器
tabButtons.forEach(button => {
button.addEventListener('click', function () {
const tabId = this.getAttribute('data-tab');
// 移除所有按钮的活动状态并添加到当前按钮
tabButtons.forEach(btn => btn.classList.remove('active'));
this.classList.add('active');
// 隐藏所有区域并显示当前区域
sections.forEach(section => section.classList.remove('active'));
document.getElementById(`${tabId}-section`).classList.add('active');
// 重置筛选条件为"所有"
resetFilterButtons();
// 重置已下架产品数据
offlineProductsData = [];
offlineGroupCreated = false;
loadedOnlineCount = 0;
// 重置页码
currentPage = 0;
// 清空搜索
clearSearch();
// 加载产品
loadProducts(tabId, 0, 'all');
});
});
// 自动选择流量卡专区
const dataCardButton = document.querySelector('.tab-button[data-tab="data-card"]');
if (dataCardButton) {
dataCardButton.click();
}
// 初始化筛选按钮
initFilterButtons();
// 初始化搜索功能
initSearchFunctionality();
// 初始化加载更多按钮
initLoadMoreButton();
// 智能客服浮层功能
initAIFloatingLayer();
// 订单查询功能 - 只初始化原有的弹窗功能
initOrderQuery();
// 新增初始化代码
initPageNavigation();
initMyPage();
initAIFloatingButton();
// 移除原订单查询按钮(在页面底部,现在不需要了)
const orderQueryBtn = document.getElementById('order-query-btn');
if (orderQueryBtn) {
orderQueryBtn.style.display = 'none';
}
// 隐藏原来的智能客服按钮(在页面底部,现在不需要了)
const openAIBtn = document.getElementById('open-ai-btn');
if (openAIBtn) {
openAIBtn.style.display = 'none';
}
});
/**
* 初始化筛选按钮
*/
function initFilterButtons() {
const filterButtons = document.querySelectorAll('.filter-btn');
filterButtons.forEach(button => {
button.addEventListener('click', function() {
// 移除所有按钮的active类
filterButtons.forEach(btn => {
btn.classList.remove('active');
});
// 给当前点击的按钮添加active类
this.classList.add('active');
// 获取筛选条件
const filterValue = this.getAttribute('data-filter');
currentFilter = filterValue;
// 重置已下架产品数据
offlineProductsData = [];
offlineGroupCreated = false;
loadedOnlineCount = 0;
// 清空搜索
clearSearch();
// 重置页码并加载产品
currentPage = 0;
loadProducts('data-card', 0, filterValue);
});
});
}
/**
* 初始化搜索功能
*/
function initSearchFunctionality() {
const searchInput = document.getElementById('product-search-input');
const searchClearBtn = document.getElementById('search-clear-btn');
if (!searchInput) return;
// 添加搜索输入事件监听(使用防抖)
let searchTimeout;
searchInput.addEventListener('input', function() {
const searchTerm = this.value.trim();
// 显示/隐藏清除按钮
if (searchTerm.length > 0) {
searchClearBtn.style.display = 'block';
} else {
searchClearBtn.style.display = 'none';
clearSearch();
return;
}
// 清除之前的定时器
clearTimeout(searchTimeout);
// 设置新的定时器(防抖,300ms后执行搜索)
searchTimeout = setTimeout(() => {
performSearch(searchTerm);
}, 300);
});
// 添加清除按钮点击事件
searchClearBtn.addEventListener('click', function() {
searchInput.value = '';
searchClearBtn.style.display = 'none';
clearSearch();
});
// 添加键盘事件监听
searchInput.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
searchInput.value = '';
searchClearBtn.style.display = 'none';
clearSearch();
}
});
}
/**
* 执行搜索
* @param {string} searchTerm - 搜索关键词
*/
function performSearch(searchTerm) {
if (searchTerm.length === 0) {
clearSearch();
return;
}
currentSearchTerm = searchTerm;
isSearching = true;
// 隐藏加载更多按钮
const loadMoreContainer = document.getElementById('load-more-container');
if (loadMoreContainer) {
loadMoreContainer.style.display = 'none';
}
// 隐藏搜索结果为空提示
const searchEmptyResult = document.getElementById('search-empty-result');
if (searchEmptyResult) {
searchEmptyResult.style.display = 'none';
}
// 隐藏推荐区域
const recommendedSection = document.getElementById('recommended-section');
if (recommendedSection) {
recommendedSection.style.display = 'none';
}
// 收集所有产品数据
collectAllProductsForSearch();
// 进行搜索匹配
const searchResults = searchProducts(searchTerm);
// 获取产品列表容器
const productList = document.getElementById('data-card-product-list');
if (!productList) return;
if (searchResults.length > 0) {
// 显示搜索结果
displaySearchResults(searchResults, productList);
} else {
// 显示无结果提示
showNoResults(searchTerm);
}
}
/**
* 收集所有产品数据用于搜索
*/
function collectAllProductsForSearch() {
allProductsData = [];
// 从正常产品列表中收集
const productItems = document.querySelectorAll('#data-card-product-list .product-item');
productItems.forEach(item => {
const button = item.querySelector('.product-button');
if (button) {
const productName = button.getAttribute('data-name');
const productTitle = item.querySelector('.product-info h3')?.textContent || '';
const productRating = item.querySelector('.product-rating span')?.textContent || '0';
const productDesc = item.querySelector('.product-desc')?.textContent || '';
allProductsData.push({
element: item,
name: productName,
title: productTitle,
rating: parseFloat(productRating),
description: productDesc,
isOnline: !button.classList.contains('disabled')
});
}
});
// 从已下架产品中收集
const offlineGroup = document.getElementById('offline-product-group');
if (offlineGroup) {
const offlineItems = offlineGroup.querySelectorAll('.product-item');
offlineItems.forEach(item => {
const button = item.querySelector('.product-button');
if (button) {
const productName = button.getAttribute('data-name');
const productTitle = item.querySelector('.product-info h3')?.textContent || '';
const productRating = item.querySelector('.product-rating span')?.textContent || '0';
const productDesc = item.querySelector('.product-desc')?.textContent || '';
allProductsData.push({
element: item,
name: productName,
title: productTitle,
rating: parseFloat(productRating),
description: productDesc,
isOnline: false // 已下架产品标记为不在线
});
}
});
}
}
/**
* 搜索产品
* @param {string} searchTerm - 搜索关键词
* @returns {Array} 匹配的产品列表
*/
function searchProducts(searchTerm) {
if (!searchTerm || searchTerm.length === 0) return [];
const lowerSearchTerm = searchTerm.toLowerCase();
// 进行模糊匹配
return allProductsData.filter(product => {
// 匹配标题
const titleMatch = product.title.toLowerCase().includes(lowerSearchTerm);
// 匹配描述(可选)
const descMatch = product.description.toLowerCase().includes(lowerSearchTerm);
return titleMatch || descMatch;
}).sort((a, b) => {
// 优先匹配标题,然后按评分排序
const aTitleMatch = a.title.toLowerCase().includes(lowerSearchTerm);
const bTitleMatch = b.title.toLowerCase().includes(lowerSearchTerm);
if (aTitleMatch && !bTitleMatch) return -1;
if (!aTitleMatch && bTitleMatch) return 1;
return b.rating - a.rating;
});
}
/**
* 显示搜索结果
* @param {Array} results - 搜索结果数组
* @param {HTMLElement} productList - 产品列表容器
*/
function displaySearchResults(results, productList) {
// 隐藏正常产品列表中的所有产品
const allProductItems = document.querySelectorAll('#data-card-product-list .product-item');
allProductItems.forEach(item => {
item.style.display = 'none';
});
// 隐藏已下架分组
const offlineGroup = document.getElementById('offline-product-group');
if (offlineGroup) {
offlineGroup.style.display = 'none';
}
// 隐藏筛选为空提示(如果存在)
const filterEmptyMessage = productList.querySelector('.filter-empty-message');
if (filterEmptyMessage) {
filterEmptyMessage.style.display = 'none';
}
// 显示匹配的产品
results.forEach(result => {
result.element.style.display = 'flex';
});
// 重新绑定点击事件
setTimeout(() => {
rebindProductEvents();
}, 0);
}
/**
* 显示无搜索结果
* @param {string} searchTerm - 搜索关键词
*/
function showNoResults(searchTerm) {
// 隐藏所有产品
const allProductItems = document.querySelectorAll('#data-card-product-list .product-item');
allProductItems.forEach(item => {
item.style.display = 'none';
});
// 隐藏已下架分组
const offlineGroup = document.getElementById('offline-product-group');
if (offlineGroup) {
offlineGroup.style.display = 'none';
}
// 隐藏筛选为空提示(如果存在)
const productList = document.getElementById('data-card-product-list');
if (productList) {
const filterEmptyMessage = productList.querySelector('.filter-empty-message');
if (filterEmptyMessage) {
filterEmptyMessage.style.display = 'none';
}
}
// 显示无结果提示
const searchEmptyResult = document.getElementById('search-empty-result');
if (searchEmptyResult) {
searchEmptyResult.style.display = 'block';
}
// 显示推荐区域
const recommendedSection = document.getElementById('recommended-section');
const recommendedList = document.getElementById('recommended-product-list');
if (recommendedSection && recommendedList) {
recommendedSection.style.display = 'block';
recommendedList.innerHTML = '';
// 修复:确保 allProductsData 有数据
// 如果 allProductsData 为空,重新收集一次
if (allProductsData.length === 0) {
collectAllProductsForSearch();
}
// 修复问题1:过滤掉已下架产品,只显示在线产品
if (allProductsData.length > 0) {
// 重新排序:只保留在线产品,然后按评分排序
const sortedProducts = [...allProductsData].filter(product => product.isOnline).sort((a, b) => {
// 按评分排序
return b.rating - a.rating;
});
// 限制显示数量,避免过多
const displayProducts = sortedProducts.slice(0, 6); // 只显示前6个推荐产品
displayProducts.forEach(product => {
// 创建新的产品元素,而不是克隆(避免事件绑定问题)
const productItem = document.createElement('div');
productItem.className = 'product-item';
// 复制原产品的HTML内容
productItem.innerHTML = product.element.innerHTML;
// 修复:确保推荐产品的按钮可以点击
const button = productItem.querySelector('.product-button');
if (button && !button.classList.contains('disabled')) {
const productName = button.getAttribute('data-name');
if (productName) {
// 移除旧的监听器,添加新的
const newButton = button.cloneNode(true);
button.parentNode.replaceChild(newButton, button);
newButton.addEventListener('click', function() {
fetchProductDetail(productName, 'data-card');
});
}
}
recommendedList.appendChild(productItem);
});
} else {
// 如果没有产品可推荐,显示提示信息
recommendedList.innerHTML = '
';
}
}
}
/**
* 清除搜索状态
*/
function clearSearch() {
isSearching = false;
currentSearchTerm = '';
// 显示所有产品
const allProductItems = document.querySelectorAll('#data-card-product-list .product-item');
allProductItems.forEach(item => {
item.style.display = 'flex';
});
// 显示已下架分组
const offlineGroup = document.getElementById('offline-product-group');
if (offlineGroup) {
offlineGroup.style.display = 'block';
}
// 显示筛选为空提示(如果存在且没有产品)
const productList = document.getElementById('data-card-product-list');
if (productList) {
const filterEmptyMessage = productList.querySelector('.filter-empty-message');
const hasProducts = productList.querySelector('.product-item');
if (filterEmptyMessage && !hasProducts) {
filterEmptyMessage.style.display = 'flex';
}
}
// 隐藏搜索结果为空提示
const searchEmptyResult = document.getElementById('search-empty-result');
if (searchEmptyResult) {
searchEmptyResult.style.display = 'none';
}
// 隐藏推荐区域
const recommendedSection = document.getElementById('recommended-section');
if (recommendedSection) {
recommendedSection.style.display = 'none';
}
// 重新显示加载更多按钮(如果有更多产品)
const loadMoreContainer = document.getElementById('load-more-container');
const loadMoreBtn = document.getElementById('load-more-btn');
if (loadMoreContainer && loadMoreBtn) {
// 修复问题1:只在有效产品数量大于10时才显示加载更多按钮
if (totalOnlineProducts > 10 && loadedOnlineCount < totalOnlineProducts) {
showLoadMoreButton(loadMoreContainer, loadMoreBtn);
} else {
hideLoadMoreButton(loadMoreContainer);
}
}
// 重新绑定所有产品事件
setTimeout(() => {
rebindAllProductEvents();
}, 0);
}
/**
* 重新绑定产品事件
*/
function rebindProductEvents() {
const productButtons = document.querySelectorAll('#data-card-product-list .product-button:not(.disabled)');
productButtons.forEach(button => {
const productName = button.getAttribute('data-name');
if (productName) {
// 移除旧的监听器
const newButton = button.cloneNode(true);
button.parentNode.replaceChild(newButton, button);
if (!newButton.classList.contains('disabled')) {
newButton.addEventListener('click', function() {
fetchProductDetail(productName, 'data-card');
});
}
}
});
}
/**
* 重新绑定所有产品事件
*/
function rebindAllProductEvents() {
rebindProductEvents();
// 绑定已下架产品的点击事件(如果有)
const offlineButtons = document.querySelectorAll('#offline-product-group .product-button:not(.disabled)');
offlineButtons.forEach(button => {
const productName = button.getAttribute('data-name');
if (productName) {
button.addEventListener('click', function() {
fetchProductDetail(productName, 'data-card');
});
}
});
}
/**
* 初始化加载更多按钮
*/
function initLoadMoreButton() {
const loadMoreBtn = document.getElementById('load-more-btn');
const loadMoreContainer = document.getElementById('load-more-container');
if (!loadMoreBtn) return;
loadMoreBtn.addEventListener('click', function() {
if (isLoading || isSearching) return;
currentPage++;
loadProducts('data-card', currentPage, currentFilter);
});
// 初始隐藏加载更多按钮
loadMoreContainer.style.display = 'none';
}
/**
* 重置筛选按钮为"所有"选中状态
*/
function resetFilterButtons() {
const filterButtons = document.querySelectorAll('.filter-btn');
filterButtons.forEach(btn => {
btn.classList.remove('active');
if (btn.getAttribute('data-filter') === 'all') {
btn.classList.add('active');
}
});
currentFilter = 'all';
}
/**
* 初始化轮播图自动轮播功能
*/
function initBannerSlider() {
const bannerSlides = document.querySelectorAll('.banner-slide');
const bannerDots = document.querySelectorAll('.dot');
const prevArrow = document.querySelector('.banner-arrow-prev');
const nextArrow = document.querySelector('.banner-arrow-next');
if (bannerSlides.length === 0 || bannerDots.length === 0) {
console.error('Banner slides or dots not found');
return;
}
// 切换到指定轮播项
function showSlide(index) {
// 确保索引在有效范围内
let newIndex = index;
if (newIndex >= bannerSlides.length) {
newIndex = 0;
} else if (newIndex < 0) {
newIndex = bannerSlides.length - 1;
}
// 隐藏当前轮播项,移除活动类
bannerSlides[currentSlide].classList.remove('active');
bannerDots[currentSlide].classList.remove('active');
// 更新当前轮播项索引
currentSlide = newIndex;
// 显示新的轮播项,添加活动类
bannerSlides[currentSlide].classList.add('active');
bannerDots[currentSlide].classList.add('active');
}
// 切换到下一张
function nextSlide() {
showSlide(currentSlide + 1);
resetTimer();
}
// 切换到上一张
function prevSlide() {
showSlide(currentSlide - 1);
resetTimer();
}
// 重置定时器
function resetTimer() {
clearInterval(bannerInterval);
bannerInterval = setInterval(nextSlide, 5000);
}
// 设置定时器,每5秒切换一次轮播项
bannerInterval = setInterval(nextSlide, 5000);
// 为指示点添加点击事件监听器
bannerDots.forEach(dot => {
dot.addEventListener('click', function () {
const slideIndex = parseInt(this.getAttribute('data-index'));
showSlide(slideIndex);
resetTimer();
});
});
// 为左右箭头添加点击事件监听器
if (prevArrow) {
prevArrow.addEventListener('click', function(e) {
e.stopPropagation(); // 防止事件冒泡
prevSlide();
});
}
if (nextArrow) {
nextArrow.addEventListener('click', function(e) {
e.stopPropagation(); // 防止事件冒泡
nextSlide();
});
}
// 为轮播项添加点击事件监听器
bannerSlides.forEach((slide, index) => {
slide.addEventListener('click', function () {
showSlide(index);
resetTimer();
});
});
// 添加键盘导航支持(可选功能)
document.addEventListener('keydown', function(e) {
if (e.key === 'ArrowLeft') {
prevSlide();
} else if (e.key === 'ArrowRight') {
nextSlide();
}
});
// 添加触摸滑动支持(移动端可选功能)
let touchStartX = 0;
let touchEndX = 0;
const bannerContainer = document.querySelector('.banner-container');
if (bannerContainer) {
bannerContainer.addEventListener('touchstart', function(e) {
touchStartX = e.changedTouches[0].screenX;
}, {passive: true});
bannerContainer.addEventListener('touchend', function(e) {
touchEndX = e.changedTouches[0].screenX;
handleSwipe();
}, {passive: true});
}
function handleSwipe() {
const swipeThreshold = 50; // 最小滑动距离
if (touchEndX < touchStartX - swipeThreshold) {
// 向左滑动,下一张
nextSlide();
} else if (touchEndX > touchStartX + swipeThreshold) {
// 向右滑动,上一张
prevSlide();
}
}
}
/**
* 加载产品列表
* @param {string} category - 产品类别
* @param {number} page - 当前页码
* @param {string} filter - 筛选条件(运营商)
*/
function loadProducts(category, page, filter = 'all') {
if (isLoading) return;
isLoading = true;
const productList = document.getElementById(`${category}-product-list`);
const loadMoreBtn = document.getElementById('load-more-btn');
const loadMoreContainer = document.getElementById('load-more-container');
if (!productList) {
isLoading = false;
return;
}
// 显示加载提示(仅第一页)
if (page === 0) {
const loadingIndicator = document.createElement('div');
loadingIndicator.className = 'loading';
loadingIndicator.innerHTML = `
加载中
`;
productList.innerHTML = '';
productList.appendChild(loadingIndicator);
offlineProductsData = [];
offlineGroupCreated = false;
loadedOnlineCount = 0;
// 重置已下架分组
const existingOfflineGroup = document.getElementById('offline-product-group');
if (existingOfflineGroup) {
existingOfflineGroup.remove();
}
// 清空搜索
const searchInput = document.getElementById('product-search-input');
if (searchInput) {
searchInput.value = '';
}
const searchClearBtn = document.getElementById('search-clear-btn');
if (searchClearBtn) {
searchClearBtn.style.display = 'none';
}
clearSearch();
} else {
// 禁用加载更多按钮并显示加载中状态
if (loadMoreBtn) {
loadMoreBtn.disabled = true;
loadMoreBtn.innerHTML = '加载中...';
}
}
// 构建API URL,添加筛选参数
let apiUrl = `/api/products_filtered?category=${category}&page=${page}&limit=${itemsPerPage}`;
if (filter && filter !== 'all') {
apiUrl += `&operator=${encodeURIComponent(filter)}`;
}
// 获取产品列表
fetch(apiUrl)
.then(response => response.json())
.then(data => {
// 移除加载提示
if (page === 0) {
productList.innerHTML = '';
}
if (!data) {
if (page === 0) {
// 问题2修复:使用与搜索相同样式的h3标题
const emptyMessage = document.createElement('div');
emptyMessage.className = 'search-empty-result';
emptyMessage.style.display = 'flex';
emptyMessage.style.flexDirection = 'column';
emptyMessage.style.alignItems = 'center';
emptyMessage.style.justifyContent = 'center';
emptyMessage.style.padding = '40px 20px';
emptyMessage.innerHTML = `
暂无该产品
`;
productList.appendChild(emptyMessage);
}
if (loadMoreContainer) {
loadMoreContainer.style.display = 'none';
}
isLoading = false;
return;
}
const products = data.products || data;
const totalProducts = data.total || products.length;
if (products.length === 0) {
// 如果是第一页且没有产品,显示提示信息
if (page === 0) {
// 问题2修复:使用与搜索相同样式的h3标题
const emptyMessage = document.createElement('div');
emptyMessage.className = 'search-empty-result';
emptyMessage.style.display = 'block'; // 只需要改显示状态
emptyMessage.innerHTML = `
暂无该产品
`;
productList.appendChild(emptyMessage);
}
if (loadMoreContainer) {
loadMoreContainer.style.display = 'none';
}
isLoading = false;
return;
}
// ========== 前端排序逻辑开始 ==========
// 对产品进行排序:status为pass的优先,然后按rating降序,最后按id排序
const sortedProducts = [...products].sort((a, b) => {
// 第一级排序:status,pass在前
if (a.status === 'pass' && b.status !== 'pass') return -1;
if (a.status !== 'pass' && b.status === 'pass') return 1;
// 第二级排序:rating,降序
const ratingA = a.rating || 0;
const ratingB = b.rating || 0;
if (ratingB !== ratingA) {
return ratingB - ratingA; // 降序
}
// 第三级排序:id,升序
return (a.id || 0) - (b.id || 0);
});
// ========== 前端排序逻辑结束 ==========
// 分离正常产品和已下架产品
const onlineProducts = [];
const currentPageOfflineProducts = [];
sortedProducts.forEach(product => {
if (product.status === 'fail') {
currentPageOfflineProducts.push(product);
} else {
onlineProducts.push(product);
}
});
// 将已下架产品添加到总列表中
if (currentPageOfflineProducts.length > 0) {
offlineProductsData = offlineProductsData.concat(currentPageOfflineProducts);
}
// 计算有效产品总数(假设后端返回的是有效产品总数)
totalOnlineProducts = data.totalOnline || (page === 0 ? onlineProducts.length : totalOnlineProducts);
// 修复问题1:计算是否有更多产品需要加载
const hasMoreProducts = totalOnlineProducts > 10 && loadedOnlineCount < totalOnlineProducts;
// 如果是第一页,先添加所有正常产品
if (page === 0) {
// 先添加所有正常产品(最多10个)
const productsToShow = onlineProducts.slice(0, itemsPerPage);
productsToShow.forEach(product => {
const productItem = createProductItem(product, category);
productList.appendChild(productItem);
});
loadedOnlineCount = productsToShow.length;
// 修复问题1:只在有效产品数量大于10时才显示加载更多按钮
if (hasMoreProducts) {
showLoadMoreButton(loadMoreContainer, loadMoreBtn);
} else {
hideLoadMoreButton(loadMoreContainer);
}
} else {
// 非第一页,添加正常产品到已有产品后面
const productsToShow = onlineProducts.slice(0, itemsPerPage);
productsToShow.forEach(product => {
const productItem = createProductItem(product, category);
productList.appendChild(productItem);
});
loadedOnlineCount += productsToShow.length;
// 修复问题1:检查是否还有更多有效产品
if (loadedOnlineCount < totalOnlineProducts) {
showLoadMoreButton(loadMoreContainer, loadMoreBtn);
} else {
hideLoadMoreButton(loadMoreContainer);
}
}
// 如果是第一页且当前页有已下架产品,需要创建分组
if (page === 0 && currentPageOfflineProducts.length > 0) {
// 等待一个微任务,确保正常产品已经渲染完成
setTimeout(() => {
createOfflineProductsGroup(category);
}, 0);
}
// 如果是后续页面且有已下架产品,需要更新已下架分组
else if (page > 0 && currentPageOfflineProducts.length > 0) {
// 等待一个微任务,确保正常产品已经渲染完成
setTimeout(() => {
updateOfflineProductsGroup(category);
}, 0);
}
isLoading = false;
})
.catch(error => {
console.error('加载产品失败:', error);
if (page === 0) {
productList.innerHTML = '加载失败,请稍后重试
';
}
if (loadMoreBtn) {
loadMoreBtn.disabled = false;
loadMoreBtn.innerHTML = '加载更多';
}
// 修复问题1:出错时也隐藏加载更多按钮
if (loadMoreContainer) {
loadMoreContainer.style.display = 'none';
}
isLoading = false;
});
}
/**
* 显示加载更多按钮
*/
function showLoadMoreButton(container, button) {
if (container && button) {
container.style.display = 'block';
button.disabled = false;
button.innerHTML = '加载更多';
}
}
/**
* 隐藏加载更多按钮
*/
function hideLoadMoreButton(container) {
if (container) {
container.style.display = 'none';
}
}
/**
* 创建已下架产品分组
* @param {string} category - 产品类别
*/
function createOfflineProductsGroup(category) {
if (offlineGroupCreated || offlineProductsData.length === 0) return;
offlineGroupCreated = true;
const productList = document.getElementById(`${category}-product-list`);
if (!productList) return;
// 创建已下架产品分组
const offlineGroup = document.createElement('div');
offlineGroup.id = 'offline-product-group';
offlineGroup.className = 'offline-product-group';
offlineGroup.innerHTML = `
`;
// 将分组添加到产品列表的后面
productList.parentNode.insertBefore(offlineGroup, productList.nextSibling);
// 将已下架产品添加到分组容器中
const offlineContainer = offlineGroup.querySelector('.offline-products-container');
offlineProductsData.forEach(product => {
const productItem = createProductItem(product, category);
offlineContainer.appendChild(productItem);
});
// 添加点击事件
const header = offlineGroup.querySelector('.offline-group-header');
const toggleBtn = offlineGroup.querySelector('.toggle-offline-btn');
const container = offlineGroup.querySelector('.offline-products-container');
header.addEventListener('click', function() {
const isExpanded = container.style.display === 'block';
if (isExpanded) {
container.style.display = 'none';
toggleBtn.innerHTML = '';
} else {
container.style.display = 'block';
toggleBtn.innerHTML = '';
}
});
}
/**
* 更新已下架产品分组
* @param {string} category - 产品类别
*/
function updateOfflineProductsGroup(category) {
const offlineGroup = document.getElementById('offline-product-group');
if (!offlineGroup) {
createOfflineProductsGroup(category);
return;
}
const offlineContainer = offlineGroup.querySelector('.offline-products-container');
if (!offlineContainer) return;
// 获取当前已显示的下架产品
const existingOfflineProducts = offlineContainer.querySelectorAll('.product-item');
const existingIds = [];
existingOfflineProducts.forEach(item => {
const button = item.querySelector('.product-button');
if (button) {
const productName = button.getAttribute('data-name');
existingIds.push(productName);
}
});
// 添加新的下架产品(避免重复)
offlineProductsData.forEach(product => {
if (!existingIds.includes(product.name)) {
const productItem = createProductItem(product, category);
offlineContainer.appendChild(productItem);
}
});
}
/**
* 创建产品项
* @param {Object} product - 产品信息
* @param {string} category - 产品类别
* @returns {HTMLElement} 产品项
*/
function createProductItem(product, category) {
const productItem = document.createElement('div');
productItem.className = 'product-item';
// 根据 status 字段判断按钮状态
const isDisabled = product.status === 'fail'; // 如果 status 为 'fail',则禁用
const buttonText = isDisabled ? '已下架' : '免费办理';
const buttonDisabledAttr = isDisabled ? 'disabled' : '';
const buttonDisabledClass = isDisabled ? 'disabled' : '';
// 根据status决定是否显示蒙版
const overlayHtml = isDisabled ? '已下架
' : '';
// 解析标签字符串
let tagsHtml = '';
if (product.biaoqian) {
// 使用"丨"分割标签
const tags = product.biaoqian.split('丨');
if (tags.length > 0) {
tagsHtml = '';
tags.forEach(tag => {
if (tag.trim()) { // 确保标签不为空
tagsHtml += `${tag.trim()}`;
}
});
tagsHtml += '
';
}
}
// 设置产品项的 HTML 内容
productItem.innerHTML = `

${overlayHtml}
${product.name}
${generateRatingStars(product.rating)}
${product.rating}
${product.description}
${tagsHtml}
`;
// 如果存在 jiaobiao 参数,则添加角标
if (product.jiaobiao) {
const productImage = productItem.querySelector('.product-image');
const tag = document.createElement('div');
tag.className = 'product-tag';
tag.textContent = product.jiaobiao;
productImage.appendChild(tag);
}
// 获取详情按钮并添加点击事件监听器 - 仅当按钮未禁用时
const detailButton = productItem.querySelector('.product-button');
if (!isDisabled) {
detailButton.addEventListener('click', function () {
const productName = this.getAttribute('data-name');
fetchProductDetail(productName, category);
});
}
return productItem;
}
/**
* 生成星级评分 HTML
* @param {number} rating - 评分
* @returns {string} 星级评分 HTML
*/
function generateRatingStars(rating) {
let starsHtml = '';
for (let i = 1; i <= 5; i++) {
if (i <= rating) {
starsHtml += '';
} else if (i - 0.5 <= rating) {
starsHtml += '';
} else {
starsHtml += '';
}
}
return starsHtml;
}
/**
* 获取产品详情
* @param {number} productName - 产品 name
* @param {string} category - 产品类别
*/
function fetchProductDetail(productName, category) {
fetch(`/api/product/${encodeURIComponent(productName)}?category=${category}`)
.then(response => response.json())
.then(product => {
if (product.error) {
alert(product.error);
return;
}
// 检查是否存在 action_url 并进行跳转
if (product.action_url) {
// 直接跳转到 action_url
window.location.href = product.action_url;
return;
}
// 如果没有 action_url,则显示产品详情模态框
document.getElementById('modal-product-img').src = `/api/images/${product.image_filename}`;
document.getElementById('modal-product-title').textContent = product.name;
const ratingHtml = generateRatingStars(product.rating);
document.getElementById('modal-product-rating-stars').innerHTML = ratingHtml;
document.getElementById('modal-product-rating-score').textContent = product.rating;
document.getElementById('modal-product-desc').textContent = product.description;
loadVariantOptions(product);
document.getElementById('product-modal').style.display = 'block';
document.body.style.overflow = 'auto';
document.querySelector('.quantity-input').value = 1;
currentProductName = productName;
})
.catch(error => {
console.error('获取产品详情失败:', error);
});
}
/**
* 加载产品变体选项
* @param {Object} product - 产品信息
*/
function loadVariantOptions(product) {
const variantOptionsContainer = document.getElementById('variant-options');
variantOptionsContainer.innerHTML = '';
if (!product.variants || product.variants.length === 0) {
variantOptionsContainer.innerHTML = '';
return;
}
let variantHtml = '';
product.variants.forEach(variant => {
variantHtml += `
`;
variant.options.forEach(option => {
variantHtml += `
${option}
`;
});
variantHtml += `
`;
});
variantOptionsContainer.innerHTML = variantHtml;
// 为变体选项添加点击事件监听器
const variantItems = variantOptionsContainer.querySelectorAll('.variant-item');
variantItems.forEach(item => {
item.addEventListener('click', function () {
const parent = this.parentElement;
parent.querySelectorAll('.variant-item').forEach(el => el.classList.remove('active'));
this.classList.add('active');
});
});
// 默认选中第一个变体选项
variantOptionsContainer.querySelectorAll('.variant-option').forEach(group => {
const firstItem = group.querySelector('.variant-item');
if (firstItem) {
firstItem.classList.add('active');
}
});
}
// 为数量选择器按钮添加点击事件监听器
document.querySelectorAll('.quantity-btn').forEach(btn => {
btn.addEventListener('click', function () {
const input = this.parentElement.querySelector('.quantity-input');
let value = parseInt(input.value);
if (this.classList.contains('minus')) {
if (value > 1) {
input.value = value - 1;
}
} else if (this.classList.contains('plus')) {
input.value = value + 1;
}
});
});
/**
* 初始化智能客服浮层功能
*/
function initAIFloatingLayer() {
// 注意:原来的 open-ai-btn 已被替换为 ai-floating-btn
// 所以我们直接为新按钮绑定事件,但这里只处理关闭和遮罩层逻辑
const closeAIBtn = document.getElementById('close-ai-floating');
const aiOverlay = document.getElementById('ai-overlay');
const aiFloatingLayer = document.getElementById('ai-floating-layer');
const aiFrame = document.getElementById('ai-frame');
// 关闭智能客服浮层
function closeAIFloating() {
aiOverlay.classList.remove('show');
aiFloatingLayer.classList.remove('show');
// 等待动画完成后隐藏
setTimeout(() => {
aiOverlay.style.display = 'none';
aiFloatingLayer.style.display = 'none';
document.body.style.overflow = 'auto';
}, 300);
}
// 点击关闭按钮关闭浮层
if (closeAIBtn) {
closeAIBtn.addEventListener('click', closeAIFloating);
}
// 点击遮罩层关闭浮层
if (aiOverlay) {
aiOverlay.addEventListener('click', closeAIFloating);
}
// 阻止浮层内容点击时关闭
if (aiFloatingLayer) {
aiFloatingLayer.addEventListener('click', function(event) {
event.stopPropagation();
});
}
// 窗口大小变化时调整浮层
window.addEventListener('resize', function() {
const windowHeight = window.innerHeight;
if (aiFloatingLayer) {
aiFloatingLayer.style.maxHeight = Math.min(600, windowHeight * 0.85) + 'px';
}
});
// 初始化浮层大小
if (aiFloatingLayer) {
const windowHeight = window.innerHeight;
aiFloatingLayer.style.maxHeight = Math.min(600, windowHeight * 0.85) + 'px';
}
}
/**
* 初始化订单查询功能
*/
function initOrderQuery() {
// 注意:原来的订单查询按钮和弹窗在"我的"页面中已被替换
// 这里只保留原有的弹窗功能,但元素可能不存在
const orderQueryBtn = document.getElementById('order-query-btn');
const orderQueryModal = document.getElementById('order-query-modal');
const submitQueryBtn = document.getElementById('submit-query-btn');
const cancelQueryBtn = document.getElementById('cancel-query-btn');
const phoneInput = document.getElementById('phone-input');
const phoneError = document.getElementById('phone-error');
// 如果元素不存在,直接返回
if (!orderQueryBtn || !orderQueryModal) {
return;
}
// 打开订单查询弹窗
orderQueryBtn.addEventListener('click', function() {
orderQueryModal.style.display = 'block';
// 清空输入框和错误提示
if (phoneInput) phoneInput.value = '';
if (phoneError) phoneError.style.display = 'none';
});
// 关闭订单查询弹窗
if (cancelQueryBtn) {
cancelQueryBtn.addEventListener('click', function() {
orderQueryModal.style.display = 'none';
// 清空输入框和错误提示
if (phoneInput) phoneInput.value = '';
if (phoneError) phoneError.style.display = 'none';
});
}
// 显示错误提示
function showPhoneError(message = '请输入下单的手机号码') {
if (phoneError) {
phoneError.textContent = message;
phoneError.style.display = 'block';
}
if (phoneInput) {
phoneInput.style.borderColor = '#e74c3c';
}
}
// 隐藏错误提示
function hidePhoneError() {
if (phoneError) {
phoneError.style.display = 'none';
}
if (phoneInput) {
phoneInput.style.borderColor = '#e0e0e0';
}
}
// 当用户开始输入时,清空错误提示
if (phoneInput) {
phoneInput.addEventListener('input', function() {
hidePhoneError();
});
}
// 提交查询
if (submitQueryBtn) {
submitQueryBtn.addEventListener('click', function() {
const phone = phoneInput ? phoneInput.value.trim() : '';
// 手机号验证
if (!phone) {
showPhoneError('请输入手机号码');
return;
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
showPhoneError('无效的手机号码!');
return;
}
// 如果验证通过,隐藏错误提示
hidePhoneError();
// 显示加载动画和蒙版
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
overlay.style.zIndex = '1002';
const loadingDiv = document.createElement('div');
loadingDiv.style.position = 'fixed';
loadingDiv.style.top = '50%';
loadingDiv.style.left = '50%';
loadingDiv.style.transform = 'translate(-50%, -50%)';
loadingDiv.style.zIndex = '1003';
loadingDiv.style.padding = '15px';
loadingDiv.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
loadingDiv.style.borderRadius = '8px';
loadingDiv.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.2)';
loadingDiv.innerHTML = `
查询中
`;
document.body.appendChild(overlay);
document.body.appendChild(loadingDiv);
// 关闭输入框弹窗
orderQueryModal.style.display = 'none';
// 禁用所有按钮
document.querySelectorAll('button').forEach(button => {
button.disabled = true;
});
// 调用后端接口
fetch('/orderchax', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ phone: phone })
})
.then(response => response.json())
.then(data => {
if (data.success && data.url) {
// 提供两种跳转方式供选择:
// 方式1:直接跳转
window.location.href = data.url;
// 方式2:在新标签页打开
// window.open(data.url, '_blank');
} else {
// 查询失败,重新显示弹窗
orderQueryModal.style.display = 'block';
showPhoneError('查询失败:' + (data.message || '请稍后重试'));
}
})
.catch(error => {
console.error('Error:', error);
// 查询出错,重新显示弹窗
orderQueryModal.style.display = 'block';
showPhoneError('查询出错,请稍后再试');
})
.finally(() => {
// 移除加载提示和蒙版
overlay.remove();
loadingDiv.remove();
// 启用所有按钮
document.querySelectorAll('button').forEach(button => {
button.disabled = false;
});
});
});
}
// 点击弹窗外部关闭弹窗
window.addEventListener('click', function(event) {
if (event.target === orderQueryModal) {
orderQueryModal.style.display = 'none';
// 清空输入框和错误提示
if (phoneInput) phoneInput.value = '';
if (phoneError) phoneError.style.display = 'none';
}
});
// 回车键提交查询
if (phoneInput) {
phoneInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
if (submitQueryBtn) submitQueryBtn.click();
}
});
}
}
/**
* 初始化页面切换功能
*/
function initPageNavigation() {
const navItems = document.querySelectorAll('.nav-item');
const pageContents = document.querySelectorAll('.page-content');
console.log('导航项数量:', navItems.length);
console.log('页面内容数量:', pageContents.length);
// 先确保默认显示首页
let defaultPageId = 'home-page';
navItems.forEach(item => {
const pageId = item.getAttribute('data-page');
console.log('导航项:', pageId, '是否有active类:', item.classList.contains('active'));
});
pageContents.forEach(page => {
console.log('页面:', page.id, '是否有active类:', page.classList.contains('active'));
});
// 修复:移除所有页面的active类
pageContents.forEach(page => {
page.classList.remove('active');
});
// 为首页添加active类
const homePage = document.getElementById('home-page');
if (homePage) {
homePage.classList.add('active');
}
// 更新导航状态
navItems.forEach(nav => {
nav.classList.remove('active');
if (nav.getAttribute('data-page') === 'home-page') {
nav.classList.add('active');
}
});
navItems.forEach(item => {
item.addEventListener('click', function() {
const pageId = this.getAttribute('data-page');
// 更新导航状态
navItems.forEach(nav => nav.classList.remove('active'));
this.classList.add('active');
// 切换页面内容
pageContents.forEach(page => {
page.classList.remove('active');
if (page.id === pageId) {
page.classList.add('active');
}
});
// 如果切换到我的页面,重置订单查询表单
if (pageId === 'my-page') {
resetMyPageForm();
}
});
});
}
/**
* 重置我的页面表单
*/
function resetMyPageForm() {
const phoneInput = document.getElementById('my-phone-input');
const phoneError = document.getElementById('my-phone-error');
if (phoneInput) {
phoneInput.value = '';
}
if (phoneError) {
phoneError.style.display = 'none';
}
}
/**
* 初始化我的页面功能
*/
function initMyPage() {
// 初始化FAQ折叠功能
initFAQ();
// 初始化我的页面订单查询功能
initMyPageOrderQuery();
}
/**
* 初始化FAQ折叠功能
*/
function initFAQ() {
const faqQuestions = document.querySelectorAll('.faq-question');
faqQuestions.forEach(question => {
question.addEventListener('click', function() {
const faqItem = this.parentElement;
faqItem.classList.toggle('active');
});
});
}
/**
* 初始化我的页面订单查询功能
*/
function initMyPageOrderQuery() {
const submitBtn = document.getElementById('my-submit-query-btn');
const phoneInput = document.getElementById('my-phone-input');
const phoneError = document.getElementById('my-phone-error');
if (!submitBtn || !phoneInput) return;
// 显示错误提示
function showPhoneError(message = '无效的手机号码!') {
if (phoneError) {
phoneError.textContent = message;
phoneError.style.display = 'block';
phoneInput.style.borderColor = '#e74c3c';
}
}
// 隐藏错误提示
function hidePhoneError() {
if (phoneError) {
phoneError.style.display = 'none';
phoneInput.style.borderColor = '#e0e0e0';
}
}
// 当用户开始输入时,清空错误提示
phoneInput.addEventListener('input', function() {
hidePhoneError();
});
// 提交查询
submitBtn.addEventListener('click', function() {
const phone = phoneInput.value.trim();
// 手机号验证
if (!phone) {
showPhoneError('请输入手机号码');
return;
}
if (!/^1[3-9]\d{9}$/.test(phone)) {
showPhoneError('无效的手机号码!');
return;
}
// 如果验证通过,隐藏错误提示
hidePhoneError();
// 显示加载动画和蒙版
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
overlay.style.zIndex = '1002';
const loadingDiv = document.createElement('div');
loadingDiv.style.position = 'fixed';
loadingDiv.style.top = '50%';
loadingDiv.style.left = '50%';
loadingDiv.style.transform = 'translate(-50%, -50%)';
loadingDiv.style.zIndex = '1003';
loadingDiv.style.padding = '15px';
loadingDiv.style.backgroundColor = 'rgba(255, 255, 255, 0.9)';
loadingDiv.style.borderRadius = '8px';
loadingDiv.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.2)';
loadingDiv.innerHTML = `
查询中
`;
document.body.appendChild(overlay);
document.body.appendChild(loadingDiv);
// 禁用所有按钮
document.querySelectorAll('button').forEach(button => {
button.disabled = true;
});
// 调用后端接口
fetch('/orderchax', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ phone: phone })
})
.then(response => response.json())
.then(data => {
if (data.success && data.url) {
// 提供两种跳转方式供选择:
// 方式1:直接跳转
window.location.href = data.url;
// 方式2:在新标签页打开
// window.open(data.url, '_blank');
} else {
// 查询失败,显示错误
showPhoneError('查询失败:' + (data.message || '请稍后重试'));
}
})
.catch(error => {
console.error('Error:', error);
showPhoneError('查询出错,请稍后再试');
})
.finally(() => {
// 移除加载提示和蒙版
overlay.remove();
loadingDiv.remove();
// 启用所有按钮
document.querySelectorAll('button').forEach(button => {
button.disabled = false;
});
});
});
// 回车键提交查询
phoneInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
submitBtn.click();
}
});
}
/**
* 优化智能客服按钮功能
*/
function initAIFloatingButton() {
const aiFloatingBtn = document.getElementById('ai-floating-btn');
// 为新按钮绑定点击事件
if (aiFloatingBtn) {
aiFloatingBtn.addEventListener('click', function() {
// 直接调用智能客服打开逻辑
const aiOverlay = document.getElementById('ai-overlay');
const aiFloatingLayer = document.getElementById('ai-floating-layer');
if (aiOverlay && aiFloatingLayer) {
aiOverlay.style.display = 'block';
aiFloatingLayer.style.display = 'flex';
// 触发动画
setTimeout(() => {
aiOverlay.classList.add('show');
aiFloatingLayer.classList.add('show');
}, 10);
// 防止页面滚动
document.body.style.overflow = 'hidden';
}
});
}
}