// 全局变量定义 const serverIP = '10.28.20.150'; const serverPort = '8080'; let page = 21; // 初始页码为1,代表从第1条数据开始获取 let pageSize = 30; // 初始每次固定获取10条数据 let licenseTotal = 0; // 数据总量(从接口获取) let loadedItems = 0; // 已加载的数据条目数量 let isLoading = false; // 防止多次加载 const timeoutDuration = 10000; // 超时时间10秒 const preLoadDistance = 300; // 距离底部300px时提前加载 // 假设 Authorization 值存储在 localStorage 中,key 为 "authToken" const authToken = localStorage.getItem("Authorization"); let currentUserInfo ; // 获取当前用户登录信息 let currentUserPermissions; // 用于存储用户权限信息 //获取 主内容区域 const license_info_mainElement = document.querySelector('main'); // 主内容区域 //模态框 const license_info_modal = document.getElementById('license-info-modal'); // 模态框容器 const license_info_modalContent = document.querySelector('.license-info-modal-content'); // 模态框内容区域 const license_info_modalDescription = document.getElementById('license-info-modal-description'); // 模态框描述 const license_info_modalPrice = document.getElementById('license-info-modal-price'); // 模态框产品信息 const license_info_modalRating = document.getElementById('license-info-modal-rating'); // 模态框MAC地址 const license_info_closeModal = document.querySelector('.license-info-close'); // 模态框关闭按钮 const license_info_loadingIndicator = document.getElementById('loading-indicator'); // 加载提示元素 //存储 let LicApplicationData = []; // 用于存储从接口获取的数据 // 统一的打开模态框函数 function openModal(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.style.display = "block"; // 显示模态框 } else { console.error('模态框不存在,ID:', modalId); } } // 统一的关闭模态框函数 function closeModal(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.style.display = "none"; // 隐藏模态框 } else { console.error('模态框不存在,ID:', modalId); } } //-----------头部-------------------------------- function setupUserInfoModal(currentUserInfo) { console.log("currentUserInfo,", currentUserInfo); // 获取按钮、模态框和关闭按钮的 DOM 元素 const loginButton = document.querySelector('.login-button'); const loginModal = document.getElementById('loginModal'); const loginModalClose = document.querySelector('.login-modal-close'); const userInfoContainer = document.getElementById('userInfoContainer'); // 设置按钮的显示内容为当前用户的名称 loginButton.textContent = currentUserInfo.Username; // 点击按钮时显示模态框,并将用户信息填充到模态框中 loginButton.addEventListener('click', () => { userInfoContainer.innerHTML = `

用户名: ${currentUserInfo.Username}

邮箱: ${currentUserInfo.Email}

电话: ${currentUserInfo.Telephone}

账号: ${currentUserInfo.Account}

角色: ${currentUserInfo.Role}

`; loginModal.style.display = 'flex'; // 为退出登录按钮绑定点击事件 const logoutButton = document.querySelector('.logout-button'); logoutButton.addEventListener('click', logout); }); // 点击关闭按钮时隐藏模态框 loginModalClose.addEventListener('click', () => { loginModal.style.display = 'none'; }); // 点击模态框外部区域时关闭模态框 window.addEventListener('click', (event) => { if (event.target === loginModal) { loginModal.style.display = 'none'; } }); } // 退出登录函数 function logout() { localStorage.removeItem('Authorization'); window.location.href = '/'; } // 定义检查权限并显示按钮的函数 function checkPermissionsAndShowButton() { console.log("checkPermissionsAndShowButton ", currentUserPermissions); if (currentUserPermissions.includes('capture_license_once_to_db')) { const captureLicenseBtn = document.getElementById('capture-license-btn'); captureLicenseBtn.style.display = 'block'; // 为按钮添加点击事件监听 captureLicenseBtn.addEventListener('click', CaptureLicenseOncefunc); } } // 主动抓取一次License数据函数 function CaptureLicenseOncefunc() { // 显示加载模态框 const loadingModal = document.createElement('div'); loadingModal.classList.add('modal-content', 'apple-modal-content'); loadingModal.innerHTML = `

