app.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // DOM 加载完成后执行,启动入口:初始化菜单、默认页面加载
  2. document.addEventListener("DOMContentLoaded", () => {
  3. const items = document.querySelectorAll(".menu-item");
  4. function setActive(name) {
  5. items.forEach(i => {
  6. i.classList.toggle("active", i.dataset.page === name);
  7. });
  8. }
  9. function bindMenu() {
  10. items.forEach(item => {
  11. item.addEventListener("click", () => {
  12. const page = item.dataset.page;
  13. setActive(page);
  14. loadPage(page);
  15. });
  16. });
  17. }
  18. bindMenu();
  19. setActive("page1");
  20. loadPage("page1");
  21. });
  22. function logout() {
  23. window.location.href = "/api/auth/logout";
  24. }
  25. function setIMEI(imei) {
  26. const el = document.getElementById("imei-value");
  27. if (el) {
  28. el.textContent = imei;
  29. }
  30. }
  31. async function fetchIMEI() {
  32. try {
  33. const res = await fetch("/api/device/imei");
  34. if (!res.ok) {
  35. throw new Error("http error");
  36. }
  37. const imei = await res.text();
  38. if (!imei || imei.trim() === "") {
  39. throw new Error("empty imei");
  40. }
  41. setIMEI(imei.trim());
  42. return;
  43. } catch (e) {
  44. console.log("get imei failed, retrying...");
  45. setTimeout(fetchIMEI, 3000); // 3秒后继续重试
  46. }
  47. }
  48. let sysTimeTimer = null;
  49. function startSysTime() {
  50. if (sysTimeTimer !== null) {
  51. return;
  52. }
  53. function update() {
  54. const el = document.getElementById("sys-time");
  55. if (!el) {
  56. return;
  57. }
  58. const now = new Date();
  59. const year = now.getFullYear();
  60. const month = String(now.getMonth() + 1).padStart(2, "0");
  61. const day = String(now.getDate()).padStart(2, "0");
  62. const hour = String(now.getHours()).padStart(2, "0");
  63. const min = String(now.getMinutes()).padStart(2, "0");
  64. const sec = String(now.getSeconds()).padStart(2, "0");
  65. el.textContent =
  66. `${year}-${month}-${day} ${hour}:${min}:${sec}`;
  67. }
  68. update();
  69. sysTimeTimer = setInterval(update, 1000);
  70. }
  71. document.addEventListener("DOMContentLoaded", () => {
  72. startSysTime();
  73. });
  74. function reboot() {
  75. if (!confirm("确定重启设备吗?")) return;
  76. fetch("/api/system/reboot", {
  77. method: "POST"
  78. })
  79. .then(r => r.json())
  80. .then(d => {
  81. if (d.ok) {
  82. alert("设备正在重启...");
  83. setTimeout(logout, 1000);
  84. } else {
  85. alert("重启失败: " + d.error);
  86. }
  87. })
  88. .catch(e => alert("请求失败: " + e));
  89. }
  90. function loadIMEI() {
  91. fetchIMEI();
  92. }
  93. loadIMEI();