var TYPE_NAMES = { conflict: "Драка", aggression: "Агрессия", smoking: "Курение" }; var TYPE_LEVELS = { conflict: "high", aggression: "medium", smoking: "medium" }; var LEVEL_NAMES = { high: "Критично", medium: "Внимание" }; var STATUS_NAMES = { new: "Новый", ok: "Подтверждён", dismissed: "Отклонён" }; var CAMS = []; var INC = []; var curType = "conflict"; var curTab = "cams"; function esc(s) { return String(s == null ? "" : s) .replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); } function pad(n) { return String(n).length < 2 ? "0" + n : String(n); } function fmtDate(iso) { var d = new Date(iso); return pad(d.getDate()) + "." + pad(d.getMonth() + 1) + "." + d.getFullYear(); } function fmtTime(iso) { var d = new Date(iso); return pad(d.getHours()) + ":" + pad(d.getMinutes()); } function statusPill(st) { var map = { new: "risk", ok: "ok", dismissed: "info" }; return '' + (STATUS_NAMES[st] || st) + ""; } function levelPill(level) { var st = level === "high" ? "risk" : "warn"; return '' + (LEVEL_NAMES[level] || level) + ""; } function camName(id) { var c = CAMS.find(function (x) { return x.id === id; }); return c ? c.name : id; } async function api(path, data) { var opts = data ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) } : {}; var r = await fetch("api/" + path, opts); return r.json(); } function lastEvent(cam) { return cam.events && cam.events.length ? cam.events[cam.events.length - 1] : null; } function renderCams() { var grid = document.getElementById("camGrid"); if (!grid) return; grid.innerHTML = CAMS.map(function (c) { var last = lastEvent(c); return "
" + "
" + esc(c.name) + "" + (last ? fmtTime(last.at) : "сейчас") + "
" + "
" + (last ? "
" + esc(TYPE_NAMES[last.type] || last.type) + "
" : "") + "
"; }).join(""); } function drawCam(cam, hasAlert) { var cv = document.getElementById("cv-" + cam.id); if (!cv) return; var w = cv.width, h = cv.height; var ctx = cv.getContext("2d"); var t = Date.now() / 1000; ctx.clearRect(0, 0, w, h); ctx.fillStyle = "rgba(12,10,9,0.05)"; ctx.fillRect(0, 0, w, h); ctx.strokeStyle = "rgba(12,10,9,0.1)"; ctx.lineWidth = 1; for (var i = 0; i < 4; i++) { var yy = ((cam.id.charCodeAt(1) * (i + 3) * 17) % h) + Math.sin(t * 1.3 + i) * 3; ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(w, yy); ctx.stroke(); } ctx.fillStyle = "rgba(12,10,9,0.14)"; for (var j = 0; j < 6; j++) { var xx = ((cam.id.charCodeAt(3) * 31 * (j + 1)) % w) + Math.cos(t * 0.9 + j) * 10; ctx.fillRect(xx, 4, 1.5, h - 8); } if (hasAlert) { var bx = w / 2 + Math.cos(t * 1.6) * 40; var by = h / 2 + Math.sin(t * 1.2) * 18; ctx.strokeStyle = "rgba(220,38,38,0.65)"; ctx.lineWidth = 2; ctx.strokeRect(bx - 34, by - 26, 68, 52); ctx.lineWidth = 1; } ctx.font = "10px monospace"; ctx.fillStyle = "rgba(12,10,9,0.4)"; ctx.fillText(cam.id.toUpperCase() + " · LIVE " + pad(new Date().getDate()) + "-" + pad(new Date().getMonth() + 1), 8, 14); } function renderKpiCams() { var el = document.getElementById("kpiCams"); if (!el) return; var alerts = CAMS.filter(function (c) { return lastEvent(c); }).length; el.innerHTML = "
" + CAMS.length + "камер в сети
" + "
" + alerts + "камер с активными тревогами
" + "
" + esc(TYPE_NAMES[curType]) + "активный сценарий
"; } function renderIncidents(list) { var wrap = document.getElementById("incContent"); if (!wrap) return; var s = document.getElementById("incSearch"), ft = document.getElementById("incFType"), fs_ = document.getElementById("incFStatus"); var q = (s && s.value ? s.value : "").toLowerCase(); var ty = ft ? ft.value : "all"; var st = fs_ ? fs_.value : "all"; var rows = (list || []).filter(function (i) { if (st !== "all" && i.status !== st) return false; if (ty !== "all" && i.type !== ty) return false; if (q && (i.id + " " + camName(i.camId)).toLowerCase().indexOf(q) < 0) return false; return true; }); if (!rows.length) { wrap.innerHTML = "
Ничего не найдено
Измените фильтры или дождитесь новой тревоги.
"; } else { var body = rows.map(function (i) { var act = ""; if (i.status !== "ok") act = ""; if (i.status !== "dismissed") act += (act ? " " : "") + ""; return "" + esc(i.id) + "" + esc(camName(i.camId)) + "" + esc(TYPE_NAMES[i.type] || i.type) + "" + "" + levelPill(i.level) + "" + fmtDate(i.at) + " " + fmtTime(i.at) + "" + statusPill(i.status) + "" + "" + act + ""; }).join(""); wrap.innerHTML = "" + "" + "" + body + "
IDКамераСобытиеУровеньДатаСтатус
"; } renderKpiInc(); } function renderKpiInc() { var el = document.getElementById("kpiInc"); if (!el) return; var all = INC || []; var nNew = all.filter(function (i) { return i.status === "new"; }).length; var nOk = all.filter(function (i) { return i.status === "ok"; }).length; var nDis = all.filter(function (i) { return i.status === "dismissed"; }).length; el.innerHTML = "
" + all.length + "
Всего инцидентов
" + "
" + nNew + "
Новых
" + "
" + nOk + "
Подтверждено
" + "
" + nDis + "
Отклонено
"; } function switchTab(tab) { curTab = tab; var camT = document.getElementById("camTab"), incT = document.getElementById("incTab"), pt = document.getElementById("pageTitle"); if (camT) camT.hidden = tab !== "cams"; if (incT) incT.hidden = tab !== "inc"; if (pt) pt.textContent = tab === "cams" ? "Камеры" : "Журнал инцидентов"; var items = document.querySelectorAll(".kt-ai-nav-item[data-tab]"); items.forEach(function (n) { n.classList.toggle("is-active", n.getAttribute("data-tab") === tab); }); if (tab === "inc" && !INC.length) loadIncidents(); } function setType(t) { curType = t; var segs = document.querySelectorAll(".seg[data-type]"); segs.forEach(function (b) { b.classList.toggle("is-active", b.getAttribute("data-type") === t); }); renderKpiCams(); } async function loadCams() { CAMS = await api("cams"); renderCams(); renderKpiCams(); } async function loadIncidents() { INC = await api("incidents"); renderIncidents(INC); } function setStatus(id, status) { api("incidents/status", { id: id, status: status }).then(loadIncidents); } function doExport() { if (!INC.length) { alert("Пока нет инцидентов для выгрузки"); return; } var head = ["ID", "Камера", "Событие", "Уровень", "Дата", "Статус"]; var body = INC.map(function (i) { return [i.id, camName(i.camId), TYPE_NAMES[i.type] || i.type, LEVEL_NAMES[i.level] || i.level, fmtDate(i.at) + " " + fmtTime(i.at), STATUS_NAMES[i.status] || i.status]; }); var csv = "\uFEFF" + [head].concat(body).map(function (r) { return r.map(function (v) { return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"'; }).join(";"); }).join("\n"); var a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv;charset=utf-8" })); a.download = "visionguard-incidenty.csv"; a.click(); } function toast(msg, tone) { var stack = document.querySelector(".kt-ai-toast-stack"); if (!stack) { stack = document.createElement("div"); stack.className = "kt-ai-toast-stack"; document.body.appendChild(stack); } var t = document.createElement("div"); t.className = "kt-ai-toast"; t.setAttribute("data-tone", tone || "risk"); t.innerHTML = msg; stack.appendChild(t); setTimeout(function () { t.remove(); }, 4500); } function simOnce() { if (!CAMS.length) return; var cam = CAMS[Math.floor(Math.random() * CAMS.length)]; api("incidents", { camId: cam.id, type: curType }).then(function () { loadCams(); loadIncidents(); toast("Тревога: " + esc(TYPE_NAMES[curType]) + " · " + esc(cam.name), "risk"); }); } function onFilter() { if (INC) renderIncidents(INC); } document.addEventListener("DOMContentLoaded", function () { var items = document.querySelectorAll(".kt-ai-nav-item[data-tab]"); items.forEach(function (n) { n.addEventListener("click", function (e) { e.preventDefault(); switchTab(n.getAttribute("data-tab")); }); }); switchTab("cams"); loadCams().then(function () { drawCams(); loadIncidents(); }); setInterval(function () { loadCams(); if (curTab === "inc") loadIncidents(); }, 8000); }); function drawCams() { CAMS.forEach(function (c) { drawCam(c, !!lastEvent(c)); }); var next = Date.now() / 1000; setTimeout(function () { if (next - Date.now() / 1000 < 30) drawCams(); }, 100); }