正在获取 License 信息...

`; document.body.appendChild(loadingModal); // 定义超时函数 const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject(new Error('获取超时')); }, 10000); // 10秒超时 }); showLoadingModal("正在主动获取 OA库 元信息...") // 发起 GET 请求的 Promise const fetchPromise = fetch(`http://${serverIP}:${serverPort}/api/admin/GetCaptureLicenseOnce`, { method: 'GET', headers: { 'Authorization': `Bearer ${authToken}`, // 假设 token 已定义 'Content-Type': 'application/json' } }).then(response => response.json()); // 使用 Promise.race 来竞争两个 Promise,哪个先返回就使用哪个 Promise.race([fetchPromise, timeoutPromise]) .then(data => { // 先关闭进度条 document.body.removeChild(loadingModal); hideLoadingModal(); // 显示成功或失败提示 if (data.success) { alert('License 获取成功!'); } else { alert('获取失败:' + data.error); } }) .catch(error => { // 先关闭进度条 document.body.removeChild(loadingModal); hideLoadingModal(); // 显示错误提示 alert(error.message); // 如果超时或请求失败 }); } //-----------侧边栏---------------------------- // 获取所有菜单项 const menuItems = document.querySelectorAll('nav ul li a'); // 为每个菜单项添加点击事件监听器 menuItems.forEach(item => { item.addEventListener('click', function() { // 移除其他项的 active 类 menuItems.forEach(i => i.classList.remove('active')); // 为当前点击的项添加 active 类 this.classList.add('active'); }); }); //用户管理- //获取用户管理和 License 信息按钮 const userManagementLink = document.getElementById('user-management-link'); const licenseInfoLink = document.getElementById('license-info-link'); const roleManagementLink = document.getElementById('role-management-link'); // 根据用户权限控制菜单显示 function updateMenuVisibility() { console.log("updateMenuVisibility: ",currentUserPermissions); if (currentUserPermissions) { userManagementLink.style.display = currentUserPermissions.includes('read_user') ? 'block' : 'none'; roleManagementLink.style.display = currentUserPermissions.includes('get_role') ? 'block' : 'none'; licenseInfoLink.style.display = (currentUserPermissions.includes('read_license') || currentUserPermissions.includes('read_all_license')) ? 'block' : 'none'; } // 调用函数检查权限并显示按钮 checkPermissionsAndShowButton(); } // 监听用户管理按钮的点击事件 userManagementLink.addEventListener('click', function(event) { event.preventDefault(); // 阻止默认的跳转行为 removeScrollListeners(); // 移除滚动监听器 // 使用 fetch 来加载 user_management.html 的内容 fetch('../user/user_management.html') .then(response => response.text()) .then(data => { // 将 user_management.html 的内容插入到主内容区域 license_info_mainElement.innerHTML = data; // 动态引入 user.js 文件 const script = document.createElement('script'); script.src = '../user/user.js'; document.body.appendChild(script); }) .catch(error => console.error('加载用户管理页面失败:', error)); }); // 监听 License 信息按钮的点击事件 licenseInfoLink.addEventListener('click', function(event) { event.preventDefault(); // 阻止默认的跳转行为 // 创建一个新的 div 元素 const container = document.createElement('div'); // 将瀑布流的 License 信息内容恢复到主内容区域 const licenseInfoHtml = `
`; // 这是原来的 License 信息区域 HTML // 将 licenseInfoHtml 插入到 div 元素中 // container.innerHTML = licenseInfoHtml; // searchBar = container.querySelector('search-bar'); // statusFilter = container.querySelector('license-status-filter'); // startDate = container.querySelector('start-date'); // endDate = container.querySelector('end-date'); // submitButton = container.querySelector('submit-button'); // licenseInfoContainer = container.querySelector('license-info-restaurant-list'); license_info_mainElement.innerHTML = licenseInfoHtml; searchBar = document.getElementById('search-bar'); statusFilter = document.getElementById('license-status-filter'); startDate = document.getElementById('start-date'); endDate = document.getElementById('end-date'); submitButton = document.getElementById('submit-button'); licenseInfoContainer = document.getElementById('license-info-restaurant-list'); //清楚lic信息组的数据 LicApplicationData = []; initializeScrollListeners(); // 重新初始化滚动监听器 // 再次加载 License 信息数据并渲染卡片 (async function() { const data = await fetchLicenseData(1, 10); if (data.length > 0) { console.log('加载的数据:', data); // 检查是否成功获取数据 renderLicenseCards(data, true); // 渲染数据到页面并清空之前的内容 } else { console.error('未加载到数据'); } })(); // 刷新页面 location.reload(); }); roleManagementLink.addEventListener('click', function(event) { event.preventDefault(); // 阻止默认的跳转行为 removeScrollListeners(); // 移除滚动监听器 // 使用 fetch 来加载 user_management.html 的内容 fetch('../role/role.html') .then(response => response.text()) .then(data => { // 将 user_management.html 的内容插入到主内容区域 license_info_mainElement.innerHTML = data; // 动态引入 user.js 文件 const script = document.createElement('script'); script.src = '../role/role.js'; document.body.appendChild(script); }) .catch(error => console.error('加载用户管理页面失败:', error)); }); //-------license数据显示------------------------------------------------------ // 获取数据函数 async function fetchLicenseData(page, pageSize) { try { const response = await fetch(`http://${serverIP}:${serverPort}/api/admin/GetAllLicenseInfo?page=${page}&pageSize=${pageSize}`, { method: 'GET', headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' } }); const result = await response.json(); // 设置总量,如果第一次加载,获取total字段 if (licenseTotal === 0 && result.total) { licenseTotal = result.total; } console.log("result total ",licenseTotal,result.total); // 使用 concat 方法将新数据与之前的数据进行累加 LicApplicationData = LicApplicationData.concat(result.data || []); console.log("LicApplicationData: ",LicApplicationData,licenseTotal,result); return result.data || []; } catch (error) { console.error("加载数据失败", error); return []; // 返回空数组,防止后续操作出错 } } // 渲染 license_info 卡片数据函数 function renderLicenseCards(data, clearContainer = false) { console.log("-----------渲染次数"); // 获取与 license_info 相关的 HTML 元素 const license_info_container = document.getElementById('license-info-restaurant-list'); // 卡片列表容器 if (clearContainer) { license_info_container.innerHTML = ''; // 清空容器内容 isLoading = false; // 重置加载状态 loadedItems = 0; // 重置已加载项数 page = 21; // 每次请求后,page 增加10,表示从下一组数据开始 pageSize = 30; // pageSize 每次递增10 console.log("-----------渲染清除"); } console.log("-----------data:",data); data.forEach(group => { const firstItem = group[0]; // 获取该组的第一个数据项 // 获取子行的数量 const childRowCount = group.length; let statusClass = ''; if (firstItem.LicenseFlage === '已生成') { statusClass = 'license-status-green'; } else if (firstItem.LicenseFlage === '未生成') { statusClass = 'license-status-yellow'; } else if (firstItem.LicenseFlage === '已失效') { statusClass = 'license-status-red'; } /*筛选名字*/ let creatorUser = firstItem.Creator; if (creatorUser.includes('-')) { let firstDashIndex = creatorUser.indexOf('-'); let secondDashIndex = creatorUser.indexOf('-', firstDashIndex + 1); creatorUser = creatorUser.substring(firstDashIndex + 1, secondDashIndex); } const card = document.createElement('div'); card.className = 'license-info-card'; // 给卡片添加一个唯一标识符的 data 属性 card.setAttribute('data-oa-request-id', firstItem.oa_request_id); // 在卡片的第一行显示申请时间 //

