// 设备列表页
async function loadDevices() {
const resp = await fetch("/api/devices");
const devices = await resp.json();
renderTable(devices);
}
function renderTable(devices) {
const tbody = document.querySelector("#device-table tbody");
tbody.innerHTML = devices.map(d => {
const stateLabel = getStateLabel(d.state);
const stateClass = getStateClass(d.state);
return `
| ${d.serial} |
${d.name || '(点击编辑)'}
|
${d.ip || '-'} |
${stateLabel}
|
${d.version || '-'} |
${d.last_login || '-'} |
${USER_ROLE === 'admin' || USER_ROLE === 'manager' ? `` : ''}
|
`;
}).join("");
}
function getStateLabel(state) {
return {0: '离线', 1: '在线', 2: '通信不良'}[state] || '未知';
}
function getStateClass(state) {
return {0: 'status-offline', 1: 'status-online', 2: 'status-poor'}[state] || '';
}
// 异步刷新所有设备的在线状态
async function refreshDeviceStatuses() {
const cells = document.querySelectorAll(".status-cell");
for (const cell of cells) {
const deviceId = cell.dataset.deviceId;
if (!deviceId) continue;
try {
const resp = await fetch(`/api/devices/${deviceId}/status`);
const data = await resp.json();
if (data.ok) {
cell.textContent = data.state_name;
cell.className = getStateClass(data.state) + " status-cell";
cell.dataset.deviceId = deviceId;
}
} catch (e) {
// 网络错误静默跳过
}
}
}
function esc(s) { return s.replace(/'/g, "\\'").replace(/"/g, """); }
async function editName(id, currentName, td) {
const input = document.createElement("input");
input.value = currentName;
td.innerHTML = "";
td.appendChild(input);
input.focus();
async function save() {
const name = input.value.trim();
td.textContent = name || "(点击编辑)";
await fetch(`/api/devices/${id}/name`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
}
input.addEventListener("blur", save);
input.addEventListener("keydown", e => { if (e.key === "Enter") save(); });
}
loadDevices();
// 每 5 秒异步刷新设备在线状态
setInterval(refreshDeviceStatuses, 5000);