// Config form binding helpers shared by WebUI classic scripts. function getConfigBoundElements() { return Array.from(document.querySelectorAll("[data-key]")); } function syncMirrorFields() { const mirrors = Array.from(document.querySelectorAll("[data-mirror-key]")); for (const mirror of mirrors) { const key = mirror.dataset.mirrorKey; const source = document.querySelector(`[data-key="${CSS.escape(key)}"]`); if (!source) continue; const copy = () => { if (mirror.type === "checkbox") mirror.checked = !!source.checked; else mirror.value = source.value; }; copy(); source.addEventListener("input", copy); source.addEventListener("change", copy); mirror.addEventListener("input", () => { if (source.type === "checkbox") source.checked = !!mirror.checked; else source.value = mirror.value; source.dispatchEvent(new Event("input", { bubbles: true })); source.dispatchEvent(new Event("change", { bubbles: true })); }); } } function syncRegionCoordEditability() { const toggle = document.querySelector('#region_coords_edit_enabled'); if (!toggle) return; const apply = () => { const enabled = !!toggle.checked; document.querySelectorAll('[data-index]').forEach((el) => { el.disabled = !enabled; }); }; apply(); toggle.addEventListener('change', apply); } function getConfigValue(cfg, key) { if (!cfg || !key) return undefined; if (Object.prototype.hasOwnProperty.call(cfg, key)) return cfg[key]; if (!String(key).includes(".")) return undefined; let cur = cfg; for (const part of String(key).split(".")) { if (!cur || typeof cur !== "object" || !Object.prototype.hasOwnProperty.call(cur, part)) return undefined; cur = cur[part]; } return cur; } function coerceValue(type, raw, isCheckbox) { if (type === "bool") { if (typeof raw === "boolean") return raw; const text = String(raw ?? "").trim().toLowerCase(); if (["1", "true", "yes", "y", "on"].includes(text)) return true; if (["0", "false", "no", "n", "off", ""].includes(text)) return false; return !!raw; } if (type === "int") { const n = parseInt(String(raw ?? "0"), 10); return Number.isFinite(n) ? n : 0; } if (type === "float") { const n = parseFloat(String(raw ?? "0")); return Number.isFinite(n) ? n : 0; } if (type === "list_lines") { if (Array.isArray(raw)) return raw.map(x => String(x).trim()).filter(Boolean); return String(raw ?? "").split("\n").map(x => x.trim()).filter(Boolean); } if (isCheckbox) return !!raw; return String(raw ?? ""); } function applyConfigToUI(cfg) { const seenIndexedKeys = new Set(); for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; const val = getConfigValue(cfg, key); const indexAttr = el.dataset.index; const hasIndex = typeof indexAttr !== "undefined"; if (hasIndex) { if (seenIndexedKeys.has(key)) continue; seenIndexedKeys.add(key); const grouped = document.querySelectorAll(`[data-key="${CSS.escape(key)}"][data-index]`); const useVal = Array.isArray(val) ? val : (Array.isArray(DEFAULTS[key]) ? DEFAULTS[key] : []); grouped.forEach((field) => { const idx = parseInt(field.dataset.index || "-1", 10); field.value = Number.isInteger(idx) && idx >= 0 ? String(useVal[idx] ?? 0) : "0"; }); continue; } // undefined/null 都视为“未配置”:保留页面默认值 const hasVal = !(typeof val === "undefined" || val === null); const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined); if (typeof useVal === "undefined") continue; if (el.type === "checkbox") { el.checked = !!useVal; continue; } if (type === "list_lines") { el.value = (Array.isArray(useVal) ? useVal : []).join("\n"); continue; } el.value = String(useVal); } } function collectConfigFromUI() { const out = {}; const indexed = new Map(); for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; const indexAttr = el.dataset.index; if (!key) continue; if (typeof indexAttr !== "undefined") { const idx = parseInt(indexAttr, 10); if (!indexed.has(key)) indexed.set(key, [0, 0, 0, 0]); indexed.get(key)[idx] = coerceValue("int", el.value, false); continue; } if (el.type === "checkbox") { out[key] = coerceValue(type, el.checked, true); } else { out[key] = coerceValue(type, el.value, false); } } for (const [key, value] of indexed.entries()) out[key] = value; return out; } async function loadConfig() { try { const cfg = await apiGet("/api/config"); applyConfigToUI(cfg); syncRegionCoordEditability(); toast("配置已加载", "success"); } catch (e) { toast("配置加载失败:" + e.message, "error", { duration: 5000 }); appendLog(["[WEB] 配置加载失败: " + e.message]); } } async function saveConfig() { setButtonBusy("btnSave", true); try { const cfgUpdate = collectConfigFromUI(); await apiPost("/api/config", cfgUpdate); toast("配置已保存", "success"); } catch (e) { toast("保存失败:" + (e?.message || e), "error", { duration: 5000 }); throw e; } finally { setButtonBusy("btnSave", false); } } function renderLicenseStatus(data) { const statusEl = document.getElementById("licenseStatus"); const machineEl = document.getElementById("licenseMachine"); const pathEl = document.getElementById("licensePath"); if (statusEl) { const state = data && data.ok ? "有效" : "无效"; const parts = [ `状态:${state}`, `原因:${data?.reason || ""}`, ]; if (data?.customer) parts.push(`客户:${data.customer}`); if (data?.expires_at) parts.push(`到期:${data.expires_at}`); statusEl.textContent = parts.join(" | "); } if (machineEl) machineEl.value = data?.machine_fingerprint || ""; if (pathEl) pathEl.value = data?.license_path || ""; } async function refreshLicenseStatus() { try { const data = await apiGet("/api/license"); renderLicenseStatus(data); } catch (e) { const statusEl = document.getElementById("licenseStatus"); if (statusEl) statusEl.textContent = "授权状态读取失败:" + (e?.message || e); } } async function installLicenseFromUI() { const input = document.getElementById("licenseText"); const text = String(input?.value || "").trim(); if (!text) { toast("请输入卡密", "warn"); return; } setButtonBusy("btnLicenseInstall", true); try { const data = await apiPost("/api/license", { license_text: text }); renderLicenseStatus(data); if (input) input.value = ""; toast("卡密验证成功", "success"); } catch (e) { const data = e?.data || {}; renderLicenseStatus(data); toast("卡密验证失败:" + (data.message || data.error || e?.message || e), "error", { duration: 5000 }); } finally { setButtonBusy("btnLicenseInstall", false); } }