oa_request_id:${firstItem.oa_request_id}

card.innerHTML = `

${firstItem.GlxmName}

${firstItem.ApplicationDate} ${firstItem.ApplicationTime}

创建者:${creatorUser}

公司:${firstItem.Company}

集群:${childRowCount} 套 共计:${firstItem.TotalNodes} 节点

许可证状态:${firstItem.LicenseFlage}

`; // 给卡片添加点击事件,点击后显示模态框 card.addEventListener('click', () => { // 传递当前卡片的详细数据到模态框 const oaRequestId = card.getAttribute('data-oa-request-id'); showModalForCard(group, oaRequestId); // 传递 oa_request_id //showModalForCard(group); // 传递当前卡片的详细数据到模态框 }); // 将卡片添加到容器中 license_info_container.appendChild(card); }); } // 检查是否滚动到底部并触发加载 // async function checkAndLoadMore(scrollHeight, scrollTop, clientHeight) { // if (isLoading || loadedItems >= licenseTotal) return; // 如果正在加载或已加载完所有数据则退出 // // console.log(`Scroll Info - scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, clientHeight: ${clientHeight}`); // if (scrollTop + clientHeight >= scrollHeight - preLoadDistance) { // console.log(`触发加载更多数据:page=${page}, pageSize=${pageSize}`); // 每次触发时打印输出 // await loadMoreData(); // } // } // 加载更多数据函数 async function loadMoreData() { if (isLoading) return; // 防止重复加载 isLoading = true; console.log('开始加载更多数据'); // 显示加载提示 // license_info_loadingIndicator.style.display = 'block'; // 显示提示 // license_info_loadingIndicator.innerText = '正在加载...'; // 重置加载提示 // 设置超时处理 const timeout = setTimeout(() => { license_info_loadingIndicator.innerText = '加载超时,请重试'; // 修改提示语为超时提示 isLoading = false; license_info_loadingIndicator.style.display = 'none'; // 超时后隐藏加载提示 }, timeoutDuration); // 获取数据 const data = await fetchLicenseData(page, pageSize); console.log(`加载的新数据 data`,data); // 每次触发时打印输出 // 清除超时定时器 clearTimeout(timeout); if (data.length > 0) { // 更新 page 和 pageSize,下一次请求从新的位置开始 page += 10; // 每次请求后,page 增加10,表示从下一组数据开始 pageSize += 10; // pageSize 每次递增10 // 更新已加载的条目数 loadedItems += data.length; // 渲染数据到页面 renderLicenseCards(data); console.log('数据加载完成,更新页面'); } // 隐藏加载提示 //license_info_loadingIndicator.style.display = 'none'; // 加载完成后隐藏提示 isLoading = false; // 请求完成,允许下次请求 // 检查内容高度,必要时继续加载 //checkContentHeight(); checkAndLoadMore(); } //--------------------------监听 window 滚动---监听 main 容器的滚动----------------------------------------------- // // 监听 window 滚动 // window.addEventListener('scroll', () => { // checkAndLoadMore(document.body.scrollHeight, window.scrollY, window.innerHeight); // }); // // 监听 main 容器的滚动 // license_info_mainElement.addEventListener('scroll', () => { // checkAndLoadMore(license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight); // }); function initializeScrollListeners() { // 只监听 main 容器的滚动 license_info_mainElement.addEventListener('scroll', handleMainScroll); // console.log('滚动监听已初始化'); } function removeScrollListeners() { // 移除 main 容器的滚动监听 license_info_mainElement.removeEventListener('scroll', handleMainScroll); } // 新增一个重启滑动监听功能函数,当用户清空搜索条件时调用 function restartScrollListeners() { // 重新绑定滑动监听器 initializeScrollListeners(); } function handleMainScroll() { // console.log('handleMainScroll', license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight); checkAndLoadMore(license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight); } async function checkAndLoadMore(scrollHeight, scrollTop, clientHeight) { if (isLoading || loadedItems >= licenseTotal) return; // 如果正在加载或已加载完所有数据则退出 // console.log(`Scroll Info - scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, clientHeight: ${clientHeight}`); if (scrollTop + clientHeight >= scrollHeight - preLoadDistance) { console.log(`触发加载更多数据:page=${page}, pageSize=${pageSize}`); // 每次触发时打印输出 await loadMoreData(); } } //----------------------------------------------------------------------------------------- // 初始化加载第一页 (async function() { const data = await fetchLicenseData(1, 20); if (data.length > 0) { renderLicenseCards(data); // 渲染数据到页面 loadedItems += data.length; // 更新已加载的条目数 } //license_info_loadingIndicator.style.display = 'none'; // 初始化后隐藏加载提示 // 检查内容高度 // checkContentHeight(); checkAndLoadMore() })(); //初始化监听滚动条 initializeScrollListeners() ///-----------获取登录用户信息---------------------------------------- async function fetchUsername() { try { const response = await fetch(`http://${serverIP}:${serverPort}/api/admin/userInfo`, { method: 'GET', headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' } }); const data = await response.json(); currentUserRole = data.data.Role; // 存储当前用户的角色 currentUserName = data.data.Username; // 使用获取到的角色,调用获取权限的接口 await fetchPermissionsByRole(currentUserRole); console.log('当前用户角色:', data); currentUserInfo = data.data; // 调用该函数,初始化模态框 setupUserInfoModal(currentUserInfo); updateMenuVisibility(); return data.data; // 返回获取到的用户信息数据 } catch (error) { console.error('Error fetching user info or permissions:', error); } } fetchUsername(); // 调用函数更新菜单可见性 // 将 fetchPermissionsByRole 转换为异步函数 async function fetchPermissionsByRole(role) { try { const response = await fetch(`http://${serverIP}:${serverPort}/api/admin/GetSelfRoles`, { method: 'POST', headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: role }) }); const data = await response.json(); currentUserPermissions = data.data.Permissions; // 获取用户的权限数组 console.log('currentUserPermissions:', currentUserPermissions); // 检查用户是否有读取许可证的权限 const hasReadLicensePermission = currentUserPermissions.includes("read_license"); const hasReadLicenseAllPermission = currentUserPermissions.includes("read_all_license"); const hasReadUserPermission = currentUserPermissions.includes("read_user"); const hasReadRolePermission = currentUserPermissions.includes("get_role"); if (!hasReadLicensePermission || !hasReadLicenseAllPermission) { if (hasReadRolePermission) { document.getElementById('role-management-link').click(); }else if (hasReadUserPermission){ document.getElementById('user-management-link').click(); } } // if (hasReadLicensePermission || hasReadLicenseAllPermission) { // document.getElementById('license-info-link').click(); // }else if (hasReadRolePermission) {// 根据权限触发相应的按钮点击事件 // // 如果没有读取许可证的权限,则触发角色管理按钮的点击事件 // document.getElementById('role-management-link').click(); // } else if ( hasReadUserPermission) { // // 如果有读取许可证的权限,则触发用户管理按钮的点击事件 // document.getElementById('user-management-link').click(); // } // if (hasReadRolePermission) {// 根据权限触发相应的按钮点击事件 // // 如果没有读取许可证的权限,则触发角色管理按钮的点击事件 // document.getElementById('role-management-link').click(); // } else if ( hasReadUserPermission) { // // 如果有读取许可证的权限,则触发用户管理按钮的点击事件 // document.getElementById('user-management-link').click(); // } // 定义权限类别 // const licensePermissions = ['upload_license', 'read_license']; // const userPermissionsCheck = ['create_user', 'read_user', 'update_user', 'delete_user']; // const rolePermissions = ['create_role', 'delete_role', 'update_role', 'get_role']; // const hasLicenseAccess = licensePermissions.some(permission => userPermissions.includes(permission)); // const hasUserManagementAccess = userPermissionsCheck.some(permission => userPermissions.includes(permission)); // const hasRoleManagementAccess = rolePermissions.some(permission => userPermissions.includes(permission)); // 根据权限渲染菜单并显示初始页面 //renderMenuAndInitialPage(hasLicenseAccess, hasUserManagementAccess, hasRoleManagementAccess); } catch (error) { console.error('Error fetching permissions:', error); } } //--------------进度条------------------------------------------------- // 创建模态框的 DOM 元素并插入到 body 中 function createLoadingModal() { const modalHTML = ` `; document.body.insertAdjacentHTML('beforeend', modalHTML); } // 显示加载模态框 function showLoadingModal(message = "加载中...") { const loadingModal = document.getElementById('loadingModal'); const loadingMessage = document.getElementById('loadingMessage'); if (loadingModal && loadingMessage) { loadingMessage.textContent = message; // 设置显示的消息 loadingModal.style.display = 'flex'; // 显示模态框 } } // 隐藏加载模态框 function hideLoadingModal() { const loadingModal = document.getElementById('loadingModal'); if (loadingModal) { loadingModal.style.display = 'none'; // 隐藏模态框 } } // 页面加载时创建模态框 document.addEventListener('DOMContentLoaded', createLoadingModal); //-----------搜索栏---------------------------- // 获取搜索框元素 // 获取搜索框、状态下拉框、时间选择框和按钮元素 // 获取搜索框、状态下拉框、时间选择框和按钮元素 let searchBar = document.getElementById('search-bar'); let statusFilter = document.getElementById('license-status-filter'); let startDate = document.getElementById('start-date'); let endDate = document.getElementById('end-date'); let submitButton = document.getElementById('submit-button'); let licenseInfoContainer = document.getElementById('license-info-restaurant-list'); // 过滤功能实现 function filterContent() { console.log('过滤功能触发'); // 移除滚动监听器,停止滚动加载 // removeScrollListeners(); console.log('statusFilter.valuesdaad撒大啊', statusFilter.value,startDate.value ,endDate.value,searchBar.value ); // 检查如果所有输入框都是默认值,则直接返回,不发送数据 if (!statusFilter.value && !startDate.value && !endDate.value && !searchBar.value) { console.log("所有过滤条件为空,不发送请求"); return; // 不发送请求 } // 构建请求体参数 const requestData = { license_flag: statusFilter.value || undefined, starting_date: startDate.value || undefined, end_date: endDate.value || undefined, any_search: searchBar.value || undefined, }; console.log("requestData",requestData); // 发送 POST 请求到接口 fetch(`http://${serverIP}:${serverPort}/api/admin/GetConditionalSearch`, { method: 'POST', headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify(requestData), }) .then(response => response.json()) .then(data => { console.log('成功获取数据:', data); // 处理返回的数据并更新界面 displayLicenseInfo(data.data); }) .catch(error => { console.error('获取数据时发生错误:', error); }); } // 处理并显示返回的 License 信息 function displayLicenseInfo(data) { // 清空之前的结果 licenseInfoContainer.innerHTML = ''; LicApplicationData =[]; // 遍历返回的数据,生成并插入卡片 // 处理返回的数据并更新界面,使用 renderLicenseCards 方法进行渲染 renderLicenseCards(data, true); } // 确定按钮点击事件的修改(停止滚动监听) submitButton.addEventListener('click', function() { console.log('确定按钮点击事件触发'); // 检查下拉框和时间选择框是否为默认值 if (!statusFilter.value && !startDate.value && !endDate.value) { // 如果都是默认值,则刷新页面 location.reload(); } else { // 否则,执行过滤内容功能 filterContent(); // 隐藏滚动加载,防止继续加载更多内容 removeScrollListeners(); } }); // 监听返回按钮的点击事件,刷新页面并恢复滚动监听 const resetButton = document.getElementById('reset-button'); resetButton.addEventListener('click', function() { // 刷新页面 location.reload(); }); // 修改当搜索栏没有输入时,重新启动滚动监听 searchBar.addEventListener('input', function() { if (!searchBar.value && !statusFilter.value && !startDate.value && !endDate.value) { console.log("搜索条件清空,重新启动滚动监听"); restartScrollListeners(); } });