license_info.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. // 全局变量定义
  2. let page = 11; // 初始页码为1,代表从第1条数据开始获取
  3. let pageSize = 20; // 初始每次固定获取10条数据
  4. let total = 0; // 数据总量(从接口获取)
  5. let loadedItems = 0; // 已加载的数据条目数量
  6. let isLoading = false; // 防止多次加载
  7. const timeoutDuration = 10000; // 超时时间10秒
  8. const preLoadDistance = 300; // 距离底部300px时提前加载
  9. // 假设 Authorization 值存储在 localStorage 中,key 为 "authToken"
  10. const authToken = localStorage.getItem("Authorization");
  11. const currentUserInfo = fetchUsername(); // 获取当前用户登录信息
  12. let currentUserPermissions; // 用于存储用户权限信息
  13. //获取 主内容区域
  14. const license_info_mainElement = document.querySelector('main'); // 主内容区域
  15. //模态框
  16. const license_info_modal = document.getElementById('license-info-modal'); // 模态框容器
  17. const license_info_modalContent = document.querySelector('.license-info-modal-content'); // 模态框内容区域
  18. const license_info_modalDescription = document.getElementById('license-info-modal-description'); // 模态框描述
  19. const license_info_modalPrice = document.getElementById('license-info-modal-price'); // 模态框产品信息
  20. const license_info_modalRating = document.getElementById('license-info-modal-rating'); // 模态框MAC地址
  21. const license_info_closeModal = document.querySelector('.license-info-close'); // 模态框关闭按钮
  22. const license_info_loadingIndicator = document.getElementById('loading-indicator'); // 加载提示元素
  23. //存储
  24. let LicApplicationData = []; // 用于存储从接口获取的数据
  25. // 统一的打开模态框函数
  26. function openModal(modalId) {
  27. const modal = document.getElementById(modalId);
  28. if (modal) {
  29. modal.style.display = "block"; // 显示模态框
  30. } else {
  31. console.error('模态框不存在,ID:', modalId);
  32. }
  33. }
  34. // 统一的关闭模态框函数
  35. function closeModal(modalId) {
  36. const modal = document.getElementById(modalId);
  37. if (modal) {
  38. modal.style.display = "none"; // 隐藏模态框
  39. } else {
  40. console.error('模态框不存在,ID:', modalId);
  41. }
  42. }
  43. //-----------侧边栏----------------------------
  44. // 获取所有菜单项
  45. const menuItems = document.querySelectorAll('nav ul li a');
  46. // 为每个菜单项添加点击事件监听器
  47. menuItems.forEach(item => {
  48. item.addEventListener('click', function() {
  49. // 移除其他项的 active 类
  50. menuItems.forEach(i => i.classList.remove('active'));
  51. // 为当前点击的项添加 active 类
  52. this.classList.add('active');
  53. });
  54. });
  55. //用户管理-
  56. //获取用户管理和 License 信息按钮
  57. const userManagementLink = document.getElementById('user-management-link');
  58. const licenseInfoLink = document.getElementById('license-info-link');
  59. const roleManagementLink = document.getElementById('role-management-link');
  60. // 监听用户管理按钮的点击事件
  61. userManagementLink.addEventListener('click', function(event) {
  62. event.preventDefault(); // 阻止默认的跳转行为
  63. removeScrollListeners(); // 移除滚动监听器
  64. // 使用 fetch 来加载 user_management.html 的内容
  65. fetch('../user/user_management.html')
  66. .then(response => response.text())
  67. .then(data => {
  68. // 将 user_management.html 的内容插入到主内容区域
  69. license_info_mainElement.innerHTML = data;
  70. // 动态引入 user.js 文件
  71. const script = document.createElement('script');
  72. script.src = '../user/user.js';
  73. document.body.appendChild(script);
  74. })
  75. .catch(error => console.error('加载用户管理页面失败:', error));
  76. });
  77. // 监听 License 信息按钮的点击事件
  78. licenseInfoLink.addEventListener('click', function(event) {
  79. event.preventDefault(); // 阻止默认的跳转行为
  80. // 将瀑布流的 License 信息内容恢复到主内容区域
  81. const licenseInfoHtml = `
  82. <!-- 包裹搜索框、下拉框、时间选择框和确定按钮的 div -->
  83. <div class="search-container">
  84. <!-- License 状态下拉框 -->
  85. <select id="license-status-filter" aria-label="选择 License 状态">
  86. <option value="">License 状态</option>
  87. <option value="已生成">已生成</option>
  88. <option value="未生成">未生成</option>
  89. <option value="已失效">已失效</option>
  90. </select>
  91. <!-- 开始时间选择框,类型改为 date -->
  92. <input type="date" id="start-date" placeholder="开始时间" />
  93. <!-- 结束时间选择框,类型改为 date -->
  94. <input type="date" id="end-date" placeholder="结束时间" />
  95. <!-- 搜索框 -->
  96. <input type="text" id="search-bar" placeholder="搜索..." />
  97. <!-- 确定按钮 -->
  98. <button id="submit-button">确定</button>
  99. </div>
  100. <div class="license-info-container" id="license-info-restaurant-list"> </div>
  101. `; // 这是原来的 License 信息区域 HTML
  102. //mainContainer.innerHTML = licenseInfoHtml;
  103. license_info_mainElement.innerHTML = licenseInfoHtml;
  104. //清楚lic信息组的数据
  105. LicApplicationData = [];
  106. initializeScrollListeners(); // 重新初始化滚动监听器
  107. // 再次加载 License 信息数据并渲染卡片
  108. (async function() {
  109. const data = await fetchLicenseData(1, 10);
  110. if (data.length > 0) {
  111. console.log('加载的数据:', data); // 检查是否成功获取数据
  112. renderLicenseCards(data, true); // 渲染数据到页面并清空之前的内容
  113. } else {
  114. console.error('未加载到数据');
  115. }
  116. })();
  117. });
  118. roleManagementLink.addEventListener('click', function(event) {
  119. event.preventDefault(); // 阻止默认的跳转行为
  120. removeScrollListeners(); // 移除滚动监听器
  121. // 使用 fetch 来加载 user_management.html 的内容
  122. fetch('../role/role.html')
  123. .then(response => response.text())
  124. .then(data => {
  125. // 将 user_management.html 的内容插入到主内容区域
  126. license_info_mainElement.innerHTML = data;
  127. // 动态引入 user.js 文件
  128. const script = document.createElement('script');
  129. script.src = '../role/role.js';
  130. document.body.appendChild(script);
  131. })
  132. .catch(error => console.error('加载用户管理页面失败:', error));
  133. });
  134. //-------license数据显示------------------------------------------------------
  135. // 获取数据函数
  136. async function fetchLicenseData(page, pageSize) {
  137. try {
  138. const response = await fetch(`http://127.0.0.1:8080/api/admin/GetAllLicenseInfo?page=${page}&pageSize=${pageSize}`, {
  139. method: 'GET',
  140. headers: {
  141. 'Authorization': `Bearer ${authToken}`,
  142. 'Content-Type': 'application/json'
  143. }
  144. });
  145. const result = await response.json();
  146. // 设置总量,如果第一次加载,获取total字段
  147. if (total === 0 && result.total) {
  148. total = result.total;
  149. }
  150. // 使用 concat 方法将新数据与之前的数据进行累加
  151. LicApplicationData = LicApplicationData.concat(result.data || []);
  152. console.log("LicApplicationData: ",LicApplicationData);
  153. return result.data || [];
  154. } catch (error) {
  155. console.error("加载数据失败", error);
  156. return []; // 返回空数组,防止后续操作出错
  157. }
  158. }
  159. // 渲染 license_info 卡片数据函数
  160. function renderLicenseCards(data, clearContainer = false) {
  161. console.log("-----------渲染次数");
  162. // 获取与 license_info 相关的 HTML 元素
  163. const license_info_container = document.getElementById('license-info-restaurant-list'); // 卡片列表容器
  164. if (clearContainer) {
  165. license_info_container.innerHTML = ''; // 清空容器内容
  166. isLoading = false; // 重置加载状态
  167. loadedItems = 0; // 重置已加载项数
  168. page = 11; // 每次请求后,page 增加10,表示从下一组数据开始
  169. pageSize = 20; // pageSize 每次递增10
  170. console.log("-----------渲染清除");
  171. }
  172. console.log("-----------data:",data);
  173. data.forEach(group => {
  174. const firstItem = group[0]; // 获取该组的第一个数据项
  175. // 获取子行的数量
  176. const childRowCount = group.length;
  177. let statusClass = '';
  178. if (firstItem.LicenseFlage === '已生成') {
  179. statusClass = 'license-status-green';
  180. } else if (firstItem.LicenseFlage === '未生成') {
  181. statusClass = 'license-status-yellow';
  182. } else if (firstItem.LicenseFlage === '已失效') {
  183. statusClass = 'license-status-red';
  184. }
  185. const card = document.createElement('div');
  186. card.className = 'license-info-card';
  187. // 给卡片添加一个唯一标识符的 data 属性
  188. card.setAttribute('data-oa-request-id', firstItem.oa_request_id);
  189. // 在卡片的第一行显示申请时间
  190. card.innerHTML = `
  191. <div class="license-info-card-header">
  192. <h3 class="card-title">${firstItem.GlxmName}</h3>
  193. </div>
  194. <div class="license-info-card-content">
  195. <p class="card-text">${firstItem.ApplicationDate} ${firstItem.ApplicationTime}</p> <!-- 显示日期和时间 -->
  196. <p class="card-text">创建者:${firstItem.Creator}</p>
  197. <p class="card-text">公司:${firstItem.Company}</p>
  198. <p class="card-text">集群:${childRowCount} 套 共计:${firstItem.TotalNodes} 节点</p>
  199. <p class="card-text license-status ${statusClass}">许可证状态:${firstItem.LicenseFlage}</p>
  200. <p class="card-text">oa_request_id:${firstItem.oa_request_id}</p>
  201. </div>
  202. `;
  203. // 给卡片添加点击事件,点击后显示模态框
  204. card.addEventListener('click', () => {
  205. // 传递当前卡片的详细数据到模态框
  206. const oaRequestId = card.getAttribute('data-oa-request-id');
  207. showModalForCard(group, oaRequestId); // 传递 oa_request_id
  208. //showModalForCard(group); // 传递当前卡片的详细数据到模态框
  209. });
  210. // 将卡片添加到容器中
  211. license_info_container.appendChild(card);
  212. });
  213. }
  214. // 检查是否滚动到底部并触发加载
  215. // async function checkAndLoadMore(scrollHeight, scrollTop, clientHeight) {
  216. // if (isLoading || loadedItems >= total) return; // 如果正在加载或已加载完所有数据则退出
  217. // // console.log(`Scroll Info - scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, clientHeight: ${clientHeight}`);
  218. // if (scrollTop + clientHeight >= scrollHeight - preLoadDistance) {
  219. // console.log(`触发加载更多数据:page=${page}, pageSize=${pageSize}`); // 每次触发时打印输出
  220. // await loadMoreData();
  221. // }
  222. // }
  223. // 加载更多数据函数
  224. async function loadMoreData() {
  225. if (isLoading) return; // 防止重复加载
  226. isLoading = true;
  227. console.log('开始加载更多数据');
  228. // 显示加载提示
  229. // license_info_loadingIndicator.style.display = 'block'; // 显示提示
  230. // license_info_loadingIndicator.innerText = '正在加载...'; // 重置加载提示
  231. // 设置超时处理
  232. const timeout = setTimeout(() => {
  233. license_info_loadingIndicator.innerText = '加载超时,请重试'; // 修改提示语为超时提示
  234. isLoading = false;
  235. license_info_loadingIndicator.style.display = 'none'; // 超时后隐藏加载提示
  236. }, timeoutDuration);
  237. // 获取数据
  238. const data = await fetchLicenseData(page, pageSize);
  239. console.log(`加载的新数据 data`,data); // 每次触发时打印输出
  240. // 清除超时定时器
  241. clearTimeout(timeout);
  242. if (data.length > 0) {
  243. // 更新 page 和 pageSize,下一次请求从新的位置开始
  244. page += 10; // 每次请求后,page 增加10,表示从下一组数据开始
  245. pageSize += 10; // pageSize 每次递增10
  246. // 更新已加载的条目数
  247. loadedItems += data.length;
  248. // 渲染数据到页面
  249. renderLicenseCards(data);
  250. console.log('数据加载完成,更新页面');
  251. }
  252. // 隐藏加载提示
  253. //license_info_loadingIndicator.style.display = 'none'; // 加载完成后隐藏提示
  254. isLoading = false; // 请求完成,允许下次请求
  255. // 检查内容高度,必要时继续加载
  256. //checkContentHeight();
  257. checkAndLoadMore();
  258. }
  259. //--------------------------监听 window 滚动---监听 main 容器的滚动-----------------------------------------------
  260. // // 监听 window 滚动
  261. // window.addEventListener('scroll', () => {
  262. // checkAndLoadMore(document.body.scrollHeight, window.scrollY, window.innerHeight);
  263. // });
  264. // // 监听 main 容器的滚动
  265. // license_info_mainElement.addEventListener('scroll', () => {
  266. // checkAndLoadMore(license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight);
  267. // });
  268. function initializeScrollListeners() {
  269. // 只监听 main 容器的滚动
  270. license_info_mainElement.addEventListener('scroll', handleMainScroll);
  271. // console.log('滚动监听已初始化');
  272. }
  273. function removeScrollListeners() {
  274. // 移除 main 容器的滚动监听
  275. license_info_mainElement.removeEventListener('scroll', handleMainScroll);
  276. }
  277. // 新增一个重启滑动监听功能函数,当用户清空搜索条件时调用
  278. function restartScrollListeners() {
  279. // 重新绑定滑动监听器
  280. initializeScrollListeners();
  281. }
  282. function handleMainScroll() {
  283. // console.log('handleMainScroll', license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight);
  284. checkAndLoadMore(license_info_mainElement.scrollHeight, license_info_mainElement.scrollTop, license_info_mainElement.clientHeight);
  285. }
  286. async function checkAndLoadMore(scrollHeight, scrollTop, clientHeight) {
  287. if (isLoading || loadedItems >= total) return; // 如果正在加载或已加载完所有数据则退出
  288. // console.log(`Scroll Info - scrollHeight: ${scrollHeight}, scrollTop: ${scrollTop}, clientHeight: ${clientHeight}`);
  289. if (scrollTop + clientHeight >= scrollHeight - preLoadDistance) {
  290. console.log(`触发加载更多数据:page=${page}, pageSize=${pageSize}`); // 每次触发时打印输出
  291. await loadMoreData();
  292. }
  293. }
  294. //-----------------------------------------------------------------------------------------
  295. // 初始化加载第一页
  296. (async function() {
  297. const data = await fetchLicenseData(1, 10);
  298. if (data.length > 0) {
  299. renderLicenseCards(data); // 渲染数据到页面
  300. loadedItems += data.length; // 更新已加载的条目数
  301. }
  302. //license_info_loadingIndicator.style.display = 'none'; // 初始化后隐藏加载提示
  303. // 检查内容高度
  304. // checkContentHeight();
  305. checkAndLoadMore()
  306. })();
  307. //初始化监听滚动条
  308. initializeScrollListeners()
  309. //-----------点击卡片弹出模态框------------------------------------------------------
  310. // 模态框显示函数
  311. // 模态框显示函数
  312. function showModalForCard(item,oaRequestId) {
  313. const modal = document.getElementById('license-info-modal');
  314. const modalContent = document.querySelector('.license-info-modal-content');
  315. const modalBody = document.getElementById('license-info-modal-body'); // 获取下半部分容器
  316. console.log(`当前点击的卡片 ID: ${oaRequestId}`);
  317. // 设置分页相关的变量
  318. let currentPage = 1;
  319. const itemsPerPage = 3; // 每页显示两组
  320. // 对 item 数组按 oa_id 进行升序排序
  321. const sortedItem = item.sort((a, b) => a.oa_id - b.oa_id);
  322. const totalPages = Math.ceil(sortedItem.length / itemsPerPage); // 计算总页数
  323. // 获取分页容器
  324. const paginationContainer = document.querySelector('.license-info-modal-pagination');
  325. // 清空分页容器,避免重复创建元素
  326. paginationContainer.innerHTML = '';
  327. // 创建"上一页"按钮
  328. const prevButton = document.createElement('button');
  329. prevButton.classList.add('prev-page');
  330. prevButton.innerText = '上一页';
  331. paginationContainer.appendChild(prevButton);
  332. // 创建下拉框
  333. const selectPageDropdown = document.createElement('select');
  334. paginationContainer.appendChild(selectPageDropdown);
  335. // 创建"下一页"按钮
  336. const nextButton = document.createElement('button');
  337. nextButton.classList.add('next-page');
  338. nextButton.innerText = '下一页';
  339. paginationContainer.appendChild(nextButton);
  340. // 初始化上半部分内容(Company, Creator, ApplicationDate, ApplicationTime 和两个按钮)
  341. function initializeHeaderContent(firstItem,sortedItem) {
  342. console.log("initializeHeaderContent"); // 检查是否找到按钮
  343. // 清空上半部分内容
  344. const modalHeader = document.querySelector('.license-info-modal-header');
  345. modalHeader.innerHTML = ''; // 确保不会重复创建
  346. let statusClass = '';
  347. if (firstItem.LicenseFlage === '已生成') {
  348. statusClass = 'license-status-green';
  349. } else if (firstItem.LicenseFlage === '未生成') {
  350. statusClass = 'license-status-yellow';
  351. } else if (firstItem.LicenseFlage === '已失效') {
  352. statusClass = 'license-status-red';
  353. }
  354. // 检查当前用户是否有权限生成或分发
  355. const hasGeneratePermission = currentUserPermissions.includes('generate_license');
  356. const hasDispatchPermission = currentUserPermissions.includes('dispat_license');
  357. console.log(`当前用户是否有生成权限: ${hasGeneratePermission}, ${hasDispatchPermission}`);
  358. // 设置卡片内容
  359. // 修改后的卡片内容部分代码
  360. modalHeader.innerHTML = `
  361. <div class="license-info-card-header">
  362. <h3 class="card-title">${firstItem.GlxmName}</h3>
  363. </div>
  364. <div class="license-info-card-content">
  365. <p class="card-text">${firstItem.ApplicationDate} ${firstItem.ApplicationTime}</p> <!-- 显示日期和时间 -->
  366. <p class="card-text">公司:${firstItem.Company}</p>
  367. <p class="card-text">${firstItem.Project}</p>
  368. <p class="card-text">创建者:${firstItem.Creator}</p>
  369. <p class="card-text license-status ${statusClass}">许可证状态:${firstItem.LicenseFlage}</p>
  370. <div class="license-info-card-buttons">
  371. ${
  372. firstItem.LicenseFlage === '已生成' && hasDispatchPermission
  373. ? `<button class="license-info-modal-button" id="distributeButton">分发</button>`
  374. : `<button class="license-info-modal-button" id="distributeButton" disabled style="background-color:#ccc;cursor:not-allowed;">分发</button>`
  375. }
  376. ${
  377. firstItem.LicenseFlage !== '已生成' && hasGeneratePermission
  378. ? `<button class="license-info-modal-button" id="generateOrDistribute">生成</button>`
  379. : ''
  380. }
  381. <button class="license-info-modal-button" id="downloadAllLicenses-button">打包下载所有license.dat</button>
  382. <button id="viewDistributionHistory-button">查看分发历史</button>
  383. </div>
  384. </div>
  385. `;
  386. // 绑定 generateOrDistribute 的点击事件(如果按钮存在)
  387. const generateOrDistribute = modalHeader.querySelector('#generateOrDistribute');
  388. if (generateOrDistribute) {
  389. generateOrDistribute.addEventListener('click', () => {
  390. if (firstItem.LicenseFlage === '已生成') {
  391. // 执行分发逻辑
  392. showDistributeModal(firstItem);
  393. } else {
  394. // 执行生成逻辑
  395. const oaRequestID = parseInt(firstItem.oa_request_id, 10); // 10 表示10进制
  396. generateLicense(oaRequestID, true);
  397. }
  398. console.log('Button 1 clicked');
  399. });
  400. };
  401. // 绑定分发按钮的点击事件
  402. const distributeButton = modalHeader.querySelector('#distributeButton');
  403. if (distributeButton && !distributeButton.disabled) {
  404. distributeButton.addEventListener('click', () => {
  405. showDistributeModal(firstItem);
  406. });
  407. }
  408. // // 在生成或分发按钮点击时,调用 showDistributeModal 函数
  409. // generateOrDistribute.addEventListener('click', () => {
  410. // if (firstItem.LicenseFlage === '已生成') {
  411. // showDistributeModal(firstItem); // 显示分发模态框
  412. // } else {
  413. // const oaRequestID = parseInt(firstItem.oa_request_id, 10); // 生成许可证
  414. // generateLicense(oaRequestID, true);
  415. // }
  416. // });
  417. // 绑定 "打包下载所有license.dat" 按钮的点击事件
  418. const downloadButton = modalHeader.querySelector('#downloadAllLicenses-button');
  419. // 如果 LicenseFlage 是 "未生成" 或 "已失效",按钮变灰且不可点击
  420. if (firstItem.LicenseFlage === '未生成' || firstItem.LicenseFlage === '已失效') {
  421. downloadButton.disabled = true;
  422. downloadButton.style.backgroundColor = '#ccc'; // 设置为灰色
  423. downloadButton.style.cursor = 'not-allowed'; // 修改鼠标样式
  424. } else {
  425. // 只有当 LicenseFlage 是 "已生成" 时,才能点击下载按钮
  426. downloadButton.addEventListener('click', () => {
  427. downloadAllLicenses(sortedItem);
  428. });
  429. }
  430. // 在初始化完成后绑定 "查看分发历史" 按钮的点击事件
  431. const viewDistributionHistoryButton = document.getElementById('viewDistributionHistory-button');
  432. if (viewDistributionHistoryButton) {
  433. viewDistributionHistoryButton.addEventListener('click', () => {
  434. showDistributionHistory(firstItem);
  435. });
  436. }
  437. }
  438. // 初始化下拉框的页码选项
  439. function initializeDropdown() {
  440. selectPageDropdown.innerHTML = ''; // 清空下拉框中的选项
  441. for (let page = 1; page <= totalPages; page++) {
  442. const option = document.createElement('option');
  443. option.value = page;
  444. option.innerText = `第 ${page} 页`;
  445. selectPageDropdown.appendChild(option);
  446. }
  447. selectPageDropdown.value = currentPage; // 设置默认选项为当前页
  448. }
  449. // 渲染当前页内容
  450. function ModalForCardRenderPage(page) {
  451. modalBody.innerHTML = ''; // 清空之前的内容
  452. // 计算当前页的起始和结束索引
  453. const startIndex = (page - 1) * itemsPerPage;
  454. const endIndex = Math.min(startIndex + itemsPerPage, sortedItem.length);
  455. // 更新上半部分的字段内容 (以第一个元素为例)
  456. const firstItem = sortedItem[0];
  457. initializeHeaderContent(firstItem,sortedItem); // 动态生成上半部分内容
  458. // 遍历当前页的数据
  459. for (let i = startIndex; i < endIndex; i++) {
  460. const group = sortedItem[i];
  461. const groupBox = document.createElement('div');
  462. groupBox.classList.add('license-info-group-box');
  463. // 动态生成组内容,显示编号为 i+1(表示组1, 组2...)
  464. groupBox.innerHTML = `
  465. <div class="license-info-group-title">集群 ${i + 1} :</div>
  466. <p><strong>节点数:</strong> ${group.NodeCount}</p>
  467. <p><strong>数据库版本: </strong> ${group.ProductName}${group.ProductVersion}</p>
  468. <p><strong>CPU 型号:</strong> ${group.oa_cpu}</p>
  469. <p><strong>操作系统环境:</strong> ${group.oa_operating_system}</p>
  470. <p><strong>以下为测试显示:</strong> </p>
  471. <p><strong>oa_id:</strong> ${group.oa_id}</p>
  472. <p><strong>oa_request_id:</strong> ${group.oa_request_id}</p>
  473. `;
  474. // 将生成的组内容加入到 modalBody
  475. modalBody.appendChild(groupBox);
  476. }
  477. // 更新下拉框的值
  478. selectPageDropdown.value = page;
  479. // 更新按钮状态
  480. prevButton.disabled = (page === 1);
  481. nextButton.disabled = (page === totalPages);
  482. }
  483. // 下拉框页码选择事件
  484. selectPageDropdown.addEventListener('change', function() {
  485. currentPage = parseInt(this.value);
  486. ModalForCardRenderPage(currentPage); // 根据选择的页码渲染对应页面
  487. });
  488. // 上一页按钮点击事件
  489. prevButton.addEventListener('click', function() {
  490. if (currentPage > 1) {
  491. currentPage--;
  492. ModalForCardRenderPage(currentPage);
  493. }
  494. });
  495. // 下一页按钮点击事件
  496. nextButton.addEventListener('click', function() {
  497. if (currentPage < totalPages) {
  498. currentPage++;
  499. ModalForCardRenderPage(currentPage);
  500. }
  501. });
  502. // 显示或隐藏分页相关控件
  503. function togglePaginationVisibility() {
  504. if (totalPages <= 1) {
  505. // 隐藏下拉框和分页容器
  506. paginationContainer.style.display = 'none';
  507. } else {
  508. // 显示下拉框和分页容器
  509. paginationContainer.style.display = 'flex';
  510. }
  511. }
  512. // 初始化下拉框并渲染第一页
  513. initializeDropdown();
  514. // 渲染模态框内容
  515. ModalForCardRenderPage(currentPage);
  516. // 根据页数决定是否显示分页控件
  517. togglePaginationVisibility();
  518. // 显示模态框
  519. modal.style.display = 'flex'; // 显示模态框背景
  520. setTimeout(() => {
  521. modalContent.classList.add('show'); // 添加动画效果
  522. }, 10); // 延时确保动画生效
  523. // 关闭模态框逻辑
  524. const closeModal = document.querySelector('.license-info-close');
  525. closeModal.addEventListener('click', () => {
  526. modalContent.classList.remove('show'); // 移除动画类
  527. setTimeout(() => {
  528. modal.style.display = 'none'; // 完全隐藏模态框
  529. }, 500); // 等待动画结束后再隐藏
  530. });
  531. // 点击模态框外部关闭模态框
  532. window.addEventListener('click', (event) => {
  533. if (event.target === modal) {
  534. modalContent.classList.remove('show');
  535. setTimeout(() => {
  536. modal.style.display = 'none'; // 完全隐藏模态框
  537. }, 500); // 等待动画结束后再隐藏
  538. }
  539. });
  540. }
  541. //-------下载全部licstr按钮
  542. // 下载许可证功能
  543. function downloadAllLicenses(sortedApplicationArray) {
  544. const zip = new JSZip();
  545. console.log("传进来的 sortedApplicationArray:", sortedApplicationArray);
  546. // 初始化计数器,从1开始
  547. let idCounter = 1;
  548. let Project = sortedApplicationArray[0].Project;
  549. console.log("Project", Project);
  550. // 遍历 sortedApplicationArray,下载 lic1 和 lic2 数据
  551. sortedApplicationArray.forEach(row => {
  552. if (row.LicenseFlage === "已生成") {
  553. // 替换 oa_main_mac 和 oa_second_mac 中的冒号为点
  554. const mainMac = row.oa_main_mac.replace(/:/g, '.');
  555. const secondMac = row.oa_second_mac.replace(/:/g, '.');
  556. // 使用递增的 idCounter 替换 row.oa_id
  557. if (row.lic1) {
  558. const filename1 = `${idCounter}_license.dat_1_${mainMac}`;
  559. zip.file(filename1, row.lic1);
  560. }
  561. if (row.lic2) {
  562. const filename2 = `${idCounter}_license.dat_2_${secondMac}`;
  563. zip.file(filename2, row.lic2);
  564. }
  565. // 每次循环后递增计数器
  566. idCounter++;
  567. }
  568. });
  569. // 生成 ZIP 文件并触发下载
  570. zip.generateAsync({ type: "blob" }).then(content => {
  571. const link = document.createElement('a');
  572. link.href = URL.createObjectURL(content);
  573. link.download = `${Project}_license.zip`;
  574. link.click();
  575. });
  576. }
  577. // 刷新数据并滚动到目标卡片的函数
  578. // 刷新数据并滚动到目标卡片,同时重新打开目标卡片的模态框
  579. async function refreshLicenseDataAndScrollAndOpenModal(selfPage,selfPageSize, targetCardId) {
  580. const data = await fetchLicenseData(selfPage, selfPageSize);
  581. if (data.length > 0) {
  582. isLoading = true;
  583. console.log('加载的数据:', data); // 检查是否成功获取数据
  584. renderLicenseCards(data, true); // 渲染数据到页面并清空之前的内容
  585. page = selfPageSize+1;
  586. pageSize= selfPageSize +10;
  587. // 滚动到目标卡片
  588. if (targetCardId) {
  589. const targetCard = document.querySelector(`[data-oa-request-id="${targetCardId}"]`);
  590. if (targetCard) {
  591. targetCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
  592. // 延迟打开模态框,确保页面滚动完成
  593. setTimeout(() => {
  594. targetCard.click(); // 模拟点击卡片,触发模态框
  595. }, 500); // 延时500ms确保滚动完成
  596. }
  597. }
  598. setTimeout(() => {
  599. isLoading = false;
  600. }, 2000);
  601. } else {
  602. console.error('未加载到数据');
  603. }
  604. }
  605. function generateLicense(id, isParentRow) {
  606. // 显示加载进度条并设置动态提示信息
  607. showLoadingModal('正在生成 License...');
  608. // const payload = isParentRow ? { oa_request_id: JSON.stringify(id) } : { uniqueID:JSON.stringify(id) };
  609. const payload = isParentRow
  610. ? { oa_request_id: parseInt(id, 10) } // 将 id 转换为整数
  611. : { uniqueID: parseInt(id, 10) }; // 将 id 转换为整数
  612. console.log("generateLicense",payload ,id, isParentRow)
  613. fetch('http://127.0.0.1:8080/api/admin/GenerateLicense', {
  614. method: 'POST',
  615. headers: {
  616. 'Authorization': `Bearer ${authToken}`,
  617. 'Content-Type': 'application/json'
  618. },
  619. body: JSON.stringify(payload)
  620. })
  621. .then(response => response.json())
  622. .then(data => {
  623. if (data.success) {
  624. // 隐藏加载进度条
  625. hideLoadingModal();
  626. alert('License 生成成功!');
  627. //刷新页面
  628. // 调用封装的更新方法
  629. //updateCardAndModalStatus(id, isParentRow);
  630. // 调用刷新函数,传入当前的 page 和 pageSize
  631. refreshLicenseDataAndScrollAndOpenModal(1,pageSize,id);
  632. } else {
  633. // 请求失败时隐藏加载进度条
  634. hideLoadingModal();
  635. alert('License 生成失败:' + data.error);
  636. }
  637. })
  638. .catch(error => {
  639. console.error('生成过程中出现错误Error:', error);
  640. // 请求失败时隐藏加载进度条
  641. hideLoadingModal();
  642. alert('生成过程中出现错误,请稍后再试。',error);
  643. });
  644. }
  645. //更新卡片样式
  646. function updateCardAndModalStatus(id, isParentRow) {
  647. // 获取对应的卡片元素,通过 oa_request_id 或 uniqueID 定位
  648. const cardSelector = isParentRow ? `[data-oa-request-id="${id}"]` : `[data-unique-id="${id}"]`;
  649. const card = document.querySelector(cardSelector);
  650. console.log("generateLicense card", cardSelector, card);
  651. if (card) {
  652. // 1. 更新卡片内许可证状态
  653. const statusElement = card.querySelector('.license-status');
  654. console.log("statusElement:", statusElement); // 检查状态元素是否存在
  655. if (statusElement) {
  656. // 只更新许可证状态部分的文本,而不是整个 p 标签
  657. statusElement.innerHTML = '许可证状态:已生成';
  658. // 更新状态的 CSS 类
  659. statusElement.classList.remove('license-status-yellow', 'license-status-red');
  660. statusElement.classList.add('license-status-green');
  661. } else {
  662. console.error('找不到 .license-status 元素');
  663. }
  664. // 2. 更新模态框中的状态(如果模态框已经打开)
  665. const modalStatusElement = document.querySelector('.license-info-modal-header .license-status');
  666. console.log("modalStatusElement:", modalStatusElement); // 检查状态元素是否存在
  667. if (modalStatusElement) {
  668. modalStatusElement.textContent = '许可证状态:已生成';
  669. modalStatusElement.classList.remove('license-status-yellow', 'license-status-red');
  670. modalStatusElement.classList.add('license-status-green');
  671. } else {
  672. console.error('找不到 #license-info-modal-body .license-status 元素');
  673. }
  674. // 3. 更新模态框中的按钮为“分发”
  675. const generateButton = document.getElementById('button1'); // 获取生成按钮
  676. if (generateButton) {
  677. generateButton.textContent = '分发'; // 修改按钮文本为“分发”
  678. generateButton.removeEventListener('click', generateLicense); // 移除生成逻辑
  679. generateButton.addEventListener('click', () => {
  680. distributeLicense(id); // 添加分发逻辑
  681. });
  682. }
  683. // 4. 启用 #downloadAllLicenses-button
  684. const downloadButton = document.getElementById('downloadAllLicenses-button');
  685. if (downloadButton) {
  686. downloadButton.disabled = false; // 启用按钮
  687. downloadButton.style.backgroundColor = '#007aff'; // 恢复正常的背景颜色
  688. downloadButton.style.cursor = 'pointer'; // 修改鼠标样式为可点击
  689. }
  690. } else {
  691. console.error(`找不到与 ID ${id} 对应的卡片`);
  692. }
  693. }
  694. ///-----------获取登录用户信息----------------------------------------
  695. async function fetchUsername() {
  696. try {
  697. const response = await fetch(`http://127.0.0.1:8080/api/admin/userInfo`, {
  698. method: 'GET',
  699. headers: {
  700. 'Authorization': `Bearer ${authToken}`,
  701. 'Content-Type': 'application/json'
  702. }
  703. });
  704. const data = await response.json();
  705. currentUserRole = data.data.Role; // 存储当前用户的角色
  706. currentUserName = data.data.Username;
  707. // 使用获取到的角色,调用获取权限的接口
  708. await fetchPermissionsByRole(currentUserRole);
  709. console.log('当前用户角色:', data);
  710. return data.data; // 返回获取到的用户信息数据
  711. } catch (error) {
  712. console.error('Error fetching user info or permissions:', error);
  713. }
  714. }
  715. // 将 fetchPermissionsByRole 转换为异步函数
  716. async function fetchPermissionsByRole(role) {
  717. try {
  718. const response = await fetch(`http://127.0.0.1:8080/api/admin/GetSelfRoles`, {
  719. method: 'POST',
  720. headers: {
  721. 'Authorization': `Bearer ${authToken}`,
  722. 'Content-Type': 'application/json'
  723. },
  724. body: JSON.stringify({ name: role })
  725. });
  726. const data = await response.json();
  727. currentUserPermissions = data.data.Permissions; // 获取用户的权限数组
  728. console.log('currentUserPermissions:', currentUserPermissions);
  729. // 定义权限类别
  730. // const licensePermissions = ['upload_license', 'read_license'];
  731. // const userPermissionsCheck = ['create_user', 'read_user', 'update_user', 'delete_user'];
  732. // const rolePermissions = ['create_role', 'delete_role', 'update_role', 'get_role'];
  733. // const hasLicenseAccess = licensePermissions.some(permission => userPermissions.includes(permission));
  734. // const hasUserManagementAccess = userPermissionsCheck.some(permission => userPermissions.includes(permission));
  735. // const hasRoleManagementAccess = rolePermissions.some(permission => userPermissions.includes(permission));
  736. // 根据权限渲染菜单并显示初始页面
  737. //renderMenuAndInitialPage(hasLicenseAccess, hasUserManagementAccess, hasRoleManagementAccess);
  738. } catch (error) {
  739. console.error('Error fetching permissions:', error);
  740. }
  741. }
  742. //--------------进度条-------------------------------------------------
  743. // 创建模态框的 DOM 元素并插入到 body 中
  744. function createLoadingModal() {
  745. const modalHTML = `
  746. <div id="loadingModal" class="loading-modal" style="display: none;">
  747. <div class="loading-modal-content">
  748. <div class="spinner"></div>
  749. <p id="loadingMessage">加载中...</p>
  750. </div>
  751. </div>
  752. `;
  753. document.body.insertAdjacentHTML('beforeend', modalHTML);
  754. }
  755. // 显示加载模态框
  756. function showLoadingModal(message = "加载中...") {
  757. const loadingModal = document.getElementById('loadingModal');
  758. const loadingMessage = document.getElementById('loadingMessage');
  759. if (loadingModal && loadingMessage) {
  760. loadingMessage.textContent = message; // 设置显示的消息
  761. loadingModal.style.display = 'flex'; // 显示模态框
  762. }
  763. }
  764. // 隐藏加载模态框
  765. function hideLoadingModal() {
  766. const loadingModal = document.getElementById('loadingModal');
  767. if (loadingModal) {
  768. loadingModal.style.display = 'none'; // 隐藏模态框
  769. }
  770. }
  771. // 页面加载时创建模态框
  772. document.addEventListener('DOMContentLoaded', createLoadingModal);
  773. //-----------搜索栏----------------------------
  774. // 获取搜索框元素
  775. // 获取搜索框、状态下拉框、时间选择框和按钮元素
  776. // 获取搜索框、状态下拉框、时间选择框和按钮元素
  777. const searchBar = document.getElementById('search-bar');
  778. const statusFilter = document.getElementById('license-status-filter');
  779. const startDate = document.getElementById('start-date');
  780. const endDate = document.getElementById('end-date');
  781. const submitButton = document.getElementById('submit-button');
  782. const licenseInfoContainer = document.getElementById('license-info-restaurant-list');
  783. // 过滤功能实现
  784. function filterContent() {
  785. console.log('过滤功能触发');
  786. // 移除滚动监听器,停止滚动加载
  787. // removeScrollListeners();
  788. console.log('statusFilter.valuesdaad撒大啊', statusFilter.value,startDate.value ,endDate.value,searchBar.value );
  789. // 检查如果所有输入框都是默认值,则直接返回,不发送数据
  790. if (!statusFilter.value && !startDate.value && !endDate.value && !searchBar.value) {
  791. console.log("所有过滤条件为空,不发送请求");
  792. return; // 不发送请求
  793. }
  794. // 构建请求体参数
  795. const requestData = {
  796. license_flag: statusFilter.value || undefined,
  797. starting_date: startDate.value || undefined,
  798. end_date: endDate.value || undefined,
  799. any_search: searchBar.value || undefined,
  800. };
  801. console.log("requestData",requestData);
  802. // 发送 POST 请求到接口
  803. fetch('http://127.0.0.1:8080/api/admin/GetConditionalSearch', {
  804. method: 'POST',
  805. headers: {
  806. 'Authorization': `Bearer ${authToken}`,
  807. 'Content-Type': 'application/json',
  808. },
  809. body: JSON.stringify(requestData),
  810. })
  811. .then(response => response.json())
  812. .then(data => {
  813. console.log('成功获取数据:', data);
  814. // 处理返回的数据并更新界面
  815. displayLicenseInfo(data.data);
  816. })
  817. .catch(error => {
  818. console.error('获取数据时发生错误:', error);
  819. });
  820. }
  821. // 处理并显示返回的 License 信息
  822. function displayLicenseInfo(data) {
  823. // 清空之前的结果
  824. licenseInfoContainer.innerHTML = '';
  825. LicApplicationData =[];
  826. // 遍历返回的数据,生成并插入卡片
  827. // 处理返回的数据并更新界面,使用 renderLicenseCards 方法进行渲染
  828. renderLicenseCards(data, true);
  829. }
  830. // 确定按钮点击事件的修改(停止滚动监听)
  831. submitButton.addEventListener('click', function() {
  832. // 检查下拉框和时间选择框是否为默认值
  833. if (!statusFilter.value && !startDate.value && !endDate.value) {
  834. // 如果都是默认值,则刷新页面
  835. location.reload();
  836. } else {
  837. // 否则,执行过滤内容功能
  838. filterContent();
  839. // 隐藏滚动加载,防止继续加载更多内容
  840. removeScrollListeners();
  841. }
  842. });
  843. // 监听返回按钮的点击事件,刷新页面并恢复滚动监听
  844. const resetButton = document.getElementById('reset-button');
  845. resetButton.addEventListener('click', function() {
  846. // 刷新页面
  847. location.reload();
  848. });
  849. // 修改当搜索栏没有输入时,重新启动滚动监听
  850. searchBar.addEventListener('input', function() {
  851. if (!searchBar.value && !statusFilter.value && !startDate.value && !endDate.value) {
  852. console.log("搜索条件清空,重新启动滚动监听");
  853. restartScrollListeners();
  854. }
  855. });