feat(frontend): 主体/工作站/摄像机/NVR 页面与本地服务对接
This commit is contained in:
parent
0594a26f4f
commit
27df32d7bc
@ -1,11 +1,15 @@
|
||||
/**
|
||||
* 接口客户端:统一带上 `Authorization: Bearer <user JWT>`,统一处理 `{ ok, data, message }` 结构
|
||||
* 接口客户端:统一带上 `Authorization: Bearer <user JWT>` + `X-Subject-Id`,
|
||||
* 统一处理 `{ ok, data, message }` 结构
|
||||
*
|
||||
* 后端约定(见 backend/README):
|
||||
* - 成功 `{ ok: true, data }`;失败 `{ ok: false, message, status? }`
|
||||
* - 401 = 令牌缺失/过期/无效 → 清掉本地令牌并跳登录页
|
||||
* - 400 `status='subject_required'` = 没选主体;403 `status='subject_expired'` = 主体到期
|
||||
* (这两种由页面自己提示,不清令牌)
|
||||
*/
|
||||
import { clearToken, getToken } from '@/composables/useAuth';
|
||||
import { getStoredSubjectId } from '@/composables/subjectStorage';
|
||||
|
||||
/** 开发时走 Vite 代理(同源 /api),生产时后端同源托管,所以默认空字符串即可 */
|
||||
const BASE = (import.meta.env.VITE_API_BASE as string | undefined) || '';
|
||||
@ -42,6 +46,9 @@ async function request<T>(path: string, options: RequestOptions = {}): Promise<T
|
||||
if (auth) {
|
||||
const token = getToken();
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
// 主体范围:业务接口都靠这个 header 限定操作范围(没有主体时不带,后端回 subject_required)
|
||||
const subjectId = getStoredSubjectId();
|
||||
if (subjectId) headers['X-Subject-Id'] = String(subjectId);
|
||||
}
|
||||
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
|
||||
@ -33,15 +33,26 @@ export class LocalServiceError extends Error {
|
||||
}
|
||||
|
||||
/** 带超时的请求;**非 2xx 且返回了 JSON(带 state)时也原样返回**,交给调用方判状态 */
|
||||
async function request<T>(path: string, timeoutMs: number, method: 'GET' | 'POST' = 'GET'): Promise<T> {
|
||||
async function request<T>(path: string, timeoutMs: number, method: 'GET' | 'POST' | 'DELETE' = 'GET', requestBody?: unknown): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
try {
|
||||
const res = await fetch(`${LOCAL_BASE}${path}`, {
|
||||
method,
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: controller.signal,
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${LOCAL_BASE}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...(requestBody === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: requestBody === undefined ? undefined : JSON.stringify(requestBody),
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
// 连不上本机软件(没启动 / 没安装 / 被拦):统一成 status=0,调用方据此提示唤起或下载
|
||||
const aborted = err instanceof DOMException && err.name === 'AbortError';
|
||||
throw new LocalServiceError(aborted ? '连接本机软件超时' : '无法连接本机软件', 0);
|
||||
}
|
||||
|
||||
const text = await res.text();
|
||||
let body: unknown = null;
|
||||
@ -177,3 +188,300 @@ export async function waitForQuery(
|
||||
|
||||
return { result: last, offline: false };
|
||||
}
|
||||
|
||||
// ---------------- 按运单下载录像(本机软件 POST /api/playback/download) ----------------
|
||||
|
||||
/** 下载录像的结果 */
|
||||
export interface LocalPlaybackDownloadResult {
|
||||
ok: boolean;
|
||||
state?: 'ok' | 'need-login' | 'bad-request' | 'unsupported' | 'error';
|
||||
code?: string;
|
||||
/** 最终存放目录(本机软件里设置的录像根目录 + 年/月/日) */
|
||||
folder?: string;
|
||||
/** 合并后的成片路径(单路时就是那一路) */
|
||||
merged?: string | null;
|
||||
/** 各路段文件(合并失败时会有多个) */
|
||||
segments?: string[];
|
||||
/** 非致命提示(某路没下到 / 合并失败等) */
|
||||
warnings?: string[];
|
||||
elapsedMs?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 让本机软件按运单号下载这段时间的录像(多路自动合并)
|
||||
*
|
||||
* 走的是 `POST /api/playback/download { code }`:
|
||||
* - 录像存到**这台电脑自己设置的目录**(默认 `~/packVideo/年/月/日/`),
|
||||
* 跟「是不是设备服务器」无关 —— 任何装了本机软件的电脑都能下;
|
||||
* - 下载 + 合并可能要几十秒,所以超时给到 **180 秒**。
|
||||
*/
|
||||
export function downloadPlayback(code: string): Promise<LocalPlaybackDownloadResult> {
|
||||
return request<LocalPlaybackDownloadResult>('/api/playback/download', 180000, 'POST', { code });
|
||||
}
|
||||
|
||||
// ---------------- 海康设备通道(本机软件 POST /api/hik/channels) ----------------
|
||||
|
||||
/** 本机软件返回的单个通道 */
|
||||
export interface HikChannelItem {
|
||||
channel: number;
|
||||
type: 'analog' | 'digital';
|
||||
enabled: boolean;
|
||||
/** 设备上的通道名(来自 ISAPI,可能为空) */
|
||||
name?: string | null;
|
||||
ip?: string | null;
|
||||
port?: number | null;
|
||||
user?: string | null;
|
||||
}
|
||||
|
||||
/** 本机软件拉通道的返回体(失败时 state=hik-error,并带 lastError) */
|
||||
export interface HikChannelsPayload {
|
||||
ok: boolean;
|
||||
state?: string;
|
||||
lastError?: number;
|
||||
message?: string;
|
||||
data?: {
|
||||
endpoint: string;
|
||||
serialNumber: string;
|
||||
diskCount: number;
|
||||
analogChannelCount: number;
|
||||
digitalChannelCount: number;
|
||||
startChannel: number;
|
||||
startDigitalChannel: number;
|
||||
channels: HikChannelItem[];
|
||||
warning?: string | null;
|
||||
userId: number;
|
||||
sessionReused: boolean;
|
||||
elapsedMs: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过**本机软件**登录海康 NVR(8000 私有协议)并拉取通道列表
|
||||
*
|
||||
* 连不上本机软件(没启动 / 版本过旧 / 跨域被拦)→ 抛 {@link LocalServiceError};
|
||||
* 设备侧失败(密码错 / 端口不通)→ 正常返回,看 `ok === false` 与 `lastError`。
|
||||
*/
|
||||
export function fetchHikChannels(params: {
|
||||
host: string;
|
||||
port?: number;
|
||||
webPort?: number;
|
||||
user: string;
|
||||
password: string;
|
||||
}): Promise<HikChannelsPayload> {
|
||||
return request<HikChannelsPayload>('/api/hik/channels', 30000, 'POST', {
|
||||
host: params.host,
|
||||
port: params.port || 8000,
|
||||
webPort: params.webPort || 80,
|
||||
user: params.user,
|
||||
password: params.password,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------- 海康实时预览(本机软件 /api/hik/preview) ----------------
|
||||
|
||||
/** 预览会话(密码不会出现在 URL 里,只用 sid) */
|
||||
export interface HikPreviewData {
|
||||
sid: string;
|
||||
host: string;
|
||||
port: number;
|
||||
/** 海康通道号(数字通道从 33 起) */
|
||||
channel: number;
|
||||
/** ISAPI/RTSP 的 1 起序号 */
|
||||
logicalChannel: number;
|
||||
/** RTSP 码流 id(主码流 = 通道号*100+1) */
|
||||
streamId: string;
|
||||
fps: number;
|
||||
/** stream = 码流本地解码(可到 25fps);capture = 设备抓帧(约 5fps);ffmpeg = ffmpeg 转码 */
|
||||
mode?: 'stream' | 'capture' | 'ffmpeg' | string;
|
||||
/** 0-主码流 1-子码流 */
|
||||
streamType?: number;
|
||||
maxFps?: number;
|
||||
/** 降级提示(例如取流失败已退回抓帧) */
|
||||
warning?: string | null;
|
||||
name?: string | null;
|
||||
rtspUrl: string;
|
||||
/** 相对路径,用 {@link localUrl} 拼成可给 `<img src>` 的地址 */
|
||||
mjpegUrl: string;
|
||||
snapshotUrl: string;
|
||||
expireAt: string;
|
||||
}
|
||||
|
||||
/** 本机软件建预览会话的返回体 */
|
||||
export interface HikPreviewPayload {
|
||||
ok: boolean;
|
||||
state?: string;
|
||||
lastError?: number;
|
||||
message?: string;
|
||||
data?: HikPreviewData;
|
||||
}
|
||||
|
||||
/** 把本机服务返回的相对路径拼成完整地址(给 `<img src>` / `<a href>` 用) */
|
||||
export function localUrl(path: string): string {
|
||||
return path.startsWith('http') ? path : `${LOCAL_BASE}${path}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 建预览会话(本机软件 → 设备 8000 端口登录 + 抓帧)
|
||||
*
|
||||
* 设备侧失败(密码错 / 通道号错 / 不通)→ 正常返回,看 `ok === false` 与 `lastError`。
|
||||
*/
|
||||
export function createHikPreview(params: {
|
||||
host: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
password: string;
|
||||
channel: number;
|
||||
fps?: number;
|
||||
logicalChannel?: number;
|
||||
name?: string;
|
||||
/** 0-主码流(默认) 1-子码流 */
|
||||
streamType?: number;
|
||||
/** capture = 设备抓帧(低带宽,约 5fps);stream = SDK 取流解码;ffmpeg = ffmpeg 转码(主码流) */
|
||||
mode?: 'stream' | 'capture' | 'ffmpeg';
|
||||
}): Promise<HikPreviewPayload> {
|
||||
return request<HikPreviewPayload>('/api/hik/preview', 20000, 'POST', {
|
||||
host: params.host,
|
||||
port: params.port || 8000,
|
||||
user: params.user,
|
||||
password: params.password,
|
||||
channel: params.channel,
|
||||
fps: params.fps || 25,
|
||||
logicalChannel: params.logicalChannel,
|
||||
name: params.name,
|
||||
streamType: params.streamType ?? 0,
|
||||
mode: params.mode,
|
||||
});
|
||||
}
|
||||
|
||||
/** 关闭预览(释放本机侧会话,设备侧连接留给连接池) */
|
||||
export function closeHikPreview(sid: string): Promise<{ ok?: boolean; removed?: boolean }> {
|
||||
return request(`/api/hik/preview?sid=${encodeURIComponent(sid)}`, 4000, 'DELETE');
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面卸载时释放预览(`navigator.sendBeacon` 只能发 POST,而且不能被 abort)
|
||||
*
|
||||
* 不释放的话:本机软件会一直拉设备码流,下次再开同一通道可能拿不到帧。
|
||||
*/
|
||||
export function closeHikPreviewBeacon(sid: string): void {
|
||||
if (!sid) return;
|
||||
try {
|
||||
navigator.sendBeacon(`${LOCAL_BASE}/api/hik/preview/close?sid=${encodeURIComponent(sid)}`);
|
||||
} catch {
|
||||
// 失败就算了:会话 30 分钟自动过期
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开**满帧率**预览窗口(PlayM4 直接画到窗口,不经过 JPEG 编码 → 可跑满设备帧率 25fps)
|
||||
*
|
||||
* 浏览器无法直接承载 25fps 画面:内嵌只能逐帧转 JPEG(1080p 约 7fps 上限)。
|
||||
*/
|
||||
export function openHikWindow(params: {
|
||||
host: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
password: string;
|
||||
channel: number;
|
||||
streamType?: number;
|
||||
name?: string;
|
||||
}): Promise<{
|
||||
ok: boolean;
|
||||
state?: string;
|
||||
lastError?: number;
|
||||
message?: string;
|
||||
data?: { wid: string; host: string; channel: number; streamType: number; mode: string; fps: number; message: string };
|
||||
}> {
|
||||
return request('/api/hik/preview/window', 20000, 'POST', {
|
||||
host: params.host,
|
||||
port: params.port || 8000,
|
||||
user: params.user,
|
||||
password: params.password,
|
||||
channel: params.channel,
|
||||
streamType: params.streamType ?? 0,
|
||||
name: params.name,
|
||||
});
|
||||
}
|
||||
|
||||
/** 关窗口(用户直接关窗口时本机侧会自动释放,这里只是显式关) */
|
||||
export function closeHikWindow(wid: string): Promise<{ ok?: boolean; closed?: boolean }> {
|
||||
return request(`/api/hik/preview/window?wid=${encodeURIComponent(wid)}`, 4000, 'DELETE');
|
||||
}
|
||||
|
||||
/** 页面卸载时关满帧率窗口(同 {@link closeHikPreviewBeacon},sendBeacon 只能 POST) */
|
||||
export function closeHikWindowBeacon(wid: string): void {
|
||||
if (!wid) return;
|
||||
try {
|
||||
navigator.sendBeacon(`${LOCAL_BASE}/api/hik/preview/window/close?wid=${encodeURIComponent(wid)}`);
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 海康云台(PTZ,本机软件 /api/hik/ptz) ----------------
|
||||
|
||||
/** 云台连续动作(方向 / 变倍 / 聚焦 / 光圈 / 自动扫描) */
|
||||
export type HikPtzCommand =
|
||||
| 'up' | 'down' | 'left' | 'right'
|
||||
| 'up-left' | 'up-right' | 'down-left' | 'down-right'
|
||||
| 'zoom-in' | 'zoom-out'
|
||||
| 'focus-near' | 'focus-far'
|
||||
| 'iris-open' | 'iris-close'
|
||||
| 'auto';
|
||||
|
||||
export interface HikPtzPayload {
|
||||
ok: boolean;
|
||||
state?: string;
|
||||
lastError?: number;
|
||||
message?: string;
|
||||
data?: { channel: number; command?: string | null; action?: string | null; preset?: number; stop?: boolean };
|
||||
}
|
||||
|
||||
/**
|
||||
* 云台连续动作:<c>stop=false</c> 开始、<c>stop=true</c> 停止(必须成对)
|
||||
*
|
||||
* 走设备 8000 私有协议,不需要开预览;不是云台的通道会回 `state=hik-error`(设备不支持)。
|
||||
*/
|
||||
export function ptzControl(params: {
|
||||
host: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
password: string;
|
||||
channel: number;
|
||||
command: HikPtzCommand | string;
|
||||
stop?: boolean;
|
||||
speed?: number;
|
||||
}): Promise<HikPtzPayload> {
|
||||
return request<HikPtzPayload>('/api/hik/ptz', 8000, 'POST', {
|
||||
host: params.host,
|
||||
port: params.port || 8000,
|
||||
user: params.user,
|
||||
password: params.password,
|
||||
channel: params.channel,
|
||||
command: params.command,
|
||||
stop: params.stop === true,
|
||||
speed: params.speed || 4,
|
||||
});
|
||||
}
|
||||
|
||||
/** 预置点:set 设置当前位置 / goto 调用 / clear 删除 */
|
||||
export function ptzPreset(params: {
|
||||
host: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
password: string;
|
||||
channel: number;
|
||||
action: 'set' | 'goto' | 'clear';
|
||||
preset: number;
|
||||
}): Promise<HikPtzPayload> {
|
||||
return request<HikPtzPayload>('/api/hik/ptz/preset', 8000, 'POST', {
|
||||
host: params.host,
|
||||
port: params.port || 8000,
|
||||
user: params.user,
|
||||
password: params.password,
|
||||
channel: params.channel,
|
||||
action: params.action,
|
||||
preset: params.preset,
|
||||
});
|
||||
}
|
||||
|
||||
77
frontend/src/api/subjectApi.ts
Normal file
77
frontend/src/api/subjectApi.ts
Normal file
@ -0,0 +1,77 @@
|
||||
/** 主体(租户)相关接口 */
|
||||
import { api } from '@/api/client';
|
||||
import type { SubjectItem, SubjectMemberItem } from '@/composables/useSubject';
|
||||
|
||||
/** 我的主体列表 */
|
||||
export function fetchSubjects(): Promise<{ list: SubjectItem[]; trialDays: number }> {
|
||||
return api.get<{ list: SubjectItem[]; trialDays: number }>('/api/web/subjects');
|
||||
}
|
||||
|
||||
/** 创建主体(默认赠送 trialDays 天) */
|
||||
export function createSubject(body: { name: string; days?: number; remark?: string }): Promise<SubjectItem> {
|
||||
return api.post<SubjectItem>('/api/web/subjects', body);
|
||||
}
|
||||
|
||||
/** 修改主体(管理员):改名 / 备注 / 续期 */
|
||||
export function updateSubject(
|
||||
id: number,
|
||||
body: { name?: string; remark?: string; extendDays?: number },
|
||||
): Promise<SubjectItem> {
|
||||
return api.put<SubjectItem>(`/api/web/subjects/${id}`, body);
|
||||
}
|
||||
|
||||
/** 成员列表 */
|
||||
export function fetchSubjectMembers(id: number): Promise<{ subjectId: number; list: SubjectMemberItem[] }> {
|
||||
return api.get<{ subjectId: number; list: SubjectMemberItem[] }>(`/api/web/subjects/${id}/members`);
|
||||
}
|
||||
|
||||
/** 按姓名快速添加成员 */
|
||||
export function addSubjectMember(id: number, body: { name: string; role?: number }): Promise<SubjectMemberItem> {
|
||||
return api.post<SubjectMemberItem>(`/api/web/subjects/${id}/members`, body);
|
||||
}
|
||||
|
||||
/** 移除成员 */
|
||||
export function removeSubjectMember(id: number, memberId: number): Promise<{ id: number }> {
|
||||
return api.del<{ id: number }>(`/api/web/subjects/${id}/members/${memberId}`);
|
||||
}
|
||||
|
||||
export interface MemberBindCode {
|
||||
code: string;
|
||||
memberId: number;
|
||||
memberName: string;
|
||||
bindUrl: string;
|
||||
qrUrl: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** 生成成员绑定码(手机扫码后绑定成员) */
|
||||
export function createMemberBindCode(id: number, memberId: number): Promise<MemberBindCode> {
|
||||
return api.post<MemberBindCode>(`/api/web/subjects/${id}/members/${memberId}/bind-code`, {});
|
||||
}
|
||||
|
||||
export interface MemberBindStatus {
|
||||
status: 'pending' | 'confirmed' | 'expired' | 'bad_format' | string;
|
||||
code?: string;
|
||||
subjectId?: number;
|
||||
subjectName?: string;
|
||||
memberId?: number;
|
||||
memberName?: string;
|
||||
boundName?: string;
|
||||
}
|
||||
|
||||
/** 绑定码状态(公开接口,手机扫码页轮询) */
|
||||
export function fetchMemberBindStatus(code: string): Promise<MemberBindStatus> {
|
||||
return api.get<MemberBindStatus>(`/api/subject/member-bind?code=${encodeURIComponent(code)}`, { auth: false });
|
||||
}
|
||||
|
||||
/** 确认绑定:把当前登录账号绑到该成员(需登录) */
|
||||
export function confirmMemberBind(code: string): Promise<{
|
||||
status: string;
|
||||
subjectId: number;
|
||||
subjectName: string;
|
||||
memberId: number;
|
||||
memberName: string;
|
||||
boundName: string;
|
||||
}> {
|
||||
return api.post('/api/subject/member-bind/confirm', { code });
|
||||
}
|
||||
128
frontend/src/api/video.ts
Normal file
128
frontend/src/api/video.ts
Normal file
@ -0,0 +1,128 @@
|
||||
/**
|
||||
* 视频接入:NVR / 摄像头 / 工作台 —— 类型定义
|
||||
*
|
||||
* 后端返回的字段名同时存在驼峰与下划线(Sequelize 的 toJSON 习惯),
|
||||
* 页面只用驼峰字段,下划线字段忽略即可。
|
||||
*/
|
||||
|
||||
/** NVR 录像机 */
|
||||
export interface Nvr {
|
||||
id: number;
|
||||
userId?: number | null;
|
||||
name: string;
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
serialNumber?: string | null;
|
||||
deviceModel?: string | null;
|
||||
channelCount: number;
|
||||
lastSyncAt?: string | null;
|
||||
lastError?: string | null;
|
||||
status: number;
|
||||
remark?: string | null;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
/** 摄像头(NVR 通道) */
|
||||
export interface Camera {
|
||||
id: number;
|
||||
nvrId: number;
|
||||
channelNo: number;
|
||||
name: string;
|
||||
/** 设备上的通道名(可能为空) */
|
||||
channelName?: string | null;
|
||||
type: 'analog' | 'digital' | string;
|
||||
ip?: string | null;
|
||||
port?: number | null;
|
||||
enabled: number;
|
||||
/** 是否支持云台(PTZ),由用户勾选 */
|
||||
hasPtz?: boolean | number | null;
|
||||
status: number;
|
||||
remark?: string | null;
|
||||
nvr?: {
|
||||
id: number;
|
||||
name: string;
|
||||
host: string;
|
||||
port: number;
|
||||
serialNumber?: string | null;
|
||||
userId?: number | null;
|
||||
} | null;
|
||||
/** 已被哪个工作台绑定(null = 可绑);来自 /cameras/options */
|
||||
boundWorkstation?: { id: number; code?: string; name?: string } | null;
|
||||
}
|
||||
|
||||
/** 工作台 */
|
||||
export interface Workstation {
|
||||
id: number;
|
||||
userId?: number | null;
|
||||
code: string;
|
||||
name: string;
|
||||
/** 1 散单工作台 2 团购工作台 */
|
||||
wsType?: number;
|
||||
/** 录制范围:触发点之前秒数(团购=扫码前,散单=任务结束前) */
|
||||
recordBeforeSec?: number;
|
||||
/** 录制范围:触发点之后秒数 */
|
||||
recordAfterSec?: number;
|
||||
/** 最大录制时长(秒),默认 240 */
|
||||
recordMaxSec?: number;
|
||||
status: number;
|
||||
remark?: string | null;
|
||||
/** 合成画布(默认 1920×1080) */
|
||||
canvasWidth?: number;
|
||||
canvasHeight?: number;
|
||||
cameraCount?: number;
|
||||
scanChannelCount?: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
/** Sequelize 实际输出的下划线时间字段 */
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
/** 工作台-摄像头绑定 */
|
||||
export interface WorkstationCameraLink {
|
||||
id: number;
|
||||
workstationId: number;
|
||||
cameraId: number;
|
||||
sortNo: number;
|
||||
remark?: string | null;
|
||||
/** 合成画面里的矩形(像素,相对画布) */
|
||||
x?: number;
|
||||
y?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
/** 0 主码流 1 子码流 */
|
||||
streamType?: number;
|
||||
zIndex?: number;
|
||||
camera?: (Camera & { displayName?: string }) | null;
|
||||
}
|
||||
|
||||
/** 工作台-扫码通道绑定 */
|
||||
export interface WorkstationScanChannelLink {
|
||||
id: number;
|
||||
workstationId: number;
|
||||
scannerId: number;
|
||||
channelId: string;
|
||||
channelName?: string | null;
|
||||
sortNo: number;
|
||||
remark?: string | null;
|
||||
scanner?: { id: number; sn: string; name?: string | null; status?: number } | null;
|
||||
}
|
||||
|
||||
/** 工作台详情 */
|
||||
export interface WorkstationDetail extends Workstation {
|
||||
cameras: WorkstationCameraLink[];
|
||||
scanChannels: WorkstationScanChannelLink[];
|
||||
}
|
||||
|
||||
/** 可绑定的扫码通道(来自中控上报) */
|
||||
export interface AvailableScanChannel {
|
||||
id: number;
|
||||
scannerId: number;
|
||||
channelId: string;
|
||||
channelName?: string | null;
|
||||
scanner?: { id: number; sn: string; name?: string | null; status?: number } | null;
|
||||
/** 已被哪个工作台绑定(null = 可绑) */
|
||||
boundWorkstation?: { id: number; code?: string; name?: string } | null;
|
||||
}
|
||||
250
frontend/src/api/videoApi.ts
Normal file
250
frontend/src/api/videoApi.ts
Normal file
@ -0,0 +1,250 @@
|
||||
/**
|
||||
* 视频接入接口(`/api/web/nvrs|cameras|workstations`)
|
||||
*
|
||||
* 全部只碰「自己的」数据:后端按令牌里的 user 过滤,别人的资源一律 404。
|
||||
*/
|
||||
import { api } from '@/api/client';
|
||||
import type { Paged } from '@/api/types';
|
||||
import type {
|
||||
AvailableScanChannel,
|
||||
Camera,
|
||||
Nvr,
|
||||
Workstation,
|
||||
WorkstationDetail,
|
||||
} from '@/api/video';
|
||||
|
||||
// ---------------- NVR ----------------
|
||||
|
||||
export function fetchNvrs(params: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
keyword?: string;
|
||||
status?: number | '';
|
||||
} = {}): Promise<Paged<Nvr>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||
if (params.keyword) query.set('keyword', params.keyword);
|
||||
if (params.status !== undefined && params.status !== '') query.set('status', String(params.status));
|
||||
const qs = query.toString();
|
||||
return api.get<Paged<Nvr>>(`/api/web/nvrs${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/** 新增 NVR(同 host+port+username 已存在时后端会更新) */
|
||||
export function createNvr(body: {
|
||||
name?: string;
|
||||
host: string;
|
||||
port?: number;
|
||||
username?: string;
|
||||
password: string;
|
||||
serialNumber?: string;
|
||||
deviceModel?: string;
|
||||
remark?: string;
|
||||
}): Promise<Nvr> {
|
||||
return api.post<Nvr>('/api/web/nvrs', body);
|
||||
}
|
||||
|
||||
/** 更新 NVR(password 不传 = 保持原密码) */
|
||||
export function updateNvr(id: number, body: {
|
||||
name?: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
username?: string;
|
||||
password?: string;
|
||||
remark?: string;
|
||||
status?: number;
|
||||
}): Promise<Nvr> {
|
||||
return api.put<Nvr>(`/api/web/nvrs/${id}`, body);
|
||||
}
|
||||
|
||||
/** 删除 NVR(连带删除其下摄像头并解除工作台绑定) */
|
||||
export function deleteNvr(id: number): Promise<{ id: number; removedCameras: number }> {
|
||||
return api.del<{ id: number; removedCameras: number }>(`/api/web/nvrs/${id}`);
|
||||
}
|
||||
|
||||
/** 某 NVR 下已导入的摄像头 */
|
||||
export function fetchNvrCameras(id: number): Promise<{ nvrId: number; list: Camera[] }> {
|
||||
return api.get<{ nvrId: number; list: Camera[] }>(`/api/web/nvrs/${id}/channels`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取通道用的登录凭据(含库里解密出来的密码)
|
||||
*
|
||||
* 仅当密码存在时可取;返回后直接转给本机软件,不要长期缓存。
|
||||
*/
|
||||
export function fetchNvrCredential(id: number): Promise<{
|
||||
id: number;
|
||||
name: string;
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
password: string;
|
||||
hasPassword: boolean;
|
||||
}> {
|
||||
return api.get(`/api/web/nvrs/${id}/credential`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 导入(勾选)通道为摄像头
|
||||
*
|
||||
* 通道数据来自本机软件 `POST /api/hik/channels`,这里只把结果落库。
|
||||
*/
|
||||
export function importNvrChannels(id: number, body: {
|
||||
serialNumber?: string;
|
||||
deviceModel?: string;
|
||||
channels: Array<{
|
||||
channel: number;
|
||||
type: string;
|
||||
name?: string;
|
||||
ip?: string | null;
|
||||
port?: number | null;
|
||||
enabled?: boolean | number;
|
||||
}>;
|
||||
}): Promise<{ created: number; updated: number; list: Camera[]; nvr: Nvr }> {
|
||||
return api.post<{ created: number; updated: number; list: Camera[]; nvr: Nvr }>(
|
||||
`/api/web/nvrs/${id}/channels`,
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------- 摄像头 ----------------
|
||||
|
||||
export function fetchCameras(params: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
nvrId?: number | '';
|
||||
keyword?: string;
|
||||
status?: number | '';
|
||||
} = {}): Promise<Paged<Camera>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||
if (params.nvrId !== undefined && params.nvrId !== '') query.set('nvrId', String(params.nvrId));
|
||||
if (params.keyword) query.set('keyword', params.keyword);
|
||||
if (params.status !== undefined && params.status !== '') query.set('status', String(params.status));
|
||||
const qs = query.toString();
|
||||
return api.get<Paged<Camera>>(`/api/web/cameras${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/** 我的全部可用摄像头(工作台绑定选择器) */
|
||||
export function fetchCameraOptions(): Promise<{ list: Camera[] }> {
|
||||
return api.get<{ list: Camera[] }>('/api/web/cameras/options');
|
||||
}
|
||||
|
||||
export function updateCamera(id: number, body: {
|
||||
name?: string;
|
||||
status?: number;
|
||||
remark?: string;
|
||||
/** 1/0:是否支持云台(PTZ) */
|
||||
hasPtz?: number | boolean;
|
||||
}): Promise<Camera> {
|
||||
return api.put<Camera>(`/api/web/cameras/${id}`, body);
|
||||
}
|
||||
|
||||
export function deleteCamera(id: number): Promise<{ id: number }> {
|
||||
return api.del<{ id: number }>(`/api/web/cameras/${id}`);
|
||||
}
|
||||
|
||||
/** 批量删除摄像头 */
|
||||
export function batchDeleteCameras(ids: number[]): Promise<{ removed: number; skipped: number }> {
|
||||
return api.post<{ removed: number; skipped: number }>('/api/web/cameras/batch-delete', { ids });
|
||||
}
|
||||
|
||||
// ---------------- 工作台 ----------------
|
||||
|
||||
export function fetchWorkstations(params: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
keyword?: string;
|
||||
status?: number | '';
|
||||
/** 1 散单 2 团购;不传 = 全部 */
|
||||
wsType?: number | '';
|
||||
} = {}): Promise<Paged<Workstation>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||
if (params.keyword) query.set('keyword', params.keyword);
|
||||
if (params.status !== undefined && params.status !== '') query.set('status', String(params.status));
|
||||
if (params.wsType !== undefined && params.wsType !== '') query.set('wsType', String(params.wsType));
|
||||
const qs = query.toString();
|
||||
return api.get<Paged<Workstation>>(`/api/web/workstations${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/** 工作台详情(含已绑摄像头 / 扫码通道) */
|
||||
export function fetchWorkstation(id: number): Promise<WorkstationDetail> {
|
||||
return api.get<WorkstationDetail>(`/api/web/workstations/${id}`);
|
||||
}
|
||||
|
||||
export function createWorkstation(body: {
|
||||
/** 不传则由后端自动生成 */
|
||||
code?: string;
|
||||
name?: string;
|
||||
/** 1 散单 2 团购 */
|
||||
wsType?: number;
|
||||
recordBeforeSec?: number;
|
||||
recordAfterSec?: number;
|
||||
recordMaxSec?: number;
|
||||
remark?: string;
|
||||
}): Promise<Workstation> {
|
||||
return api.post<Workstation>('/api/web/workstations', body);
|
||||
}
|
||||
|
||||
export function updateWorkstation(id: number, body: {
|
||||
code?: string;
|
||||
name?: string;
|
||||
wsType?: number;
|
||||
recordBeforeSec?: number;
|
||||
recordAfterSec?: number;
|
||||
recordMaxSec?: number;
|
||||
remark?: string;
|
||||
status?: number;
|
||||
}): Promise<Workstation> {
|
||||
return api.put<Workstation>(`/api/web/workstations/${id}`, body);
|
||||
}
|
||||
|
||||
export function deleteWorkstation(id: number): Promise<{ id: number }> {
|
||||
return api.del<{ id: number }>(`/api/web/workstations/${id}`);
|
||||
}
|
||||
|
||||
/** 追加绑定摄像头 */
|
||||
export function bindWorkstationCameras(id: number, cameraIds: number[]): Promise<WorkstationDetail> {
|
||||
return api.post<WorkstationDetail>(`/api/web/workstations/${id}/cameras`, { cameraIds });
|
||||
}
|
||||
|
||||
export function unbindWorkstationCamera(id: number, cameraId: number): Promise<WorkstationDetail> {
|
||||
return api.del<WorkstationDetail>(`/api/web/workstations/${id}/cameras/${cameraId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存某块摄像头在合成画面里的位置 / 大小 / 码流
|
||||
*
|
||||
* 坐标是相对画布(默认 1920×1080)的像素;后端会按画布范围夹住。
|
||||
*/
|
||||
export function updateWorkstationCameraLayout(id: number, cameraId: number, patch: {
|
||||
x?: number;
|
||||
y?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
streamType?: number;
|
||||
zIndex?: number;
|
||||
}): Promise<WorkstationDetail> {
|
||||
return api.put<WorkstationDetail>(`/api/web/workstations/${id}/cameras/${cameraId}/layout`, patch);
|
||||
}
|
||||
|
||||
/** 追加绑定扫码通道 */
|
||||
export function bindWorkstationScanChannels(
|
||||
id: number,
|
||||
items: Array<{ scannerId: number; channelId: string; channelName?: string }>,
|
||||
): Promise<WorkstationDetail> {
|
||||
return api.post<WorkstationDetail>(`/api/web/workstations/${id}/scan-channels`, { items });
|
||||
}
|
||||
|
||||
export function unbindWorkstationScanChannel(id: number, linkId: number): Promise<WorkstationDetail> {
|
||||
return api.del<WorkstationDetail>(`/api/web/workstations/${id}/scan-channels/${linkId}`);
|
||||
}
|
||||
|
||||
/** 当前用户可绑定的扫码通道(自己的中控上报的通道) */
|
||||
export function fetchAvailableScanChannels(keyword = ''): Promise<{ list: AvailableScanChannel[] }> {
|
||||
const qs = keyword ? `?keyword=${encodeURIComponent(keyword)}` : '';
|
||||
return api.get<{ list: AvailableScanChannel[] }>(`/api/web/workstation-scan-channels${qs}`);
|
||||
}
|
||||
@ -1,7 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
/** 业务页公用布局:左侧菜单 + 顶栏 + 内容区 */
|
||||
/** 业务页公用布局:左侧菜单 + 顶栏(右上角主体切换) + 内容区 */
|
||||
import { computed, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { clearToken, currentUser, displayName } from '@/composables/useAuth';
|
||||
import {
|
||||
currentSubjectId,
|
||||
hasSubject,
|
||||
loadSubjects,
|
||||
setSubjectId,
|
||||
subjects,
|
||||
subjectsLoaded,
|
||||
} from '@/composables/useSubject';
|
||||
|
||||
/**
|
||||
* fill = true:列表页用 —— 内容区不滚动,卡片吃掉剩余高度,只有表格内部滚动(表头吸顶、分页贴底)
|
||||
@ -11,37 +20,97 @@ withDefaults(defineProps<{ fill?: boolean }>(), { fill: false });
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const menus = [
|
||||
{ to: '/', label: '首页' },
|
||||
{ to: '/devices', label: '设备管理' },
|
||||
{ to: '/records', label: '扫码记录' },
|
||||
{ to: '/profile', label: '个人中心' },
|
||||
{ to: '/test', label: '测试页' },
|
||||
/** 菜单项:`subject: true` 表示必须已经选中主体才显示 */
|
||||
const allMenus = [
|
||||
{ to: '/', label: '首页', subject: false },
|
||||
{ to: '/devices', label: '设备管理', subject: true },
|
||||
{ to: '/nvrs', label: 'NVR 录像机', subject: true },
|
||||
{ to: '/cameras', label: '摄像头', subject: true },
|
||||
{ to: '/workstations', label: '工作台', subject: true },
|
||||
{ to: '/records', label: '扫码记录', subject: true },
|
||||
{ to: '/subjects', label: '主体 / 成员', subject: false },
|
||||
{ to: '/profile', label: '个人中心', subject: false },
|
||||
{ to: '/test', label: '测试页', subject: true },
|
||||
];
|
||||
|
||||
/** 没有主体时只留首页 / 主体 / 个人中心(要求:先建主体才出现业务菜单) */
|
||||
const menus = computed(() => allMenus.filter(item => (item.subject ? hasSubject.value : true)));
|
||||
|
||||
/** 当前主体(用于右上角展示 / 过期提示) */
|
||||
const current = computed(() => subjects.value.find(item => item.id === currentSubjectId.value) || null);
|
||||
|
||||
/** 右上角头像里的首字 */
|
||||
const avatarText = computed(() => {
|
||||
const name = (displayName(currentUser.value) || '?').trim();
|
||||
return name.slice(0, 1).toUpperCase();
|
||||
});
|
||||
|
||||
/** 剩余天数(未过期时才显示;今天到期算 0 天) */
|
||||
const daysLeft = computed(() => {
|
||||
if (!current.value || current.value.expired) return null;
|
||||
const diff = new Date(current.value.expireAt).getTime() - Date.now();
|
||||
return Math.max(Math.ceil(diff / 86400000), 0);
|
||||
});
|
||||
|
||||
function onSwitch(event: Event) {
|
||||
const id = Number((event.target as HTMLSelectElement).value);
|
||||
if (!id || id === currentSubjectId.value) return;
|
||||
setSubjectId(id);
|
||||
// 各页面的数据都是挂载时拉取的,切主体后整页刷新最省事
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
function logout() {
|
||||
// 令牌在本地,退出即清掉并回登录页(服务端无需回调)
|
||||
clearToken();
|
||||
router.replace({ name: 'login' });
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 直接打开内页(刷新)时也能把主体下拉填满
|
||||
if (!subjectsLoaded.value) loadSubjects().catch(() => undefined);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="brand">云仓视频溯源系统</div>
|
||||
|
||||
<nav>
|
||||
<RouterLink v-for="item in menus" :key="item.to" :to="item.to">{{ item.label }}</RouterLink>
|
||||
</nav>
|
||||
<div class="me">
|
||||
<div>{{ displayName(currentUser) }}</div>
|
||||
<a href="#" @click.prevent="logout">退出登录</a>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<slot name="title">控制台</slot>
|
||||
<span class="muted">云仓视频溯源系统</span>
|
||||
|
||||
<div class="topbar-right">
|
||||
<!-- 主体切换(右上角) -->
|
||||
<div v-if="subjects.length" class="subject-picker">
|
||||
<span class="subject-label">主体</span>
|
||||
<select :value="currentSubjectId ?? ''" @change="onSwitch">
|
||||
<option v-for="item in subjects" :key="item.id" :value="item.id">
|
||||
{{ item.name }}
|
||||
</option>
|
||||
</select>
|
||||
<span v-if="current?.expired" class="subject-tag is-danger">已到期</span>
|
||||
<span v-else-if="daysLeft !== null" class="subject-tag" :class="{ 'is-warn': daysLeft <= 3 }">
|
||||
剩 {{ daysLeft }} 天
|
||||
</span>
|
||||
<RouterLink class="subject-manage" to="/subjects">管理</RouterLink>
|
||||
</div>
|
||||
<RouterLink v-else class="subject-empty" to="/subjects">还没有主体,去创建 →</RouterLink>
|
||||
|
||||
<span class="topbar-divider" aria-hidden="true" />
|
||||
|
||||
<!-- 账号(右上角,与主体切换同一组) -->
|
||||
<div class="user-box">
|
||||
<span class="user-avatar">{{ avatarText }}</span>
|
||||
<span class="user-name" :title="displayName(currentUser)">{{ displayName(currentUser) }}</span>
|
||||
<a class="user-logout" href="#" @click.prevent="logout">退出登录</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<section :class="['content', { 'content-fill': fill }]">
|
||||
<slot />
|
||||
@ -49,3 +118,181 @@ function logout() {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 标题与右上角一组:标题可以被压缩,右侧不折行 */
|
||||
.topbar {
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.topbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
/* 右上角的分隔线 */
|
||||
.topbar-divider {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
background: var(--border);
|
||||
margin: 0 2px;
|
||||
}
|
||||
|
||||
/* 账号区:头像 + 昵称 + 退出登录 */
|
||||
.user-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
flex: 0 0 26px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #334155;
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
.user-name {
|
||||
max-width: 120px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
font-size: 13px;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.user-logout {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.user-logout:hover {
|
||||
color: #b91c1c;
|
||||
background: #fef2f2;
|
||||
}
|
||||
|
||||
/* 主体切换:一行「标签 + 下拉 + 期限标 + 管理」 */
|
||||
.subject-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 32px;
|
||||
padding: 0 8px 0 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.subject-label {
|
||||
font-size: 12px;
|
||||
color: #94a3b8;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.subject-picker select {
|
||||
max-width: 220px;
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
height: 24px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
color: #0f172a;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.subject-picker select:focus-visible {
|
||||
outline: 2px solid rgba(59, 130, 246, 0.35);
|
||||
outline-offset: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
/* 期限标(默认灰,快到期黄,已到期红) */
|
||||
.subject-tag {
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
padding: 0 8px;
|
||||
border-radius: 999px;
|
||||
color: #475569;
|
||||
background: #e2e8f0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.subject-tag.is-warn {
|
||||
color: #92400e;
|
||||
background: #fef3c7;
|
||||
}
|
||||
|
||||
.subject-tag.is-danger {
|
||||
color: #b91c1c;
|
||||
background: #fee2e2;
|
||||
}
|
||||
|
||||
.subject-manage {
|
||||
font-size: 12px;
|
||||
color: #2563eb;
|
||||
padding: 0 6px;
|
||||
border-left: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.subject-manage:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* 没有主体时的入口 */
|
||||
.subject-empty {
|
||||
font-size: 13px;
|
||||
color: #b45309;
|
||||
padding: 5px 12px;
|
||||
border: 1px dashed #f59e0b;
|
||||
border-radius: 999px;
|
||||
background: #fffbeb;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.subject-empty:hover {
|
||||
background: #fef3c7;
|
||||
}
|
||||
|
||||
/* 窗口变窄时依次收起次要信息:昵称 → 「主体」标签 → 期限标,保证不换行不溢出 */
|
||||
@media (max-width: 1180px) {
|
||||
.user-name {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.subject-label {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.subject-picker {
|
||||
padding-left: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.subject-tag {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.subject-picker select {
|
||||
max-width: 140px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
546
frontend/src/components/CameraLayoutCanvas.vue
Normal file
546
frontend/src/components/CameraLayoutCanvas.vue
Normal file
@ -0,0 +1,546 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 工作台「合成画面」布局画布
|
||||
*
|
||||
* 一个工作台绑定的多个摄像头,要按矩形拼成一张 1920×1080 的输出画面
|
||||
* (后续按这个布局分别拉流录制/合成),所以这里做:
|
||||
* - 按画布坐标绝对定位每个摄像头(拖拽移动、右下角拖拽缩放)
|
||||
* - 每块可选「主码流 / 子码流」、可改宽高(选中后在右侧面板里调)
|
||||
* - 每块里面放实时画面(主码流用设备抓帧 1080p,子码流用取流解码)
|
||||
* - `editable=false` 时就是「合并输出预览」
|
||||
*
|
||||
* 保存走 `PUT /api/web/workstations/:id/cameras/:cameraId/layout`。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { updateWorkstationCameraLayout } from '@/api/videoApi';
|
||||
import { fetchNvrCredential } from '@/api/videoApi';
|
||||
import {
|
||||
LocalServiceError,
|
||||
closeHikPreview,
|
||||
closeHikPreviewBeacon,
|
||||
createHikPreview,
|
||||
} from '@/api/local';
|
||||
import type { WorkstationCameraLink, WorkstationDetail } from '@/api/video';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
workstationId: number;
|
||||
canvasWidth?: number;
|
||||
canvasHeight?: number;
|
||||
links: WorkstationCameraLink[];
|
||||
editable?: boolean;
|
||||
}>(), {
|
||||
canvasWidth: 1920,
|
||||
canvasHeight: 1080,
|
||||
editable: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ (e: 'changed', detail: WorkstationDetail): void }>();
|
||||
|
||||
interface Tile {
|
||||
cameraId: number;
|
||||
name: string;
|
||||
channelNo: number;
|
||||
nvrId: number;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
streamType: number;
|
||||
zIndex: number;
|
||||
}
|
||||
|
||||
const tiles = reactive<Tile[]>([]);
|
||||
const selectedId = ref<number | null>(null);
|
||||
const saving = ref(false);
|
||||
const message = ref('');
|
||||
const error = ref('');
|
||||
|
||||
/** 预览会话:cameraId → { sid, src } */
|
||||
const previews = reactive<Record<number, { sid: string; src: string }>>({});
|
||||
const credCache = new Map<number, { host: string; port: number; username: string; password: string }>();
|
||||
|
||||
const canvasW = computed(() => Number(props.canvasWidth) || 1920);
|
||||
const canvasH = computed(() => Number(props.canvasHeight) || 1080);
|
||||
|
||||
// ---------------- 按容器宽度等比缩放画布 ----------------
|
||||
const hostRef = ref<HTMLElement | null>(null);
|
||||
const scale = ref(0.25);
|
||||
let observer: ResizeObserver | null = null;
|
||||
|
||||
function measure() {
|
||||
const width = hostRef.value?.clientWidth || 0;
|
||||
if (width > 0) scale.value = width / canvasW.value;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
measure();
|
||||
if (hostRef.value && typeof ResizeObserver !== 'undefined') {
|
||||
observer = new ResizeObserver(measure);
|
||||
observer.observe(hostRef.value);
|
||||
}
|
||||
window.addEventListener('pagehide', releaseAllBeacon);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener('pagehide', releaseAllBeacon);
|
||||
void releaseAll();
|
||||
});
|
||||
|
||||
// ---------------- 数据同步 ----------------
|
||||
function toTile(link: WorkstationCameraLink, index: number): Tile {
|
||||
const camera = link.camera;
|
||||
const width = Number(link.width) || canvasW.value;
|
||||
const height = Number(link.height) || canvasH.value;
|
||||
|
||||
return {
|
||||
cameraId: Number(link.cameraId),
|
||||
name: camera?.name || camera?.channelName || `通道${camera?.channelNo ?? ''}`,
|
||||
channelNo: Number(camera?.channelNo) || 0,
|
||||
nvrId: Number(camera?.nvrId ?? camera?.nvr?.id) || 0,
|
||||
x: Number(link.x) || 0,
|
||||
y: Number(link.y) || 0,
|
||||
width,
|
||||
height,
|
||||
streamType: Number(link.streamType) === 1 ? 1 : 0,
|
||||
zIndex: Number(link.zIndex) || index,
|
||||
};
|
||||
}
|
||||
|
||||
watch(() => props.links, (value) => {
|
||||
tiles.splice(0, tiles.length, ...(value || []).map(toTile));
|
||||
void syncPreviews();
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
// ---------------- 实时预览 ----------------
|
||||
async function credentialOf(nvrId: number) {
|
||||
if (!nvrId) return null;
|
||||
if (credCache.has(nvrId)) return credCache.get(nvrId)!;
|
||||
|
||||
try {
|
||||
const cred = await fetchNvrCredential(nvrId);
|
||||
credCache.set(nvrId, cred);
|
||||
return cred;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 给每块画面建预览(最多 4 路,避免把设备/本机打爆) */
|
||||
async function syncPreviews() {
|
||||
const wanted = new Set(tiles.slice(0, 4).map(tile => tile.cameraId));
|
||||
|
||||
for (const key of Object.keys(previews)) {
|
||||
const cameraId = Number(key);
|
||||
if (!wanted.has(cameraId)) await stopPreview(cameraId);
|
||||
}
|
||||
|
||||
for (const tile of tiles.slice(0, 4)) {
|
||||
if (previews[tile.cameraId]) continue;
|
||||
|
||||
const cred = await credentialOf(tile.nvrId);
|
||||
if (!cred) continue;
|
||||
|
||||
try {
|
||||
const res = await createHikPreview({
|
||||
host: cred.host,
|
||||
port: cred.port,
|
||||
user: cred.username,
|
||||
password: cred.password,
|
||||
channel: tile.channelNo,
|
||||
fps: 5,
|
||||
// 主码流用 ffmpeg 转码(设备抓帧并发会报 err=29/4);子码流走 SDK 取流解码
|
||||
mode: tile.streamType === 1 ? 'stream' : 'ffmpeg',
|
||||
streamType: tile.streamType,
|
||||
name: tile.name,
|
||||
});
|
||||
|
||||
if (res.ok && res.data) {
|
||||
previews[tile.cameraId] = {
|
||||
sid: res.data.sid,
|
||||
src: `${(import.meta.env.VITE_LOCAL_SERVICE as string | undefined || 'http://localhost:17300').replace(/\/+$/, '')}${res.data.mjpegUrl}&fps=5`,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof LocalServiceError && err.status === 0) {
|
||||
error.value = '本机软件未运行,画面无法加载';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function stopPreview(cameraId: number) {
|
||||
const item = previews[cameraId];
|
||||
if (!item) return;
|
||||
|
||||
delete previews[cameraId];
|
||||
try {
|
||||
await closeHikPreview(item.sid);
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
|
||||
function releaseAllBeacon() {
|
||||
for (const [ key, item ] of Object.entries(previews)) {
|
||||
closeHikPreviewBeacon(item.sid);
|
||||
delete previews[Number(key)];
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseAll() {
|
||||
await Promise.all(Object.keys(previews).map(key => stopPreview(Number(key))));
|
||||
}
|
||||
|
||||
// ---------------- 拖拽 / 缩放 ----------------
|
||||
type DragState = { mode: 'move' | 'resize'; cameraId: number; startX: number; startY: number; origin: Tile };
|
||||
|
||||
let drag: DragState | null = null;
|
||||
|
||||
const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), Math.max(min, max));
|
||||
|
||||
function tileById(cameraId: number) {
|
||||
return tiles.find(tile => tile.cameraId === cameraId);
|
||||
}
|
||||
|
||||
function onPointerDown(event: PointerEvent, tile: Tile) {
|
||||
if (!props.editable) return;
|
||||
selectedId.value = tile.cameraId;
|
||||
|
||||
drag = {
|
||||
mode: 'move',
|
||||
cameraId: tile.cameraId,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
origin: { ...tile },
|
||||
};
|
||||
(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
function onResizeDown(event: PointerEvent, tile: Tile) {
|
||||
if (!props.editable) return;
|
||||
selectedId.value = tile.cameraId;
|
||||
|
||||
drag = {
|
||||
mode: 'resize',
|
||||
cameraId: tile.cameraId,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
origin: { ...tile },
|
||||
};
|
||||
(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
function onPointerMove(event: PointerEvent) {
|
||||
if (!drag) return;
|
||||
|
||||
const tile = tileById(drag.cameraId);
|
||||
if (!tile) return;
|
||||
|
||||
const dx = (event.clientX - drag.startX) / scale.value;
|
||||
const dy = (event.clientY - drag.startY) / scale.value;
|
||||
|
||||
if (drag.mode === 'move') {
|
||||
tile.x = Math.round(clamp(drag.origin.x + dx, 0, canvasW.value - tile.width));
|
||||
tile.y = Math.round(clamp(drag.origin.y + dy, 0, canvasH.value - tile.height));
|
||||
} else {
|
||||
tile.width = Math.round(clamp(drag.origin.width + dx, 160, canvasW.value - tile.x));
|
||||
tile.height = Math.round(clamp(drag.origin.height + dy, 90, canvasH.value - tile.y));
|
||||
}
|
||||
}
|
||||
|
||||
async function onPointerUp() {
|
||||
if (!drag) return;
|
||||
|
||||
const tile = tileById(drag.cameraId);
|
||||
drag = null;
|
||||
if (!tile) return;
|
||||
|
||||
await saveTile(tile);
|
||||
}
|
||||
|
||||
// ---------------- 保存 ----------------
|
||||
async function saveTile(tile: Tile) {
|
||||
saving.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const detail = await updateWorkstationCameraLayout(props.workstationId, tile.cameraId, {
|
||||
x: tile.x,
|
||||
y: tile.y,
|
||||
width: tile.width,
|
||||
height: tile.height,
|
||||
streamType: tile.streamType,
|
||||
zIndex: tile.zIndex,
|
||||
});
|
||||
|
||||
message.value = '布局已保存';
|
||||
window.setTimeout(() => { message.value = ''; }, 2000);
|
||||
emit('changed', detail);
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : '保存失败';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function changeStream(tile: Tile, value: number) {
|
||||
tile.streamType = Number(value) === 1 ? 1 : 0;
|
||||
await stopPreview(tile.cameraId);
|
||||
await saveTile(tile);
|
||||
await syncPreviews();
|
||||
}
|
||||
|
||||
async function applySize(tile: Tile) {
|
||||
tile.width = Math.round(clamp(Number(tile.width) || 0, 160, canvasW.value - tile.x));
|
||||
tile.height = Math.round(clamp(Number(tile.height) || 0, 90, canvasH.value - tile.y));
|
||||
await saveTile(tile);
|
||||
}
|
||||
|
||||
async function fillCanvas(tile: Tile) {
|
||||
tile.x = 0;
|
||||
tile.y = 0;
|
||||
tile.width = canvasW.value;
|
||||
tile.height = canvasH.value;
|
||||
await saveTile(tile);
|
||||
}
|
||||
|
||||
async function bringToFront(tile: Tile) {
|
||||
tile.zIndex = Math.max(...tiles.map(item => item.zIndex), 0) + 1;
|
||||
await saveTile(tile);
|
||||
}
|
||||
|
||||
const selected = computed(() => (selectedId.value ? tileById(selectedId.value) : undefined));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="layout-wrap">
|
||||
<div
|
||||
ref="hostRef"
|
||||
class="layout-host"
|
||||
:class="{ editing: editable }"
|
||||
:style="{ height: Math.round(canvasH * scale) + 'px' }"
|
||||
>
|
||||
<div
|
||||
class="layout-stage"
|
||||
:style="{
|
||||
width: canvasW + 'px',
|
||||
height: canvasH + 'px',
|
||||
transform: `scale(${scale})`,
|
||||
}"
|
||||
@pointermove="onPointerMove"
|
||||
@pointerup="onPointerUp"
|
||||
@pointerleave="onPointerUp"
|
||||
>
|
||||
<div
|
||||
v-for="tile in tiles"
|
||||
:key="tile.cameraId"
|
||||
class="tile"
|
||||
:class="{ active: editable && selectedId === tile.cameraId }"
|
||||
:style="{
|
||||
left: tile.x + 'px',
|
||||
top: tile.y + 'px',
|
||||
width: tile.width + 'px',
|
||||
height: tile.height + 'px',
|
||||
zIndex: tile.zIndex,
|
||||
}"
|
||||
@pointerdown="onPointerDown($event, tile)"
|
||||
>
|
||||
<div class="tile-fallback">{{ tile.name }}<br /><small>无画面(摄像头可能离线)</small></div>
|
||||
<img
|
||||
v-if="previews[tile.cameraId]"
|
||||
:src="previews[tile.cameraId].src"
|
||||
:alt="tile.name"
|
||||
draggable="false"
|
||||
/>
|
||||
|
||||
<span class="tile-label">
|
||||
{{ tile.name }} · {{ tile.width }}×{{ tile.height }} · {{ tile.streamType === 1 ? '子码流' : '主码流' }}
|
||||
</span>
|
||||
|
||||
<span v-if="editable" class="tile-resize" @pointerdown="onResizeDown($event, tile)" />
|
||||
</div>
|
||||
|
||||
<p v-if="!tiles.length" class="stage-empty">还没有绑定摄像头</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="editable && selected" class="layout-panel">
|
||||
<strong>{{ selected.name }}</strong>
|
||||
<label>码流
|
||||
<select :value="selected.streamType" @change="changeStream(selected, Number(($event.target as HTMLSelectElement).value))">
|
||||
<option :value="0">主码流</option>
|
||||
<option :value="1">子码流</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>宽
|
||||
<input v-model.number="selected.width" type="number" min="160" :max="canvasW" @change="applySize(selected)" />
|
||||
</label>
|
||||
<label>高
|
||||
<input v-model.number="selected.height" type="number" min="90" :max="canvasH" @change="applySize(selected)" />
|
||||
</label>
|
||||
<label>x
|
||||
<input v-model.number="selected.x" type="number" min="0" @change="saveTile(selected)" />
|
||||
</label>
|
||||
<label>y
|
||||
<input v-model.number="selected.y" type="number" min="0" @change="saveTile(selected)" />
|
||||
</label>
|
||||
<div class="panel-actions">
|
||||
<button class="btn btn-sm" @click="fillCanvas(selected)">铺满画布</button>
|
||||
<button class="btn btn-sm btn-ghost" @click="bringToFront(selected)">置顶</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="alert alert-error">{{ error }}</p>
|
||||
<p v-else-if="message" class="hint ok">{{ message }}</p>
|
||||
<p v-if="editable" class="hint">
|
||||
拖动画面移动位置,拖右下角调整大小;点选后可改宽高 / 码流。默认画布 {{ canvasW }}×{{ canvasH }}。
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.layout-wrap {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.layout-host {
|
||||
flex: 1;
|
||||
min-width: 320px;
|
||||
overflow: hidden;
|
||||
background: #0b1220;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #1e293b;
|
||||
}
|
||||
|
||||
.layout-host.editing {
|
||||
border-color: #3b82f6;
|
||||
}
|
||||
|
||||
.layout-stage {
|
||||
position: relative;
|
||||
transform-origin: top left;
|
||||
background:
|
||||
repeating-linear-gradient(0deg, rgba(148, 163, 184, 0.08) 0 1px, transparent 1px 120px),
|
||||
repeating-linear-gradient(90deg, rgba(148, 163, 184, 0.08) 0 1px, transparent 1px 120px);
|
||||
}
|
||||
|
||||
.tile {
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
background: #111827;
|
||||
border: 2px solid transparent;
|
||||
cursor: move;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.tile.active {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.35);
|
||||
}
|
||||
|
||||
.tile img {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 图片没帧时(摄像头离线)显示在下方,有画面就被 img 盖住 */
|
||||
.tile-fallback {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: #64748b;
|
||||
font-size: 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tile-fallback small {
|
||||
font-size: 22px;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.tile-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: #64748b;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
|
||||
.tile-label {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
padding: 4px 10px;
|
||||
font-size: 22px;
|
||||
color: #e2e8f0;
|
||||
background: rgba(2, 6, 23, 0.6);
|
||||
}
|
||||
|
||||
.tile-resize {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
background: linear-gradient(135deg, transparent 50%, #3b82f6 50%);
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
|
||||
.stage-empty {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #64748b;
|
||||
font-size: 40px;
|
||||
}
|
||||
|
||||
.layout-panel {
|
||||
width: 240px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.layout-panel label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.layout-panel input {
|
||||
width: 90px;
|
||||
}
|
||||
|
||||
.panel-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.hint.ok {
|
||||
color: #15803d;
|
||||
}
|
||||
</style>
|
||||
79
frontend/src/components/DataPager.vue
Normal file
79
frontend/src/components/DataPager.vue
Normal file
@ -0,0 +1,79 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 通用分页条(列表页共用)
|
||||
*
|
||||
* 用法:
|
||||
* ```vue
|
||||
* <DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||
* unit="条" @update:page="load" @update:page-size="onPageSize" />
|
||||
* ```
|
||||
*
|
||||
* 约定:页码从 **1** 开始;页面收到 `update:page` 后自己去取数据。
|
||||
* `update:page-size` 时本组件会**同时发一次 `update:page`(1)**,页面两件事都要处理
|
||||
* (或只处理 pageSize 然后自己重新 load(1))。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
/** 可选的每页条数 */
|
||||
pageSizes?: number[];
|
||||
/** 单位(条 / 台 / 个) */
|
||||
unit?: string;
|
||||
/** 加载中:禁用所有按钮 */
|
||||
loading?: boolean;
|
||||
}>(), {
|
||||
pageSizes: () => [ 10, 20, 50, 100 ],
|
||||
unit: '条',
|
||||
loading: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:page', value: number): void;
|
||||
(e: 'update:pageSize', value: number): void;
|
||||
}>();
|
||||
|
||||
const pages = computed(() => Math.max(Math.ceil(props.total / Math.max(props.pageSize, 1)), 1));
|
||||
const jump = ref('');
|
||||
|
||||
function go(target: number) {
|
||||
if (props.loading) return;
|
||||
const clamped = Math.min(Math.max(Math.trunc(target), 1), pages.value);
|
||||
if (clamped !== props.page) emit('update:page', clamped);
|
||||
}
|
||||
|
||||
function onPageSizeChange(event: Event) {
|
||||
const value = Number((event.target as HTMLSelectElement).value);
|
||||
if (!Number.isFinite(value) || value <= 0 || value === props.pageSize) return;
|
||||
|
||||
emit('update:pageSize', value);
|
||||
emit('update:page', 1);
|
||||
}
|
||||
|
||||
function onJump() {
|
||||
const value = Number(jump.value);
|
||||
jump.value = '';
|
||||
if (Number.isFinite(value) && value > 0) go(value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pager">
|
||||
<span class="hint">共 {{ total }} {{ unit }}</span>
|
||||
|
||||
<button class="btn btn-ghost btn-sm" :disabled="loading || page <= 1" @click="go(1)">首页</button>
|
||||
<button class="btn btn-ghost btn-sm" :disabled="loading || page <= 1" @click="go(page - 1)">上一页</button>
|
||||
<span class="hint pager-pos">{{ page }} / {{ pages }}</span>
|
||||
<button class="btn btn-ghost btn-sm" :disabled="loading || page >= pages" @click="go(page + 1)">下一页</button>
|
||||
<button class="btn btn-ghost btn-sm" :disabled="loading || page >= pages" @click="go(pages)">末页</button>
|
||||
|
||||
<select class="pager-select" :value="pageSize" :disabled="loading" @change="onPageSizeChange">
|
||||
<option v-for="size in pageSizes" :key="size" :value="size">{{ size }} 条/页</option>
|
||||
</select>
|
||||
|
||||
<input v-model="jump" class="pager-jump" placeholder="跳页" inputmode="numeric"
|
||||
:disabled="loading" @keyup.enter="onJump" />
|
||||
</div>
|
||||
</template>
|
||||
92
frontend/src/components/ModalBox.vue
Normal file
92
frontend/src/components/ModalBox.vue
Normal file
@ -0,0 +1,92 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 通用弹窗:遮罩 + 居中面板 + 标题栏 + 底部按钮插槽
|
||||
*
|
||||
* 用 Teleport 挂到 body,避免被列表容器的 `overflow: hidden` 裁掉。
|
||||
*/
|
||||
withDefaults(defineProps<{ open: boolean; title?: string; width?: string }>(), {
|
||||
title: '',
|
||||
width: '560px',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{ (e: 'close'): void }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="modal-mask" @click.self="emit('close')">
|
||||
<div class="modal-box" :style="{ width }">
|
||||
<header class="modal-head">
|
||||
<strong>{{ title }}</strong>
|
||||
<button class="modal-x" type="button" aria-label="关闭" @click="emit('close')">×</button>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<slot />
|
||||
</div>
|
||||
<footer v-if="$slots.footer" class="modal-foot">
|
||||
<slot name="footer" />
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(15, 23, 42, 0.45);
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.modal-box {
|
||||
max-width: calc(100vw - 48px);
|
||||
max-height: calc(100vh - 80px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #fff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 60px rgba(15, 23, 42, 0.28);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.modal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid #eef0f4;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.modal-x {
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
color: #94a3b8;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-x:hover {
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 16px 18px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.modal-foot {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 18px;
|
||||
border-top: 1px solid #eef0f4;
|
||||
background: #fafbfc;
|
||||
}
|
||||
</style>
|
||||
26
frontend/src/composables/subjectStorage.ts
Normal file
26
frontend/src/composables/subjectStorage.ts
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 主体选择的本地存储(**只做 localStorage**,不引接口,避免和 api/client.ts 形成循环依赖)
|
||||
*
|
||||
* `client.ts` 每次请求都会调 `getStoredSubjectId()` 决定要不要带 `X-Subject-Id`。
|
||||
*/
|
||||
const SUBJECT_KEY = 'packs_subject_id';
|
||||
|
||||
/** 上次使用的主体 id(没有/非法返回 null) */
|
||||
export function getStoredSubjectId(): number | null {
|
||||
try {
|
||||
const raw = Number(localStorage.getItem(SUBJECT_KEY));
|
||||
return Number.isInteger(raw) && raw > 0 ? raw : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 记住/清除当前主体 */
|
||||
export function setStoredSubjectId(id: number | null): void {
|
||||
try {
|
||||
if (id) localStorage.setItem(SUBJECT_KEY, String(id));
|
||||
else localStorage.removeItem(SUBJECT_KEY);
|
||||
} catch {
|
||||
/* localStorage 不可用时忽略(隐私模式) */
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import { ref } from 'vue';
|
||||
import { setStoredSubjectId } from '@/composables/subjectStorage';
|
||||
|
||||
/** 本地令牌与当前用户的存放(SPA 用 header 令牌,不依赖 cookie/session) */
|
||||
const TOKEN_KEY = 'packs_token';
|
||||
@ -43,6 +44,8 @@ export function setUser(user: CurrentUser): void {
|
||||
export function clearToken(): void {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem(USER_KEY);
|
||||
// 主体选择也要清:换账号后不能带着上一个账号的主体 id
|
||||
setStoredSubjectId(null);
|
||||
currentUser.value = null;
|
||||
}
|
||||
|
||||
|
||||
126
frontend/src/composables/useSubject.ts
Normal file
126
frontend/src/composables/useSubject.ts
Normal file
@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 主体(租户)状态:当前主体 + 主体列表
|
||||
*
|
||||
* - 上次使用的主题存在 `localStorage.packs_subject_id`,登录后如果还在列表里就继续用它
|
||||
* - 所有业务接口都要带 `X-Subject-Id`(见 `api/client.ts`)
|
||||
* - 没有可用主体时,菜单里只留「主体」入口,先创建主体才能看到设备/录像机/摄像头/工作台/扫码记录
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { api } from '@/api/client';
|
||||
import { getToken } from '@/composables/useAuth';
|
||||
import { getStoredSubjectId, setStoredSubjectId } from '@/composables/subjectStorage';
|
||||
|
||||
export interface SubjectItem {
|
||||
id: number;
|
||||
name: string;
|
||||
adminUserId: number;
|
||||
expireAt: string;
|
||||
status: number;
|
||||
remark?: string | null;
|
||||
/** 1 管理员 2 成员 */
|
||||
role: number;
|
||||
memberName?: string | null;
|
||||
memberCount?: number;
|
||||
expired: boolean;
|
||||
}
|
||||
|
||||
export interface SubjectMemberItem {
|
||||
id: number;
|
||||
name: string;
|
||||
role: number;
|
||||
status: number;
|
||||
userId: number | null;
|
||||
boundAt?: string | null;
|
||||
wechatBound: boolean;
|
||||
user?: { id: number; username?: string | null; nickname?: string | null; avatar?: string | null } | null;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
function readId(): number | null {
|
||||
return getStoredSubjectId();
|
||||
}
|
||||
|
||||
/** 主体列表(响应式) */
|
||||
export const subjects = ref<SubjectItem[]>([]);
|
||||
/** 新建主体默认赠送天数(后端下发) */
|
||||
export const trialDays = ref(7);
|
||||
/** 当前主体 id(响应式) */
|
||||
export const currentSubjectId = ref<number | null>(readId());
|
||||
/** 是否已经拉过主体列表 */
|
||||
export const subjectsLoaded = ref(false);
|
||||
/** 这份列表是用哪个令牌拉下来的(换账号/退出后自动重拉,避免脏数据) */
|
||||
let loadedForToken = '';
|
||||
|
||||
/** 当前主体对象 */
|
||||
export const currentSubject = computed<SubjectItem | null>(
|
||||
() => subjects.value.find(item => item.id === currentSubjectId.value) || null,
|
||||
);
|
||||
|
||||
/** 是否有可用主体(存在且在有效期内) */
|
||||
export const hasSubject = computed(() => Boolean(currentSubject.value && !currentSubject.value.expired));
|
||||
|
||||
/** 当前账号是不是当前主体的管理员 */
|
||||
export const isSubjectAdmin = computed(() => Number(currentSubject.value?.role) === 1);
|
||||
|
||||
export function getSubjectId(): number | null {
|
||||
const id = currentSubjectId.value;
|
||||
return id && subjects.value.some(item => item.id === id) ? id : null;
|
||||
}
|
||||
|
||||
/** 切换主体(只改本地;接口靠 header 带上) */
|
||||
export function setSubjectId(id: number | null): void {
|
||||
setStoredSubjectId(id);
|
||||
currentSubjectId.value = id;
|
||||
if (!id) return;
|
||||
}
|
||||
|
||||
/** 清掉主体选择(退出登录 / 换账号时) */
|
||||
export function clearSubjectCache(): void {
|
||||
subjects.value = [];
|
||||
subjectsLoaded.value = false;
|
||||
loadedForToken = '';
|
||||
currentSubjectId.value = null;
|
||||
setStoredSubjectId(null);
|
||||
}
|
||||
|
||||
/** 用后端下发的列表刷新(登录接口里也带了一份) */
|
||||
export function applySubjects(list: SubjectItem[], days?: number): void {
|
||||
subjects.value = Array.isArray(list) ? list : [];
|
||||
subjectsLoaded.value = true;
|
||||
loadedForToken = getToken();
|
||||
if (typeof days === 'number' && days > 0) trialDays.value = days;
|
||||
|
||||
// 上次用的主体还在 → 继续用;否则挑第一个可用的(没过期),都没有就选第一个
|
||||
const stored = readId();
|
||||
const keep = stored && subjects.value.some(item => item.id === stored) ? stored : null;
|
||||
if (keep) {
|
||||
currentSubjectId.value = keep;
|
||||
return;
|
||||
}
|
||||
const usable = subjects.value.find(item => !item.expired && Number(item.status) === 1) || subjects.value[0];
|
||||
setSubjectId(usable ? usable.id : null);
|
||||
}
|
||||
|
||||
/** 拉取主体列表(`GET /api/web/subjects`) */
|
||||
export async function loadSubjects(): Promise<SubjectItem[]> {
|
||||
const data = await api.get<{ list: SubjectItem[]; trialDays: number }>('/api/web/subjects');
|
||||
applySubjects(data.list, data.trialDays);
|
||||
return subjects.value;
|
||||
}
|
||||
|
||||
/** 没拉过(或换了账号)就拉一次(路由守卫里用) */
|
||||
export async function ensureSubjects(): Promise<void> {
|
||||
if (subjectsLoaded.value && loadedForToken === getToken() && getToken()) return;
|
||||
await loadSubjects();
|
||||
}
|
||||
|
||||
/** 本地更新某个主体(改完名字/续期后不用整表重拉) */
|
||||
export function patchSubject(id: number, patch: Partial<SubjectItem>): void {
|
||||
const index = subjects.value.findIndex(item => item.id === id);
|
||||
if (index >= 0) subjects.value[index] = Object.assign({}, subjects.value[index], patch);
|
||||
}
|
||||
|
||||
/** 使用期限是否已过(前端也判一次,用于提示色) */
|
||||
export function isExpired(item: SubjectItem): boolean {
|
||||
return Boolean(item.expired) || new Date(item.expireAt).getTime() <= Date.now();
|
||||
}
|
||||
@ -1,6 +1,32 @@
|
||||
import { createApp } from 'vue';
|
||||
import App from './App.vue';
|
||||
import { router } from './router';
|
||||
import { api } from './api/client';
|
||||
import { getToken, setUser, type CurrentUser } from './composables/useAuth';
|
||||
import { loadSubjects } from './composables/useSubject';
|
||||
import './styles/main.css';
|
||||
|
||||
createApp(App).use(router).mount('#app');
|
||||
|
||||
/**
|
||||
* 启动后补拉一下当前用户与主体。
|
||||
*
|
||||
* 桌面端「工具 → 打开配置页」带 `?token=` 直接打开时,本地只有令牌没有用户信息;
|
||||
* 令牌由路由守卫先落地(并把 URL 里的 token 去掉),这里只管把用户/主体补全。
|
||||
*/
|
||||
async function refreshSession(): Promise<void> {
|
||||
if (!getToken()) return;
|
||||
|
||||
try {
|
||||
const me = await api.get<CurrentUser>('/api/web/me');
|
||||
setUser(me);
|
||||
} catch {
|
||||
// 令牌无效:路由守卫会把人送回登录页
|
||||
return;
|
||||
}
|
||||
|
||||
await loadSubjects().catch(() => undefined);
|
||||
}
|
||||
|
||||
// 等首屏路由(含 SSO 令牌落地)完成后再补拉用户信息
|
||||
void router.isReady().then(refreshSession);
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
|
||||
import { getToken } from '@/composables/useAuth';
|
||||
import { ensureSubjects, hasSubject } from '@/composables/useSubject';
|
||||
|
||||
/**
|
||||
* 路由表(meta.public = 不需要登录)
|
||||
@ -23,10 +24,16 @@ const routes: RouteRecordRaw[] = [
|
||||
meta: { public: true, bare: true },
|
||||
},
|
||||
|
||||
{ path: '/', name: 'home', component: () => import('@/views/HomeView.vue') },
|
||||
{ path: '/', name: 'home', component: () => import('@/views/HomeView.vue'), meta: { allowNoSubject: true } },
|
||||
// 主体 / 成员:没有主体时只有这个入口(创建主体、切换主体、绑成员)
|
||||
{ path: '/subjects', name: 'subjects', component: () => import('@/views/SubjectsView.vue'), meta: { allowNoSubject: true } },
|
||||
{ path: '/devices', name: 'devices', component: () => import('@/views/DevicesView.vue') },
|
||||
// 视频接入:NVR → 摄像头 → 工作台
|
||||
{ path: '/nvrs', name: 'nvrs', component: () => import('@/views/NvrsView.vue') },
|
||||
{ path: '/cameras', name: 'cameras', component: () => import('@/views/CamerasView.vue') },
|
||||
{ path: '/workstations', name: 'workstations', component: () => import('@/views/WorkstationsView.vue') },
|
||||
{ path: '/records', name: 'records', component: () => import('@/views/RecordsView.vue') },
|
||||
{ path: '/profile', name: 'profile', component: () => import('@/views/ProfileView.vue') },
|
||||
{ path: '/profile', name: 'profile', component: () => import('@/views/ProfileView.vue'), meta: { allowNoSubject: true } },
|
||||
{ path: '/test', name: 'test', component: () => import('@/views/TestView.vue') },
|
||||
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
@ -37,7 +44,17 @@ export const router = createRouter({
|
||||
routes,
|
||||
});
|
||||
|
||||
router.beforeEach((to) => {
|
||||
router.beforeEach(async (to) => {
|
||||
// 桌面端「工具 → 打开配置页」:`?token=<用户 JWT>` 直接登录,并把 token 从地址栏去掉
|
||||
const ssoToken = typeof to.query.token === 'string' ? to.query.token : (typeof to.query.sso === 'string' ? to.query.sso : '');
|
||||
if (ssoToken) {
|
||||
localStorage.setItem('packs_token', ssoToken);
|
||||
const query = { ...to.query };
|
||||
delete query.token;
|
||||
delete query.sso;
|
||||
return { path: to.path, query, replace: true };
|
||||
}
|
||||
|
||||
const logged = Boolean(getToken());
|
||||
if (!to.meta.public && !logged) {
|
||||
return { name: 'login', query: { redirect: to.fullPath } };
|
||||
@ -48,5 +65,17 @@ router.beforeEach((to) => {
|
||||
if (to.meta.public && logged && !alwaysShow) {
|
||||
return { name: 'home' };
|
||||
}
|
||||
|
||||
// 业务页都要主体:没拉过列表先拉一次,没有可用主体就去「主体 / 成员」页创建
|
||||
if (logged && !to.meta.public) {
|
||||
try {
|
||||
await ensureSubjects();
|
||||
} catch {
|
||||
// 后端不可用时不拦路由,让页面自己报错
|
||||
}
|
||||
if (to.meta.allowNoSubject !== true && !hasSubject.value) {
|
||||
return { name: 'subjects', query: { need: '1' } };
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
@ -134,29 +134,26 @@ select:focus {
|
||||
}
|
||||
|
||||
.bare-card {
|
||||
position: relative; /* 登录页的右上角三角就以卡片为定位父级 */
|
||||
width: 360px;
|
||||
max-width: 100%;
|
||||
margin: auto;
|
||||
overflow: hidden; /* 让三角的直角被卡片圆角裁掉 */
|
||||
}
|
||||
|
||||
/* ---------------- 登录页的面板切换(账号密码 ↔ 微信扫码) ----------------
|
||||
· 面板都放在同一个 .panel-switch 容器里,靠 is-login / is-register / is-wechat 决定显示哪个;
|
||||
· 登录与扫码用 padding-top + min-height 定成同高 → 切换时卡片高度/位置不变;
|
||||
· 右上角的三角形 .corner-toggle 挂在容器上,和输入框右边缘对齐(不是页面右上角)。 */
|
||||
· 登录与扫码用 min-height 定成同高 → 切换时卡片高度/位置不变;
|
||||
· 右上角三角形 .corner-toggle 挂在**卡片**(.card.bare-card)上,不是在面板里:
|
||||
它从卡片顶边算 38px 高,卡片自身 padding 20px,所以面板再留 18px(20+18=38)就不会被三角压住。 */
|
||||
.panel-switch {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* 登录(含注册)与扫码面板都要给右上角三角形留出 38px,登录/扫码再定成同高 */
|
||||
.panel-switch.is-login,
|
||||
.panel-switch.is-register,
|
||||
.panel-switch.is-wechat {
|
||||
padding-top: 38px;
|
||||
}
|
||||
|
||||
.panel-switch.is-login,
|
||||
.panel-switch.is-wechat {
|
||||
min-height: 300px;
|
||||
padding-top: 18px;
|
||||
min-height: 282px;
|
||||
}
|
||||
|
||||
.pane {
|
||||
@ -176,6 +173,7 @@ select:focus {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 1;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
padding: 0;
|
||||
@ -399,6 +397,30 @@ th {
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.pager-pos {
|
||||
min-width: 54px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.pager-select {
|
||||
height: 30px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.pager-jump {
|
||||
width: 72px;
|
||||
height: 30px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
@ -427,6 +449,19 @@ th {
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
/* 工作台类型:散单(蓝)/ 团购(橙) */
|
||||
.badge-single {
|
||||
color: #1d4ed8;
|
||||
background: #eff6ff;
|
||||
border-color: #bfdbfe;
|
||||
}
|
||||
|
||||
.badge-group {
|
||||
color: #b45309;
|
||||
background: #fff7ed;
|
||||
border-color: #fed7aa;
|
||||
}
|
||||
|
||||
/* ---------------- 列表页:占满高度,滚动只在表格内部(整页不滚动) ----------------
|
||||
AppLayout 传 fill 时给内容区加 .content-fill:
|
||||
卡片撑满剩余高度(只有一两条数据也撑满)→ 表头吸顶、分页固定在卡片底部。 */
|
||||
|
||||
74
frontend/src/utils/localSoftware.ts
Normal file
74
frontend/src/utils/localSoftware.ts
Normal file
@ -0,0 +1,74 @@
|
||||
/**
|
||||
* 「本机软件」的启动 / 安装辅助
|
||||
*
|
||||
* 网页**没法直接判断**软件是「没装」还是「装了没启动」(浏览器的沙箱看不到注册表)。
|
||||
* 所以统一用「先叫一次,唤不起来就当没装」这套流程(与 `/local` 公共页一致):
|
||||
*
|
||||
* 1. 用自定义协议 `yuncang://open` 叫醒 → 能起来就是「装了没启动」;
|
||||
* 2. 等不到就提示「可能未安装」,给出安装包下载地址。
|
||||
*
|
||||
* 下载地址来自后端 `GET /download/version.json`(打包脚本自动生成,带版本号),
|
||||
* 取不到时退回 `VITE_SOFTWARE_DOWNLOAD_URL`。
|
||||
*/
|
||||
import { LOCAL_BASE, launchApp } from '@/api/local';
|
||||
|
||||
/** `/download/version.json` 的内容(打包脚本写入) */
|
||||
export interface SoftwareRelease {
|
||||
version?: string;
|
||||
downloadUrl?: string;
|
||||
size?: number;
|
||||
md5?: string;
|
||||
publishedAt?: string;
|
||||
releaseNotes?: string;
|
||||
}
|
||||
|
||||
/** 兜底下载地址(后端没放 version.json 时用) */
|
||||
const FALLBACK_DOWNLOAD_URL = (import.meta.env.VITE_SOFTWARE_DOWNLOAD_URL as string | undefined) || '';
|
||||
|
||||
/** 探测本机软件是否在线:**任何 HTTP 响应都算在线**(连不上才算离线) */
|
||||
export async function isLocalServiceAlive(timeoutMs = 1500): Promise<boolean> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
await fetch(`${LOCAL_BASE}/`, { signal: controller.signal, cache: 'no-store' });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** 轮询等本机软件起来(用户点了「启动」之后) */
|
||||
export async function waitForLocalService(timeoutMs = 15000, intervalMs = 800): Promise<boolean> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
if (await isLocalServiceAlive()) return true;
|
||||
await new Promise(resolve => setTimeout(resolve, intervalMs));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 用自定义协议唤起本机软件(必须在用户手势里调用) */
|
||||
export function launchLocalSoftware(): void {
|
||||
launchApp();
|
||||
}
|
||||
|
||||
/** 取最新安装包信息(后端静态文件,失败就返回 null) */
|
||||
export async function fetchSoftwareRelease(): Promise<SoftwareRelease | null> {
|
||||
try {
|
||||
const res = await fetch('/download/version.json', { cache: 'no-store' });
|
||||
if (!res.ok) return null;
|
||||
return (await res.json()) as SoftwareRelease;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 安装包下载地址(release 里优先,其次环境变量兜底) */
|
||||
export function softwareDownloadUrl(release: SoftwareRelease | null): string {
|
||||
return release?.downloadUrl || FALLBACK_DOWNLOAD_URL;
|
||||
}
|
||||
1024
frontend/src/views/CamerasView.vue
Normal file
1024
frontend/src/views/CamerasView.vue
Normal file
File diff suppressed because it is too large
Load Diff
@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { onMounted, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import DataPager from '@/components/DataPager.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { deleteDevice, fetchDeviceChannels, fetchDevices, unbindDevice } from '@/api/web';
|
||||
import type { Channel, Device } from '@/api/types';
|
||||
@ -14,7 +15,7 @@ import { formatTime, fromNow } from '@/utils/format';
|
||||
const list = ref<Device[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = 10;
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
@ -24,13 +25,11 @@ const ok = ref('');
|
||||
const channels = ref<Record<number, Channel[]>>({});
|
||||
const expanding = ref(0);
|
||||
|
||||
const totalPages = () => Math.max(Math.ceil(total.value / pageSize), 1);
|
||||
|
||||
async function load(targetPage = page.value) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await fetchDevices({ page: targetPage, pageSize, keyword: keyword.value.trim() });
|
||||
const data = await fetchDevices({ page: targetPage, pageSize: pageSize.value, keyword: keyword.value.trim() });
|
||||
list.value = data.list;
|
||||
total.value = data.total;
|
||||
page.value = data.page;
|
||||
@ -41,6 +40,11 @@ async function load(targetPage = page.value) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 分页组件换页 / 改每页条数 */
|
||||
function changePageSize(size: number) {
|
||||
pageSize.value = size;
|
||||
}
|
||||
|
||||
function search() {
|
||||
load(1);
|
||||
}
|
||||
@ -105,7 +109,6 @@ onMounted(() => load(1));
|
||||
<div class="toolbar">
|
||||
<input v-model="keyword" placeholder="搜索 SN / 名称 / 型号" @keyup.enter="search" />
|
||||
<button class="btn" :disabled="loading" @click="search">搜索</button>
|
||||
<span class="hint">共 {{ total }} 台</span>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
@ -171,11 +174,8 @@ onMounted(() => load(1));
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<button class="btn btn-ghost btn-sm" :disabled="page <= 1 || loading" @click="load(page - 1)">上一页</button>
|
||||
<span class="hint">{{ page }} / {{ totalPages() }}</span>
|
||||
<button class="btn btn-ghost btn-sm" :disabled="page >= totalPages() || loading" @click="load(page + 1)">下一页</button>
|
||||
</div>
|
||||
<DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||
unit="台" @update:page="load" @update:page-size="changePageSize" />
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
@ -1,18 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
/** 首页:只统计「我的」数据(设备 / 通道 / 扫码记录 + 最近一次扫码) */
|
||||
/** 首页:只统计「当前主体」的数据(设备 / 通道 / 扫码记录 + 最近一次扫码) */
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { fetchStats } from '@/api/web';
|
||||
import type { Stats } from '@/api/types';
|
||||
import { hasSubject } from '@/composables/useSubject';
|
||||
import { formatTime, fromNow } from '@/utils/format';
|
||||
|
||||
const stats = ref<Stats | null>(null);
|
||||
const error = ref('');
|
||||
const loading = ref(true);
|
||||
const noSubject = ref(!hasSubject.value);
|
||||
|
||||
onMounted(async () => {
|
||||
if (noSubject.value) {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stats.value = await fetchStats();
|
||||
} catch (err) {
|
||||
@ -28,6 +34,16 @@ onMounted(async () => {
|
||||
<template #title>首页</template>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
|
||||
<div v-else-if="noSubject" class="card">
|
||||
<h3>先创建一个主体</h3>
|
||||
<p class="hint">
|
||||
主体(租户)是设备、录像机、摄像头、工作台、扫码记录的归属单位。
|
||||
创建主体并选择它之后,才会出现这些菜单。新主体默认赠送 7 天使用期限。
|
||||
</p>
|
||||
<RouterLink class="btn" to="/subjects">去创建主体</RouterLink>
|
||||
</div>
|
||||
|
||||
<p v-else-if="loading" class="hint">加载中…</p>
|
||||
|
||||
<template v-else-if="stats">
|
||||
|
||||
@ -23,6 +23,7 @@ import {
|
||||
requestLocalLogin,
|
||||
queryLocal,
|
||||
waitForQuery,
|
||||
downloadPlayback,
|
||||
LOCAL_BASE,
|
||||
type LocalQueryResult,
|
||||
} from '@/api/local';
|
||||
@ -138,8 +139,7 @@ async function launch() {
|
||||
}
|
||||
|
||||
/** 按码查信息(码为空也发一次:服务端会回「缺少运单号」+ 当前登录状态,照样能驱动页面) */
|
||||
async function runQuery() {
|
||||
querying.value = true;
|
||||
async function runQuery() { querying.value = true;
|
||||
error.value = '';
|
||||
|
||||
try {
|
||||
@ -177,6 +177,55 @@ const entries = computed<Array<{ key: string; value: string }>>(() => {
|
||||
|
||||
const raw = computed(() => (info.value ? JSON.stringify(info.value, null, 2) : ''));
|
||||
|
||||
// ---------------- 下载录像(本机软件执行,存到本机设置的目录) ----------------
|
||||
|
||||
const downloading = ref(false);
|
||||
const downloadMsg = ref('');
|
||||
const downloadError = ref('');
|
||||
const downloadFolder = ref('');
|
||||
|
||||
/**
|
||||
* 让本机软件按运单下载录像
|
||||
*
|
||||
* 下载 + 多路合并要几十秒,按钮期间禁用并提示;结果只给路径(文件在这台电脑上)。
|
||||
*/
|
||||
async function download() {
|
||||
const target = code.value.trim();
|
||||
if (!target) return;
|
||||
|
||||
downloading.value = true;
|
||||
downloadError.value = '';
|
||||
downloadFolder.value = '';
|
||||
downloadMsg.value = '正在下载录像…(多路合并可能需要几十秒)';
|
||||
|
||||
try {
|
||||
const res = await downloadPlayback(target);
|
||||
|
||||
if (res.state === 'need-login') {
|
||||
downloadMsg.value = '';
|
||||
downloadError.value = '本机软件未登录,请先登录后再下载';
|
||||
await askLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
downloadError.value = res.message || '下载失败';
|
||||
downloadMsg.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
downloadFolder.value = res.folder || '';
|
||||
const warnings = (res.warnings || []).filter(Boolean);
|
||||
downloadMsg.value = `已下载到本机:${res.merged || (res.segments || []).join('、') || res.folder || ''}`
|
||||
+ (warnings.length ? `(提示:${warnings.join(';')})` : '');
|
||||
} catch {
|
||||
downloadMsg.value = '';
|
||||
downloadError.value = '连不上本机软件(可能已退出),请先启动它再试';
|
||||
} finally {
|
||||
downloading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
@ -269,6 +318,18 @@ onMounted(load);
|
||||
</table>
|
||||
<p v-else class="center hint">本机软件没有返回内容。</p>
|
||||
|
||||
<!-- 下载录像:由**本机**软件执行,存到**本机**设置的录像目录(任何电脑都可以,不限设备服务器) -->
|
||||
<div v-if="info && info.state === 'ok' && info.ok" class="download-box">
|
||||
<button class="btn" type="button" :disabled="downloading || !code" @click="download">
|
||||
{{ downloading ? '正在下载…' : '下载录像到本机' }}
|
||||
</button>
|
||||
<p class="hint tiny">
|
||||
录像存到这台电脑的录像目录(默认 <code>用户目录\packVideo\年\月\日</code>,可在软件「设置 → 录像存储路径」改)
|
||||
</p>
|
||||
<p v-if="downloadMsg" class="hint tiny download-ok">{{ downloadMsg }}</p>
|
||||
<div v-if="downloadError" class="alert alert-error">{{ downloadError }}</div>
|
||||
</div>
|
||||
|
||||
<details v-if="raw" class="raw">
|
||||
<summary>原始返回(JSON)</summary>
|
||||
<pre class="json-box">{{ raw }}</pre>
|
||||
@ -348,6 +409,23 @@ onMounted(load);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* 下载录像区块 */
|
||||
.download-box {
|
||||
margin-top: 14px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px dashed var(--border);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.download-box .hint {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.download-ok {
|
||||
color: #15803d;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.raw {
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
|
||||
@ -14,6 +14,15 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import { setSession, type CurrentUser } from '@/composables/useAuth';
|
||||
import { applySubjects, type SubjectItem } from '@/composables/useSubject';
|
||||
|
||||
/** 登录/注册接口返回:令牌 + 用户 + 可进入的主体列表 */
|
||||
type LoginResult = {
|
||||
token: string;
|
||||
user: CurrentUser;
|
||||
subjects?: SubjectItem[];
|
||||
expiresIn?: number | string;
|
||||
};
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@ -43,12 +52,14 @@ async function doLogin() {
|
||||
error.value = '';
|
||||
busy.value = true;
|
||||
try {
|
||||
const data = await api.post<{ token: string; user: CurrentUser }>(
|
||||
const data = await api.post<LoginResult>(
|
||||
'/api/web/auth/login',
|
||||
{ account: loginForm.account, password: loginForm.password },
|
||||
{ auth: false },
|
||||
);
|
||||
setSession(data.token, data.user);
|
||||
// 登录接口直接下发主体列表:先落地,路由守卫就不用再请求一次
|
||||
if (Array.isArray(data.subjects)) applySubjects(data.subjects);
|
||||
go();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '登录失败,请稍后再试';
|
||||
@ -89,7 +100,7 @@ async function doRegister() {
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const data = await api.post<{ token: string; user: CurrentUser }>(
|
||||
const data = await api.post<LoginResult>(
|
||||
'/api/web/auth/register',
|
||||
{
|
||||
username: registerForm.username,
|
||||
@ -100,6 +111,7 @@ async function doRegister() {
|
||||
{ auth: false },
|
||||
);
|
||||
setSession(data.token, data.user);
|
||||
if (Array.isArray(data.subjects)) applySubjects(data.subjects);
|
||||
go();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '注册失败,请稍后再试';
|
||||
@ -187,6 +199,8 @@ function switchTab(next: Tab) {
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('pagehide', stopWechat);
|
||||
// 从「改密 / 重置密码」跳回来时的提示(旧令牌已失效,需要重新登录)
|
||||
if (typeof route.query.ok === 'string' && route.query.ok) ok.value = route.query.ok;
|
||||
if (route.query.mode === 'wechat') switchTab('wechat');
|
||||
else if (route.query.mode === 'register') tab.value = 'register';
|
||||
});
|
||||
@ -202,36 +216,31 @@ onBeforeUnmount(() => {
|
||||
<div class="card bare-card">
|
||||
<div class="brand-line">云仓视频溯源系统</div>
|
||||
|
||||
<!-- 右上角三角形:挂在**卡片**上(`.card.bare-card` 是定位父级),只在「登录 ↔ 扫码」之间切;注册面板不显示它 -->
|
||||
<button
|
||||
v-if="tab === 'login'"
|
||||
class="corner-toggle"
|
||||
type="button"
|
||||
title="用微信扫码登录"
|
||||
aria-label="用微信扫码登录"
|
||||
@click="switchTab('wechat')"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm9 1h2v2h-2v-2zm3 0h2v2h-2v-2zm-3 3h2v2h-2v-2zm3 0h2v2h-2v-2z"/></svg>
|
||||
</button>
|
||||
<button
|
||||
v-else-if="tab === 'wechat'"
|
||||
class="corner-toggle"
|
||||
type="button"
|
||||
title="返回账号密码登录"
|
||||
aria-label="返回账号密码登录"
|
||||
@click="switchTab('login')"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4v-4H4v4zm0-6h4v-4H4v4zm6 6h4v-4h-4v4zm-6-12h4V4H4v4zm6 0h4V4h-4v4zm6 12h4v-4h-4v4zm-5-1h8v2h-8v-2zm4-9h4V4h-4v4zm-9-1h10v2H6V9z"/></svg>
|
||||
</button>
|
||||
|
||||
<div :class="['panel-switch', paneClass]">
|
||||
<!-- 扫码 ↔ 账号密码:右上角三角形(与输入框右边缘对齐) -->
|
||||
<button
|
||||
v-if="tab === 'wechat'"
|
||||
class="corner-toggle"
|
||||
type="button"
|
||||
title="返回账号密码登录"
|
||||
aria-label="返回账号密码登录"
|
||||
@click="switchTab('login')"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 20h4v-4H4v4zm0-6h4v-4H4v4zm6 6h4v-4h-4v4zm-6-12h4V4H4v4zm6 0h4V4h-4v4zm6 12h4v-4h-4v4zm-5-1h8v2h-8v-2zm4-9h4V4h-4v4zm-9-1h10v2H6V9z"/></svg>
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
class="corner-toggle"
|
||||
type="button"
|
||||
title="用微信扫码登录"
|
||||
aria-label="用微信扫码登录"
|
||||
@click="switchTab('wechat')"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm9 1h2v2h-2v-2zm3 0h2v2h-2v-2zm-3 3h2v2h-2v-2zm3 0h2v2h-2v-2z"/></svg>
|
||||
</button>
|
||||
|
||||
<!-- 账号密码 / 注册 -->
|
||||
<!-- 账号密码 / 注册(两个面板用底部的文字链接互相切换,不放按钮) -->
|
||||
<div class="pane pane-account">
|
||||
<div class="tabs">
|
||||
<button :class="['tab', { active: tab === 'login' }]" type="button" @click="switchTab('login')">登录</button>
|
||||
<button :class="['tab', { active: tab === 'register' }]" type="button" @click="switchTab('register')">注册</button>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<div v-if="ok" class="alert alert-ok">{{ ok }}</div>
|
||||
|
||||
@ -248,6 +257,8 @@ onBeforeUnmount(() => {
|
||||
<button class="btn btn-block" :disabled="busy">登录</button>
|
||||
<p class="hint center">
|
||||
<RouterLink :to="{ name: 'forgot' }">忘记密码?</RouterLink>
|
||||
<span class="sep">·</span>
|
||||
<a href="#" @click.prevent="switchTab('register')">注册账号</a>
|
||||
</p>
|
||||
</form>
|
||||
|
||||
@ -285,12 +296,12 @@ onBeforeUnmount(() => {
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- 扫码(不放多余说明:二维码 + 返回入口) -->
|
||||
<!-- 扫码(二维码下方就一行:使用微信扫码登录) -->
|
||||
<div class="pane pane-wechat">
|
||||
<img v-if="qrUrl" class="qr-img" :src="qrUrl" width="160" height="160" alt="登录二维码" />
|
||||
<p v-else class="hint center">二维码生成中…</p>
|
||||
<p v-if="qrTip" class="hint center qr-tip">{{ qrTip }}</p>
|
||||
<p class="hint center"><a href="#" @click.prevent="switchTab('login')">返回账号密码登录</a></p>
|
||||
<p class="hint center qr-tip">使用微信扫码登录</p>
|
||||
<p v-if="qrTip" class="hint center">{{ qrTip }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -305,28 +316,6 @@ onBeforeUnmount(() => {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
flex: 1;
|
||||
border: 1px solid var(--border);
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 7px 0;
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
border-color: var(--brand);
|
||||
color: var(--brand);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-block {
|
||||
width: 100%;
|
||||
}
|
||||
@ -339,6 +328,11 @@ onBeforeUnmount(() => {
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
|
||||
.hint.center .sep {
|
||||
margin: 0 6px;
|
||||
color: var(--border);
|
||||
}
|
||||
|
||||
.pane-wechat {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
523
frontend/src/views/NvrsView.vue
Normal file
523
frontend/src/views/NvrsView.vue
Normal file
@ -0,0 +1,523 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* NVR 录像机管理
|
||||
*
|
||||
* 两段式添加摄像头:
|
||||
* 1. 填地址/账号 → 「拉取通道」:**页面直接调本机软件**(localhost:17300/api/hik/channels),
|
||||
* 走 8000 私有协议登录设备拿到通道列表;
|
||||
* 2. 勾选通道 → 提交到后端 `/api/web/nvrs/:id/channels` 落库成摄像头。
|
||||
*
|
||||
* 设备在用户内网,所以拉取只能由本机软件做;后端只存结果。
|
||||
* 密码在后端只存密文、接口不返回,因此**每次拉取需要重新输入密码**。
|
||||
*/
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import DataPager from '@/components/DataPager.vue';
|
||||
import ModalBox from '@/components/ModalBox.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import {
|
||||
createNvr,
|
||||
deleteNvr,
|
||||
fetchNvrCameras,
|
||||
fetchNvrCredential,
|
||||
fetchNvrs,
|
||||
importNvrChannels,
|
||||
updateNvr,
|
||||
} from '@/api/videoApi';
|
||||
import type { Nvr } from '@/api/video';
|
||||
import { LocalServiceError, fetchHikChannels, type HikChannelsPayload } from '@/api/local';
|
||||
import { formatTime } from '@/utils/format';
|
||||
|
||||
const list = ref<Nvr[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const okMsg = ref('');
|
||||
|
||||
// ---------------- 新增 / 编辑 ----------------
|
||||
const formOpen = ref(false);
|
||||
const saving = ref(false);
|
||||
const editing = ref<Nvr | null>(null);
|
||||
const form = reactive({ name: '', host: '', port: 8000, username: 'admin', password: '', remark: '' });
|
||||
|
||||
function openCreate() {
|
||||
editing.value = null;
|
||||
Object.assign(form, { name: '', host: '', port: 8000, username: 'admin', password: '', remark: '' });
|
||||
formOpen.value = true;
|
||||
}
|
||||
|
||||
function openEdit(nvr: Nvr) {
|
||||
editing.value = nvr;
|
||||
Object.assign(form, {
|
||||
name: nvr.name || '',
|
||||
host: nvr.host,
|
||||
port: nvr.port,
|
||||
username: nvr.username,
|
||||
password: '',
|
||||
remark: nvr.remark || '',
|
||||
});
|
||||
formOpen.value = true;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
error.value = '';
|
||||
okMsg.value = '';
|
||||
if (!form.host.trim()) { error.value = '请填写设备地址'; return; }
|
||||
if (!editing.value && !form.password) { error.value = '请填写登录密码'; return; }
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
if (editing.value) {
|
||||
const body: Record<string, unknown> = {
|
||||
name: form.name,
|
||||
host: form.host,
|
||||
port: Number(form.port) || 8000,
|
||||
username: form.username,
|
||||
remark: form.remark,
|
||||
};
|
||||
if (form.password) body.password = form.password;
|
||||
await updateNvr(editing.value.id, body);
|
||||
okMsg.value = 'NVR 已更新';
|
||||
} else {
|
||||
await createNvr({
|
||||
name: form.name,
|
||||
host: form.host.trim(),
|
||||
port: Number(form.port) || 8000,
|
||||
username: form.username.trim() || 'admin',
|
||||
password: form.password,
|
||||
remark: form.remark,
|
||||
});
|
||||
okMsg.value = 'NVR 已保存';
|
||||
}
|
||||
formOpen.value = false;
|
||||
await load(1);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '保存失败';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function doDelete(nvr: Nvr) {
|
||||
if (!window.confirm(`确认删除 NVR「${nvr.name || nvr.host}」?\n其下摄像头会一并删除,并从工作台解绑。`)) return;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await deleteNvr(nvr.id);
|
||||
okMsg.value = `已删除,连带移除 ${data.removedCameras} 个摄像头`;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '删除失败';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 拉取通道 ----------------
|
||||
const channelOpen = ref(false);
|
||||
const channelNvr = ref<Nvr | null>(null);
|
||||
const channelPassword = ref('');
|
||||
const pulling = ref(false);
|
||||
const pulling2 = ref(false);
|
||||
const payload = ref<HikChannelsPayload | null>(null);
|
||||
const channelError = ref('');
|
||||
const selected = ref<Set<number>>(new Set());
|
||||
const existingChannels = ref<Set<number>>(new Set());
|
||||
|
||||
async function openChannels(nvr: Nvr) {
|
||||
channelNvr.value = nvr;
|
||||
channelPassword.value = '';
|
||||
payload.value = null;
|
||||
channelError.value = '';
|
||||
selected.value = new Set();
|
||||
existingChannels.value = new Set();
|
||||
|
||||
try {
|
||||
const data = await fetchNvrCameras(nvr.id);
|
||||
existingChannels.value = new Set(data.list.map(item => item.channelNo));
|
||||
} catch {
|
||||
// 已有通道读取失败不影响拉取
|
||||
}
|
||||
|
||||
channelOpen.value = true;
|
||||
|
||||
// 库里已有密码时自动带出(密文存储 → 后端解密 → 直接给本机软件),
|
||||
// 用户不用每次手输;想用其他密码也可以在输入框里覆盖。
|
||||
try {
|
||||
const cred = await fetchNvrCredential(nvr.id);
|
||||
if (cred.hasPassword && cred.password) channelPassword.value = cred.password;
|
||||
} catch {
|
||||
// 取不到就保持为空,让用户手填
|
||||
}
|
||||
}
|
||||
|
||||
async function pull() {
|
||||
if (!channelNvr.value) return;
|
||||
if (!channelPassword.value) { channelError.value = '请填写设备密码'; return; }
|
||||
|
||||
pulling.value = true;
|
||||
channelError.value = '';
|
||||
payload.value = null;
|
||||
try {
|
||||
const res = await fetchHikChannels({
|
||||
host: channelNvr.value.host,
|
||||
port: channelNvr.value.port,
|
||||
user: channelNvr.value.username,
|
||||
password: channelPassword.value,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
channelError.value = res.message || `拉取失败(错误码 ${res.lastError ?? '未知'})`;
|
||||
return;
|
||||
}
|
||||
|
||||
payload.value = res;
|
||||
// 默认勾选「已配置、且还没导入过」的通道
|
||||
const next = new Set<number>();
|
||||
for (const item of res.data?.channels || []) {
|
||||
if (item.enabled && !existingChannels.value.has(item.channel)) next.add(item.channel);
|
||||
}
|
||||
selected.value = next;
|
||||
} catch (err) {
|
||||
if (err instanceof LocalServiceError) {
|
||||
if (err.status === 405) {
|
||||
channelError.value = '当前本机软件版本过旧(不支持 /api/hik/channels),请升级本机软件后重试。';
|
||||
} else {
|
||||
channelError.value = `本机软件不可用(${err.message})。请确认本机软件已启动。`;
|
||||
}
|
||||
} else {
|
||||
channelError.value = err instanceof Error ? err.message : '拉取失败';
|
||||
}
|
||||
} finally {
|
||||
pulling.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleAll(check: boolean) {
|
||||
const next = new Set<number>();
|
||||
if (check) {
|
||||
for (const item of payload.value?.data?.channels || []) {
|
||||
if (!existingChannels.value.has(item.channel)) next.add(item.channel);
|
||||
}
|
||||
}
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
function toggle(channel: number) {
|
||||
const next = new Set(selected.value);
|
||||
if (next.has(channel)) next.delete(channel);
|
||||
else next.add(channel);
|
||||
selected.value = next;
|
||||
}
|
||||
|
||||
async function importSelected() {
|
||||
if (!channelNvr.value || !payload.value?.data) return;
|
||||
if (!selected.value.size) { channelError.value = '请至少勾选一个通道'; return; }
|
||||
|
||||
pulling2.value = true;
|
||||
channelError.value = '';
|
||||
try {
|
||||
const baseName = channelNvr.value.name || channelNvr.value.host;
|
||||
const channels = (payload.value.data.channels || [])
|
||||
.filter(item => selected.value.has(item.channel))
|
||||
.map(item => ({
|
||||
channel: item.channel,
|
||||
type: item.type,
|
||||
// 优先用设备上的真实通道名(ISAPI 取到),没有就退成「NVR名-通道号」
|
||||
name: (item.name || '').trim() || `${baseName}-${item.channel}`,
|
||||
ip: item.ip,
|
||||
port: item.port,
|
||||
enabled: item.enabled,
|
||||
}));
|
||||
|
||||
const data = await importNvrChannels(channelNvr.value.id, {
|
||||
serialNumber: payload.value.data.serialNumber,
|
||||
channels,
|
||||
});
|
||||
|
||||
okMsg.value = `已导入 ${channels.length} 个通道(新增 ${data.created},更新 ${data.updated})`;
|
||||
channelOpen.value = false;
|
||||
await load();
|
||||
} catch (err) {
|
||||
channelError.value = err instanceof ApiError ? err.message : '导入失败';
|
||||
} finally {
|
||||
pulling2.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function cameraLabel(item: { channel: number; ip?: string | null; port?: number | null }) {
|
||||
return item.ip ? `${item.ip}${item.port ? `:${item.port}` : ''}` : '—';
|
||||
}
|
||||
|
||||
// ---------------- 列表 ----------------
|
||||
async function load(targetPage = page.value) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await fetchNvrs({ page: targetPage, pageSize: pageSize.value, keyword: keyword.value.trim() });
|
||||
list.value = data.list;
|
||||
total.value = data.total;
|
||||
page.value = data.page;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '加载失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
load(1);
|
||||
}
|
||||
|
||||
onMounted(() => load(1));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout fill>
|
||||
<template #title>NVR 录像机</template>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<div v-if="okMsg" class="alert alert-ok">{{ okMsg }}</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="toolbar">
|
||||
<input v-model="keyword" placeholder="搜索 名称 / 地址 / 序列号" @keyup.enter="search" />
|
||||
<button class="btn" :disabled="loading" @click="search">搜索</button>
|
||||
<button class="btn" @click="openCreate">+ 新增 NVR</button>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table class="table table-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>地址</th>
|
||||
<th>账号</th>
|
||||
<th>序列号</th>
|
||||
<th>已导入通道</th>
|
||||
<th>最近同步</th>
|
||||
<th style="width: 220px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="nvr in list" :key="nvr.id">
|
||||
<td>{{ nvr.name || '—' }}</td>
|
||||
<td><code>{{ nvr.host }}:{{ nvr.port }}</code></td>
|
||||
<td>{{ nvr.username }}</td>
|
||||
<td class="mono-sm">{{ nvr.serialNumber || '—' }}</td>
|
||||
<td>{{ nvr.channelCount }}</td>
|
||||
<td>{{ nvr.lastSyncAt ? formatTime(nvr.lastSyncAt) : '—' }}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm" @click="openChannels(nvr)">拉取通道</button>
|
||||
<button class="btn btn-sm btn-ghost" @click="openEdit(nvr)">编辑</button>
|
||||
<button class="btn btn-sm btn-danger" @click="doDelete(nvr)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!list.length && !loading">
|
||||
<td colspan="7" class="empty">还没有 NVR,点右上角「新增 NVR」添加。</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||
unit="台" @update:page="load" @update:page-size="size => (pageSize = size)" />
|
||||
</div>
|
||||
|
||||
<!-- 新增 / 编辑 -->
|
||||
<ModalBox :open="formOpen" :title="editing ? '编辑 NVR' : '新增 NVR'" @close="formOpen = false">
|
||||
<label class="field"><span>名称</span>
|
||||
<input v-model="form.name" placeholder="例如:1号仓库 NVR" />
|
||||
</label>
|
||||
<label class="field"><span>设备地址</span>
|
||||
<input v-model="form.host" placeholder="IP 或域名,例如 192.168.8.241" />
|
||||
</label>
|
||||
<label class="field"><span>SDK 端口</span>
|
||||
<input v-model.number="form.port" type="number" min="1" max="65535" placeholder="8000" />
|
||||
</label>
|
||||
<label class="field"><span>登录账号</span>
|
||||
<input v-model="form.username" placeholder="admin" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>密码{{ editing ? '(留空表示不修改)' : '' }}</span>
|
||||
<input v-model="form.password" type="password" :placeholder="editing ? '不修改请留空' : '设备登录密码'" />
|
||||
</label>
|
||||
<label class="field"><span>备注</span>
|
||||
<input v-model="form.remark" placeholder="可选" />
|
||||
</label>
|
||||
<p class="hint">密码只以密文形式存库,接口不会返回;拉取通道时需要再次输入。</p>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="formOpen = false">取消</button>
|
||||
<button class="btn" :disabled="saving" @click="save">{{ saving ? '保存中…' : '保存' }}</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 拉取通道 -->
|
||||
<ModalBox :open="channelOpen" title="拉取通道" width="720px" @close="channelOpen = false">
|
||||
<div v-if="channelNvr" class="pull-head">
|
||||
<div>
|
||||
<strong>{{ channelNvr.name || channelNvr.host }}</strong>
|
||||
<code>{{ channelNvr.host }}:{{ channelNvr.port }}</code>
|
||||
<span class="hint">账号 {{ channelNvr.username }}</span>
|
||||
</div>
|
||||
<div class="pull-form">
|
||||
<input v-model="channelPassword" type="password" placeholder="设备密码(新增时已保存,可覆盖)" @keyup.enter="pull" />
|
||||
<button class="btn" :disabled="pulling" @click="pull">{{ pulling ? '拉取中…' : '拉取通道' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="channelError" class="alert alert-error">{{ channelError }}</div>
|
||||
|
||||
<div v-if="payload?.data" class="pull-body">
|
||||
<div class="pull-meta">
|
||||
序列号 <code class="mono-sm">{{ payload.data.serialNumber }}</code>
|
||||
<span class="hint">通道 {{ payload.data.channels.length }} 个(数字 {{ payload.data.digitalChannelCount }})</span>
|
||||
<span class="hint">耗时 {{ payload.data.elapsedMs }}ms</span>
|
||||
<span v-if="payload.data.warning" class="warn">{{ payload.data.warning }}</span>
|
||||
</div>
|
||||
|
||||
<div class="pull-actions">
|
||||
<button class="btn btn-sm btn-ghost" @click="toggleAll(true)">全选未添加</button>
|
||||
<button class="btn btn-sm btn-ghost" @click="toggleAll(false)">清空</button>
|
||||
<span class="hint">已选 {{ selected.size }} 个</span>
|
||||
</div>
|
||||
|
||||
<div class="channel-grid">
|
||||
<label v-for="item in payload.data.channels" :key="item.channel"
|
||||
:class="['channel-item', { added: existingChannels.has(item.channel), off: !item.enabled }]">
|
||||
<input type="checkbox"
|
||||
:checked="selected.has(item.channel)"
|
||||
:disabled="existingChannels.has(item.channel)"
|
||||
@change="toggle(item.channel)" />
|
||||
<span class="ch-no">通道 {{ item.channel }}</span>
|
||||
<span :class="['ch-name', { 'ch-name-empty': !item.name }]">{{ (item.name || '').trim() || '未命名' }}</span>
|
||||
<span class="ch-ip">{{ cameraLabel(item) }}</span>
|
||||
<span v-if="!item.enabled" class="badge badge-off">未配置</span>
|
||||
<span v-else-if="existingChannels.has(item.channel)" class="badge">已添加</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="channelOpen = false">取消</button>
|
||||
<button class="btn" :disabled="pulling2 || !selected.size" @click="importSelected">
|
||||
{{ pulling2 ? '导入中…' : `导入所选(${selected.size})` }}
|
||||
</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.mono-sm {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
padding: 28px 0;
|
||||
}
|
||||
|
||||
.pull-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px dashed #e5e7eb;
|
||||
}
|
||||
|
||||
.pull-head code {
|
||||
margin: 0 8px;
|
||||
}
|
||||
|
||||
.pull-form {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.pull-form input {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.pull-body {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.pull-meta {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
font-size: 13px;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.pull-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.channel-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
|
||||
gap: 8px;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
padding: 2px;
|
||||
}
|
||||
|
||||
.channel-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.channel-item.added {
|
||||
background: #f8fafc;
|
||||
color: #94a3b8;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.channel-item.off {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.ch-no {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ch-ip {
|
||||
color: #64748b;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.ch-name {
|
||||
color: #334155;
|
||||
font-size: 12px;
|
||||
max-width: 120px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ch-name-empty {
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.warn {
|
||||
color: #b45309;
|
||||
}
|
||||
</style>
|
||||
@ -1,9 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
/** 个人中心:改资料 / 改密码(都是 `/api/web/me*`,用户 ID 取自令牌) */
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import { currentUser, setUser, type CurrentUser } from '@/composables/useAuth';
|
||||
import { clearToken, currentUser, setUser, type CurrentUser } from '@/composables/useAuth';
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const form = reactive({ nickname: '', email: '', phone: '' });
|
||||
const pwd = reactive({ oldPassword: '', newPassword: '', confirmPassword: '' });
|
||||
@ -61,7 +64,10 @@ async function savePassword() {
|
||||
pwd.oldPassword = '';
|
||||
pwd.newPassword = '';
|
||||
pwd.confirmPassword = '';
|
||||
ok.value = '密码已修改';
|
||||
// 改密后服务端会让「旧令牌」全部失效(password_changed_at),所以本页的令牌也不能用了:
|
||||
// 主动清掉并回登录页,用新密码重新登录(否则下一次请求才会 401,用户不知道发生了什么)
|
||||
clearToken();
|
||||
await router.replace({ name: 'login', query: { ok: '密码已修改,请用新密码重新登录' } });
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '修改失败';
|
||||
} finally {
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { onMounted, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import DataPager from '@/components/DataPager.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { fetchDevices, fetchRecords } from '@/api/web';
|
||||
import type { Device, ScanRecord } from '@/api/types';
|
||||
@ -15,7 +16,7 @@ const list = ref<ScanRecord[]>([]);
|
||||
const devices = ref<Device[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = 20;
|
||||
const pageSize = ref(20);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
|
||||
@ -27,15 +28,13 @@ const filter = reactive({
|
||||
endTime: '',
|
||||
});
|
||||
|
||||
const totalPages = () => Math.max(Math.ceil(total.value / pageSize), 1);
|
||||
|
||||
async function load(targetPage = page.value) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await fetchRecords({
|
||||
page: targetPage,
|
||||
pageSize,
|
||||
pageSize: pageSize.value,
|
||||
deviceId: filter.deviceId,
|
||||
channelId: filter.channelId.trim(),
|
||||
barcode: filter.barcode.trim(),
|
||||
@ -91,7 +90,6 @@ onMounted(async () => {
|
||||
<input v-model="filter.endTime" type="datetime-local" title="结束时间" />
|
||||
<button class="btn" :disabled="loading" @click="load(1)">查询</button>
|
||||
<button class="btn btn-ghost" :disabled="loading" @click="reset">重置</button>
|
||||
<span class="hint">共 {{ total }} 条</span>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
@ -120,11 +118,8 @@ onMounted(async () => {
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<button class="btn btn-ghost btn-sm" :disabled="page <= 1 || loading" @click="load(page - 1)">上一页</button>
|
||||
<span class="hint">{{ page }} / {{ totalPages() }}</span>
|
||||
<button class="btn btn-ghost btn-sm" :disabled="page >= totalPages() || loading" @click="load(page + 1)">下一页</button>
|
||||
</div>
|
||||
<DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||
unit="条" @update:page="load" @update:page-size="size => (pageSize = size)" />
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
@ -24,7 +24,7 @@ async function submit() {
|
||||
try {
|
||||
await api.post('/api/web/auth/reset', { token: token.value, password: password.value }, { auth: false });
|
||||
done.value = true;
|
||||
setTimeout(() => router.replace({ name: 'login' }), 1200);
|
||||
setTimeout(() => router.replace({ name: 'login', query: { ok: '密码已重置,请用新密码登录' } }), 1200);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '重置失败,请稍后再试';
|
||||
} finally {
|
||||
|
||||
505
frontend/src/views/SubjectsView.vue
Normal file
505
frontend/src/views/SubjectsView.vue
Normal file
@ -0,0 +1,505 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 主体 / 成员
|
||||
*
|
||||
* - 列表:我加入的主体(角色 / 使用期限 / 成员数),可切换、续期(管理员)
|
||||
* - 创建主体:默认赠送 7 天使用期限(天数由后端下发 `trialDays`)
|
||||
* - 成员管理:按姓名快速添加(先不绑账号)→ 生成绑定码 → 手机扫码确认后绑定账号
|
||||
*/
|
||||
import { computed, onMounted, onBeforeUnmount, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import ModalBox from '@/components/ModalBox.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import {
|
||||
addSubjectMember,
|
||||
createMemberBindCode,
|
||||
createSubject,
|
||||
fetchMemberBindStatus,
|
||||
fetchSubjectMembers,
|
||||
removeSubjectMember,
|
||||
updateSubject,
|
||||
type MemberBindCode,
|
||||
} from '@/api/subjectApi';
|
||||
import {
|
||||
applySubjects,
|
||||
currentSubjectId,
|
||||
loadSubjects,
|
||||
setSubjectId,
|
||||
subjects,
|
||||
trialDays,
|
||||
type SubjectItem,
|
||||
type SubjectMemberItem,
|
||||
} from '@/composables/useSubject';
|
||||
import { formatTime } from '@/utils/format';
|
||||
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const ok = ref('');
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
await loadSubjects();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '主体列表加载失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 创建主体 ----------------
|
||||
const createOpen = ref(false);
|
||||
const saving = ref(false);
|
||||
const form = reactive({ name: '', remark: '' });
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, { name: '', remark: '' });
|
||||
createOpen.value = true;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
if (!form.name.trim()) {
|
||||
error.value = '请填写主体名称';
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const created = await createSubject({ name: form.name.trim(), remark: form.remark || undefined });
|
||||
applySubjects([ ...subjects.value, created ], trialDays.value);
|
||||
setSubjectId(created.id);
|
||||
createOpen.value = false;
|
||||
ok.value = `主体「${created.name}」已创建(赠送 ${trialDays.value} 天,到期:${formatTime(created.expireAt)})`;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '创建失败';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 切换 / 续期 ----------------
|
||||
function useThis(item: SubjectItem) {
|
||||
if (item.expired) {
|
||||
error.value = `「${item.name}」已到期,请先续期`;
|
||||
return;
|
||||
}
|
||||
setSubjectId(item.id);
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
const renewing = ref(0);
|
||||
async function renew(item: SubjectItem) {
|
||||
const input = window.prompt(`给「${item.name}」续期多少天?(1~3650)`, '30');
|
||||
if (!input) return;
|
||||
const days = Number(input);
|
||||
if (!Number.isFinite(days) || days <= 0) {
|
||||
error.value = '续期天数必须是正整数';
|
||||
return;
|
||||
}
|
||||
renewing.value = item.id;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const updated = await updateSubject(item.id, { extendDays: Math.round(days) });
|
||||
ok.value = `「${item.name}」已续期,新到期时间:${formatTime(updated.expireAt)}`;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '续期失败';
|
||||
} finally {
|
||||
renewing.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 成员管理 ----------------
|
||||
const memberOpen = ref(false);
|
||||
const memberSubject = ref<SubjectItem | null>(null);
|
||||
const members = ref<SubjectMemberItem[]>([]);
|
||||
const membersLoading = ref(false);
|
||||
const newMemberName = ref('');
|
||||
const addingMember = ref(false);
|
||||
|
||||
async function openMembers(item: SubjectItem) {
|
||||
memberSubject.value = item;
|
||||
memberOpen.value = true;
|
||||
members.value = [];
|
||||
await loadMembers();
|
||||
}
|
||||
|
||||
async function loadMembers() {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
membersLoading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await fetchSubjectMembers(subject.id);
|
||||
members.value = data.list;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '成员加载失败';
|
||||
} finally {
|
||||
membersLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function addMember() {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
const name = newMemberName.value.trim();
|
||||
if (!name) {
|
||||
error.value = '请填写成员姓名';
|
||||
return;
|
||||
}
|
||||
addingMember.value = true;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
const created = await addSubjectMember(subject.id, { name });
|
||||
members.value = [ ...members.value, created ];
|
||||
newMemberName.value = '';
|
||||
ok.value = `成员「${created.name}」已添加,可生成绑定码让他扫码绑定账号`;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '添加成员失败';
|
||||
} finally {
|
||||
addingMember.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMember(member: SubjectMemberItem) {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
if (!window.confirm(`确认移除成员「${member.name}」?`)) return;
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
await removeSubjectMember(subject.id, member.id);
|
||||
members.value = members.value.filter(item => item.id !== member.id);
|
||||
ok.value = `成员「${member.name}」已移除`;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '移除失败';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 成员绑定码 ----------------
|
||||
const bindOpen = ref(false);
|
||||
const bindData = ref<MemberBindCode | null>(null);
|
||||
const bindStatus = ref('');
|
||||
const bindBoundName = ref('');
|
||||
let bindTimer: number | null = null;
|
||||
|
||||
async function openBindCode(member: SubjectMemberItem) {
|
||||
const subject = memberSubject.value;
|
||||
if (!subject) return;
|
||||
error.value = '';
|
||||
bindBoundName.value = '';
|
||||
try {
|
||||
const data = await createMemberBindCode(subject.id, member.id);
|
||||
bindData.value = data;
|
||||
bindStatus.value = 'pending';
|
||||
bindOpen.value = true;
|
||||
startBindPolling(data.code);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '绑定码生成失败';
|
||||
}
|
||||
}
|
||||
|
||||
function startBindPolling(code: string) {
|
||||
stopBindPolling();
|
||||
bindTimer = window.setInterval(async () => {
|
||||
try {
|
||||
const status = await fetchMemberBindStatus(code);
|
||||
if (status.status === 'confirmed') {
|
||||
bindStatus.value = 'confirmed';
|
||||
bindBoundName.value = status.boundName || '';
|
||||
stopBindPolling();
|
||||
await loadMembers();
|
||||
} else if (status.status === 'expired') {
|
||||
bindStatus.value = 'expired';
|
||||
stopBindPolling();
|
||||
}
|
||||
} catch {
|
||||
/* 网络抖动忽略,下一轮继续 */
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function stopBindPolling() {
|
||||
if (bindTimer !== null) {
|
||||
window.clearInterval(bindTimer);
|
||||
bindTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function closeBind() {
|
||||
stopBindPolling();
|
||||
bindOpen.value = false;
|
||||
bindData.value = null;
|
||||
}
|
||||
|
||||
function copyBindUrl() {
|
||||
if (!bindData.value) return;
|
||||
navigator.clipboard?.writeText(bindData.value.bindUrl).then(
|
||||
() => { ok.value = '绑定链接已复制'; },
|
||||
() => { error.value = '复制失败,请手动选择二维码下方的链接'; },
|
||||
);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(stopBindPolling);
|
||||
|
||||
/** 列表里标出「当前主体」 */
|
||||
const currentId = computed(() => currentSubjectId.value);
|
||||
const canRenew = (item: SubjectItem) => Number(item.role) === 1;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout fill>
|
||||
<template #title>主体 / 成员</template>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<div v-if="ok" class="alert alert-ok">{{ ok }}</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="toolbar">
|
||||
<button class="btn" @click="openCreate">+ 创建主体</button>
|
||||
<button class="btn btn-ghost" :disabled="loading" @click="load">刷新</button>
|
||||
<span class="hint">
|
||||
新建主体默认赠送 {{ trialDays }} 天使用期限;到期后主体内的设备 / 录像机 / 摄像头 / 工作台 / 扫码记录都会停用
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!subjects.length && !loading" class="empty-block">
|
||||
<p>你还没有加入任何主体。</p>
|
||||
<p class="hint">创建主体后才会出现「设备管理 / NVR 录像机 / 摄像头 / 工作台 / 扫码记录」等菜单。</p>
|
||||
<button class="btn" @click="openCreate">+ 创建主体</button>
|
||||
</div>
|
||||
|
||||
<div v-else class="table-wrap">
|
||||
<table class="table table-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>主体名称</th>
|
||||
<th>我的角色</th>
|
||||
<th>使用期限</th>
|
||||
<th>成员</th>
|
||||
<th>备注</th>
|
||||
<th style="width: 300px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in subjects" :key="item.id">
|
||||
<td>
|
||||
{{ item.name }}
|
||||
<span v-if="item.id === currentId" class="badge badge-ok">当前</span>
|
||||
<span v-if="item.expired" class="badge badge-off">已到期</span>
|
||||
</td>
|
||||
<td>
|
||||
<span :class="['badge', Number(item.role) === 1 ? 'badge-group' : 'badge-single']">
|
||||
{{ Number(item.role) === 1 ? '管理员' : '成员' }}
|
||||
</span>
|
||||
<span v-if="item.memberName && item.memberName !== (Number(item.role) === 1 ? '管理员' : '成员')" class="muted">
|
||||
{{ item.memberName }}
|
||||
</span>
|
||||
</td>
|
||||
<td :class="{ 'text-danger': item.expired }">{{ formatTime(item.expireAt) }}</td>
|
||||
<td>{{ item.memberCount ?? 0 }}</td>
|
||||
<td class="muted">{{ item.remark || '—' }}</td>
|
||||
<td class="ops">
|
||||
<button class="btn btn-sm" :disabled="item.id === currentId || item.expired" @click="useThis(item)">
|
||||
进入
|
||||
</button>
|
||||
<button class="btn btn-sm btn-ghost" @click="openMembers(item)">成员</button>
|
||||
<button
|
||||
v-if="canRenew(item)"
|
||||
class="btn btn-sm btn-ghost"
|
||||
:disabled="renewing === item.id"
|
||||
@click="renew(item)"
|
||||
>
|
||||
{{ renewing === item.id ? '续期中…' : '续期' }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 创建主体 -->
|
||||
<ModalBox :open="createOpen" title="创建主体" @close="createOpen = false">
|
||||
<label class="field"><span>主体名称</span>
|
||||
<input v-model="form.name" placeholder="例如:广州云仓 / 一号门店" maxlength="64" />
|
||||
</label>
|
||||
<label class="field"><span>备注</span>
|
||||
<input v-model="form.remark" placeholder="可选" maxlength="255" />
|
||||
</label>
|
||||
<p class="hint">
|
||||
创建后你将成为该主体的<b>管理员</b>;使用期限默认赠送 <b>{{ trialDays }}</b> 天,到期前可续期。
|
||||
</p>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="createOpen = false">取消</button>
|
||||
<button class="btn" :disabled="saving" @click="save">{{ saving ? '创建中…' : '创建' }}</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 成员管理 -->
|
||||
<ModalBox
|
||||
:open="memberOpen"
|
||||
:title="`成员管理 · ${memberSubject?.name || ''}`"
|
||||
@close="memberOpen = false"
|
||||
>
|
||||
<div class="member-add">
|
||||
<input v-model="newMemberName" placeholder="输入成员姓名,回车快速添加" maxlength="32" @keyup.enter="addMember" />
|
||||
<button class="btn" :disabled="addingMember" @click="addMember">
|
||||
{{ addingMember ? '添加中…' : '添加成员' }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="hint">
|
||||
添加后成员还没有账号:点「绑定码」出二维码,让成员用手机扫码并登录确认,即可绑定到该成员。
|
||||
</p>
|
||||
|
||||
<div class="table-wrap member-table">
|
||||
<table class="table table-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>姓名</th>
|
||||
<th>角色</th>
|
||||
<th>绑定账号</th>
|
||||
<th style="width: 190px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="member in members" :key="member.id">
|
||||
<td>{{ member.name }}</td>
|
||||
<td>
|
||||
<span :class="['badge', member.role === 1 ? 'badge-group' : 'badge-single']">
|
||||
{{ member.role === 1 ? '管理员' : '成员' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<template v-if="member.user">
|
||||
{{ member.user.nickname || member.user.username }}
|
||||
<span v-if="member.wechatBound" class="badge badge-ok">已绑微信</span>
|
||||
</template>
|
||||
<span v-else class="muted">未绑定</span>
|
||||
</td>
|
||||
<td class="ops">
|
||||
<button v-if="!member.userId" class="btn btn-sm" @click="openBindCode(member)">绑定码</button>
|
||||
<button
|
||||
v-if="member.role !== 1"
|
||||
class="btn btn-sm btn-ghost"
|
||||
@click="removeMember(member)"
|
||||
>
|
||||
移除
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!members.length && !membersLoading">
|
||||
<td colspan="4" class="empty">还没有成员</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="memberOpen = false">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 成员绑定码 -->
|
||||
<ModalBox :open="bindOpen" title="成员绑定码" @close="closeBind">
|
||||
<div v-if="bindData" class="bind-box">
|
||||
<img v-if="bindStatus !== 'expired'" :src="bindData.qrUrl" alt="成员绑定二维码" class="bind-qr" />
|
||||
<p class="bind-code">绑定码:<b>{{ bindData.code }}</b></p>
|
||||
<p class="hint">成员用手机扫码(或打开下面的链接)→ 登录后点「确认绑定」,即成为「{{ bindData.memberName }}」。</p>
|
||||
<p class="bind-url">{{ bindData.bindUrl }}</p>
|
||||
<p v-if="bindStatus === 'pending'" class="hint">等待扫码确认…({{ Math.round(bindData.expiresIn / 60) }} 分钟内有效)</p>
|
||||
<p v-else-if="bindStatus === 'confirmed'" class="alert alert-ok">
|
||||
已绑定:{{ bindBoundName || '账号' }}
|
||||
</p>
|
||||
<p v-else-if="bindStatus === 'expired'" class="alert alert-error">绑定码已过期,请重新生成</p>
|
||||
</div>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="copyBindUrl">复制链接</button>
|
||||
<button class="btn" @click="closeBind">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.member-add {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.member-add input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.member-table {
|
||||
max-height: 320px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.empty-block {
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-block p {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.empty-block .btn {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.bind-box {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bind-qr {
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 6px;
|
||||
}
|
||||
|
||||
.bind-code {
|
||||
font-size: 15px;
|
||||
margin: 10px 0 4px;
|
||||
}
|
||||
|
||||
.bind-url {
|
||||
word-break: break-all;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.text-danger {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.ops {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.ops .btn + .btn {
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
padding: 24px 0;
|
||||
}
|
||||
</style>
|
||||
@ -1,27 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 手机扫码后打开的页面:`/wechat?spm=1.0.<码>.1`
|
||||
* 手机扫码后打开的页面,两种用途:
|
||||
*
|
||||
* 两种确认方式:
|
||||
* - 配了微信:扫码页(本页)会把手机重定向到公众号网页授权,回来时**由后端的
|
||||
* `/api/wechat/callback` 处理完再把浏览器转回本页**(带 `?ok=1|0&message=`);
|
||||
* - 没配微信(本机默认):要求手机端**已登录**(本地有令牌),点确认调 `POST /api/wechat/confirm`。
|
||||
* 1. **扫码登录**:`/wechat?spm=1.0.<码>.1`
|
||||
* - 配了微信:本页把手机重定向到公众号网页授权,回来时由后端 `/api/wechat/callback`
|
||||
* 处理完再把浏览器转回本页(带 `?ok=1|0&message=`);
|
||||
* - 没配微信(本机默认):要求手机端**已登录**,点确认调 `POST /api/wechat/confirm`。
|
||||
* 2. **主体成员绑定**:`/wechat?bind=<码>`
|
||||
* - 已登录的账号点「确认绑定」→ `POST /api/subject/member-bind/confirm`
|
||||
* → 该账号被写进主体成员,之后可以进入这个主体。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import { isLoggedIn } from '@/composables/useAuth';
|
||||
import { fetchMemberBindStatus, confirmMemberBind, type MemberBindStatus } from '@/api/subjectApi';
|
||||
import { loadSubjects } from '@/composables/useSubject';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
/** 成员绑定码(`?bind=`) */
|
||||
const bindCode = computed(() => String(route.query.bind || '').toUpperCase());
|
||||
|
||||
const spm = computed(() => String(route.query.spm || ''));
|
||||
const code = computed(() => spm.value.split('.').find(seg => /^[0-9A-Za-z]{6}$/.test(seg))?.toUpperCase() || '');
|
||||
|
||||
const busy = ref(false);
|
||||
const done = ref(route.query.ok === '1');
|
||||
const error = ref(route.query.ok === '0' ? String(route.query.message || '扫码失败,请重新扫码') : '');
|
||||
const tip = ref('');
|
||||
|
||||
// ---------------- 成员绑定 ----------------
|
||||
const bindInfo = ref<MemberBindStatus | null>(null);
|
||||
const bindDone = ref(false);
|
||||
const bindError = ref('');
|
||||
let timer: number | null = null;
|
||||
|
||||
async function refreshBind() {
|
||||
if (!bindCode.value) return;
|
||||
try {
|
||||
bindInfo.value = await fetchMemberBindStatus(bindCode.value);
|
||||
if (bindInfo.value.status === 'expired') bindError.value = '绑定码已过期,请让管理员重新生成';
|
||||
if (bindInfo.value.status === 'confirmed') {
|
||||
bindDone.value = true;
|
||||
stopPolling();
|
||||
}
|
||||
} catch (err) {
|
||||
bindError.value = err instanceof ApiError ? err.message : '绑定码查询失败';
|
||||
}
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (timer !== null) {
|
||||
window.clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBind() {
|
||||
bindError.value = '';
|
||||
if (!isLoggedIn()) {
|
||||
// 手机端没登录 → 去登录,登录完回到本页(绑定码在 URL 里,不会丢)
|
||||
router.replace({ name: 'login', query: { redirect: route.fullPath } });
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
const data = await confirmMemberBind(bindCode.value);
|
||||
bindDone.value = true;
|
||||
tip.value = `已绑定为「${data.memberName}」(${data.subjectName})`;
|
||||
stopPolling();
|
||||
// 新加入的主体要出现在切换器里
|
||||
loadSubjects().catch(() => undefined);
|
||||
} catch (err) {
|
||||
bindError.value = err instanceof ApiError ? err.message : '绑定失败,请稍后再试';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 扫码登录 ----------------
|
||||
async function confirm() {
|
||||
error.value = '';
|
||||
if (!isLoggedIn()) {
|
||||
@ -38,19 +97,52 @@ async function confirm() {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (bindCode.value) {
|
||||
refreshBind();
|
||||
timer = window.setInterval(refreshBind, 3000);
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bare-page">
|
||||
<div class="card bare-card">
|
||||
<h1 class="title">确认登录</h1>
|
||||
<!-- ============ 成员绑定 ============ -->
|
||||
<template v-if="bindCode">
|
||||
<h1 class="title">确认绑定主体成员</h1>
|
||||
|
||||
<div v-if="done" class="alert alert-ok">已确认登录,请回到电脑上继续操作。</div>
|
||||
<div v-else-if="!code" class="alert alert-error">登录码格式不对,请重新扫码。</div>
|
||||
<div v-if="bindDone" class="alert alert-ok">
|
||||
{{ tip || '已绑定成功' }},可以回到电脑上继续操作。
|
||||
</div>
|
||||
<div v-else-if="bindError" class="alert alert-error">{{ bindError }}</div>
|
||||
<template v-else>
|
||||
<p class="code-line">绑定码 <code>{{ bindCode }}</code></p>
|
||||
<p v-if="bindInfo?.memberName" class="hint center">
|
||||
将把当前登录账号绑定为主体「{{ bindInfo.subjectName || bindInfo.subjectId }}」的成员
|
||||
<b>{{ bindInfo.memberName }}</b>
|
||||
</p>
|
||||
<p v-if="!isLoggedIn()" class="hint center">请先登录你的账号,登录后会自动回到本页。</p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirmBind">
|
||||
{{ isLoggedIn() ? (busy ? '绑定中…' : '确认绑定') : '去登录' }}
|
||||
</button>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- ============ 扫码登录 ============ -->
|
||||
<template v-else>
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<p class="code-line">登录码 <code>{{ code }}</code></p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirm">确认登录</button>
|
||||
<h1 class="title">确认登录</h1>
|
||||
|
||||
<div v-if="done" class="alert alert-ok">已确认登录,请回到电脑上继续操作。</div>
|
||||
<div v-else-if="!code" class="alert alert-error">登录码格式不对,请重新扫码。</div>
|
||||
<template v-else>
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<p class="code-line">登录码 <code>{{ code }}</code></p>
|
||||
<button class="btn btn-block" :disabled="busy" @click="confirm">确认登录</button>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@ -72,4 +164,8 @@ async function confirm() {
|
||||
text-align: center;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.center {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
|
||||
788
frontend/src/views/WorkstationsView.vue
Normal file
788
frontend/src/views/WorkstationsView.vue
Normal file
@ -0,0 +1,788 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 工作台管理
|
||||
*
|
||||
* 一个工作台可以绑定:
|
||||
* - 多个摄像头(从「已添加的摄像头」里选)
|
||||
* - 多个扫码通道(从自己的中控上报的通道里选)
|
||||
*
|
||||
* 绑定/解绑都走后端 `/api/web/workstations/:id/{cameras,scan-channels}`,
|
||||
* 接口返回绑定后的完整详情,页面直接用它刷新,不用二次查询。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import DataPager from '@/components/DataPager.vue';
|
||||
import ModalBox from '@/components/ModalBox.vue';
|
||||
import CameraLayoutCanvas from '@/components/CameraLayoutCanvas.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import {
|
||||
bindWorkstationCameras,
|
||||
bindWorkstationScanChannels,
|
||||
createWorkstation,
|
||||
deleteWorkstation,
|
||||
fetchAvailableScanChannels,
|
||||
fetchCameraOptions,
|
||||
fetchWorkstation,
|
||||
fetchWorkstations,
|
||||
unbindWorkstationCamera,
|
||||
unbindWorkstationScanChannel,
|
||||
updateWorkstation,
|
||||
} from '@/api/videoApi';
|
||||
import type { AvailableScanChannel, Camera, Workstation, WorkstationDetail } from '@/api/video';
|
||||
import { formatTime } from '@/utils/format';
|
||||
|
||||
const list = ref<Workstation[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
/** 类型筛选:'' 全部 / 1 散单 / 2 团购 */
|
||||
const typeFilter = ref<number | ''>('');
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const okMsg = ref('');
|
||||
|
||||
// ---------------- 新增 / 编辑 ----------------
|
||||
const formOpen = ref(false);
|
||||
const saving = ref(false);
|
||||
const editing = ref<Workstation | null>(null);
|
||||
const form = reactive({
|
||||
name: '',
|
||||
wsType: 1,
|
||||
recordBeforeSec: 60,
|
||||
recordAfterSec: 60,
|
||||
recordMaxSec: 240,
|
||||
remark: '',
|
||||
});
|
||||
|
||||
/** 录制范围的基准点:团购 = 扫码时间,散单 = 任务结束时间 */
|
||||
const rangeBaseLabel = computed(() => (form.wsType === 2 ? '扫码时间' : '任务结束时间'));
|
||||
|
||||
function openCreate() {
|
||||
editing.value = null;
|
||||
Object.assign(form, { name: '', wsType: 1, recordBeforeSec: 60, recordAfterSec: 60, recordMaxSec: 240, remark: '' });
|
||||
formOpen.value = true;
|
||||
}
|
||||
|
||||
function openEdit(item: Workstation) {
|
||||
editing.value = item;
|
||||
Object.assign(form, {
|
||||
name: item.name || '',
|
||||
wsType: Number(item.wsType) === 2 ? 2 : 1,
|
||||
recordBeforeSec: Number(item.recordBeforeSec ?? 60),
|
||||
recordAfterSec: Number(item.recordAfterSec ?? 60),
|
||||
recordMaxSec: Number(item.recordMaxSec ?? 240),
|
||||
remark: item.remark || '',
|
||||
});
|
||||
formOpen.value = true;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
error.value = '';
|
||||
okMsg.value = '';
|
||||
if (!form.name.trim()) { error.value = '请填写工作台名称'; return; }
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
const payload = {
|
||||
name: form.name.trim(),
|
||||
wsType: form.wsType,
|
||||
recordBeforeSec: Number(form.recordBeforeSec) || 0,
|
||||
recordAfterSec: Number(form.recordAfterSec) || 0,
|
||||
// 团购没有独立的「最大录制时长」(= 扫码前 + 扫码后),不传
|
||||
...(form.wsType === 2 ? {} : { recordMaxSec: Number(form.recordMaxSec) || 240 }),
|
||||
remark: form.remark,
|
||||
};
|
||||
|
||||
if (editing.value) {
|
||||
await updateWorkstation(editing.value.id, payload);
|
||||
okMsg.value = '工作台已更新';
|
||||
} else {
|
||||
await createWorkstation(payload);
|
||||
okMsg.value = '工作台已创建';
|
||||
}
|
||||
formOpen.value = false;
|
||||
await load(1);
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '保存失败';
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function doDelete(item: Workstation) {
|
||||
if (!window.confirm(`确认删除工作台「${item.name || item.code}」?绑定关系会一并清除(摄像头本身不受影响)。`)) return;
|
||||
error.value = '';
|
||||
try {
|
||||
await deleteWorkstation(item.id);
|
||||
okMsg.value = '工作台已删除';
|
||||
if (detail.value?.id === item.id) detail.value = null;
|
||||
await load();
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '删除失败';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 绑定管理 ----------------
|
||||
const detailOpen = ref(false);
|
||||
const detail = ref<WorkstationDetail | null>(null);
|
||||
const detailLoading = ref(false);
|
||||
const detailError = ref('');
|
||||
|
||||
const cameraOptions = ref<Camera[]>([]);
|
||||
const scanOptions = ref<AvailableScanChannel[]>([]);
|
||||
const showCameraPicker = ref(false);
|
||||
const showScanPicker = ref(false);
|
||||
/** 合并输出预览(从列表「预览」进入,不需要先开绑定管理) */
|
||||
const showMergedPreview = ref(false);
|
||||
const previewDetail = ref<WorkstationDetail | null>(null);
|
||||
const previewLoading = ref(false);
|
||||
const previewError = ref('');
|
||||
|
||||
async function openMergedPreview(item: Workstation) {
|
||||
showMergedPreview.value = true;
|
||||
previewDetail.value = null;
|
||||
previewError.value = '';
|
||||
previewLoading.value = true;
|
||||
|
||||
try {
|
||||
previewDetail.value = await fetchWorkstation(item.id);
|
||||
} catch (err) {
|
||||
previewError.value = err instanceof ApiError ? err.message : '加载布局失败';
|
||||
} finally {
|
||||
previewLoading.value = false;
|
||||
}
|
||||
}
|
||||
const pickedCameras = ref<Set<number>>(new Set());
|
||||
const pickedChannels = ref<Set<string>>(new Set());
|
||||
const busy = ref(false);
|
||||
|
||||
async function openDetail(item: Workstation) {
|
||||
detailOpen.value = true;
|
||||
detail.value = null;
|
||||
detailError.value = '';
|
||||
cameraOptions.value = [];
|
||||
scanOptions.value = [];
|
||||
showCameraPicker.value = false;
|
||||
showScanPicker.value = false;
|
||||
showMergedPreview.value = false;
|
||||
pickedCameras.value = new Set();
|
||||
pickedChannels.value = new Set();
|
||||
|
||||
detailLoading.value = true;
|
||||
try {
|
||||
detail.value = await fetchWorkstation(item.id);
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '加载失败';
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openCameraPicker() {
|
||||
showCameraPicker.value = true;
|
||||
pickedCameras.value = new Set();
|
||||
try {
|
||||
const data = await fetchCameraOptions();
|
||||
cameraOptions.value = data.list;
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '摄像头列表加载失败';
|
||||
}
|
||||
}
|
||||
|
||||
async function openScanPicker() {
|
||||
showScanPicker.value = true;
|
||||
pickedChannels.value = new Set();
|
||||
try {
|
||||
const data = await fetchAvailableScanChannels();
|
||||
scanOptions.value = data.list;
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '扫码通道列表加载失败';
|
||||
}
|
||||
}
|
||||
|
||||
function boundCameraIds() {
|
||||
return new Set((detail.value?.cameras || []).map(link => Number(link.cameraId)));
|
||||
}
|
||||
|
||||
function boundScanKeys() {
|
||||
return new Set((detail.value?.scanChannels || []).map(link => `${link.scannerId}:${link.channelId}`));
|
||||
}
|
||||
|
||||
/** 该摄像头是不是被**其他**工作台占着(本工作台已绑定的直接不列出) */
|
||||
function cameraTakenByOther(cam: Camera): boolean {
|
||||
const bound = cam.boundWorkstation;
|
||||
if (!bound) return false;
|
||||
return Number(bound.id) !== Number(detail.value?.id);
|
||||
}
|
||||
|
||||
/** 该扫码通道是不是被**其他**工作台占着 */
|
||||
function channelTakenByOther(item: AvailableScanChannel): boolean {
|
||||
const bound = item.boundWorkstation;
|
||||
if (!bound) return false;
|
||||
return Number(bound.id) !== Number(detail.value?.id);
|
||||
}
|
||||
|
||||
/** 选择器里可选的项(排除本工作台已绑 + 其他工作台已占) */
|
||||
const cameraPickable = computed(() => cameraOptions.value.filter(cam => !boundCameraIds().has(Number(cam.id))));
|
||||
const scanPickable = computed(() => scanOptions.value.filter(item => !boundScanKeys().has(`${item.scannerId}:${item.channelId}`)));
|
||||
|
||||
function toggleCamera(id: number) {
|
||||
const cam = cameraOptions.value.find(item => Number(item.id) === Number(id));
|
||||
if (cam && cameraTakenByOther(cam)) return; // 已被其他工作台占用,不允许勾选
|
||||
|
||||
const next = new Set(pickedCameras.value);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
pickedCameras.value = next;
|
||||
}
|
||||
|
||||
function toggleChannel(key: string) {
|
||||
const item = scanOptions.value.find(ch => `${ch.scannerId}:${ch.channelId}` === key);
|
||||
if (item && channelTakenByOther(item)) return;
|
||||
|
||||
const next = new Set(pickedChannels.value);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
pickedChannels.value = next;
|
||||
}
|
||||
|
||||
async function confirmBindCameras() {
|
||||
if (!detail.value || !pickedCameras.value.size) return;
|
||||
busy.value = true;
|
||||
detailError.value = '';
|
||||
try {
|
||||
detail.value = await bindWorkstationCameras(detail.value.id, [ ...pickedCameras.value ]);
|
||||
showCameraPicker.value = false;
|
||||
pickedCameras.value = new Set();
|
||||
await load();
|
||||
okMsg.value = '摄像头已绑定';
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '绑定失败';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBindChannels() {
|
||||
if (!detail.value || !pickedChannels.value.size) return;
|
||||
busy.value = true;
|
||||
detailError.value = '';
|
||||
try {
|
||||
const items = [ ...pickedChannels.value ].map(key => {
|
||||
const [ scannerId, ...rest ] = key.split(':');
|
||||
const channelId = rest.join(':');
|
||||
const found = scanOptions.value.find(item => Number(item.scannerId) === Number(scannerId) && item.channelId === channelId);
|
||||
return {
|
||||
scannerId: Number(scannerId),
|
||||
channelId,
|
||||
channelName: found?.channelName || '',
|
||||
};
|
||||
});
|
||||
|
||||
detail.value = await bindWorkstationScanChannels(detail.value.id, items);
|
||||
showScanPicker.value = false;
|
||||
pickedChannels.value = new Set();
|
||||
await load();
|
||||
okMsg.value = '扫码通道已绑定';
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '绑定失败';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 布局保存后,后端会把整个详情返回(含最新位置/大小) */
|
||||
function onLayoutChanged(data: WorkstationDetail) {
|
||||
detail.value = data;
|
||||
}
|
||||
|
||||
async function unbindCamera(cameraId: number) {
|
||||
if (!detail.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
detail.value = await unbindWorkstationCamera(detail.value.id, cameraId);
|
||||
await load();
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '解绑失败';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function unbindScan(linkId: number) {
|
||||
if (!detail.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
detail.value = await unbindWorkstationScanChannel(detail.value.id, linkId);
|
||||
await load();
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof ApiError ? err.message : '解绑失败';
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 列表 ----------------
|
||||
async function load(targetPage = page.value) {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const data = await fetchWorkstations({
|
||||
page: targetPage,
|
||||
pageSize: pageSize.value,
|
||||
keyword: keyword.value.trim(),
|
||||
wsType: typeFilter.value,
|
||||
});
|
||||
list.value = data.list;
|
||||
total.value = data.total;
|
||||
page.value = data.page;
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '加载失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
load(1);
|
||||
}
|
||||
|
||||
onMounted(() => load(1));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout fill>
|
||||
<template #title>工作台</template>
|
||||
|
||||
<div v-if="error" class="alert alert-error">{{ error }}</div>
|
||||
<div v-if="okMsg" class="alert alert-ok">{{ okMsg }}</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="toolbar">
|
||||
<input v-model="keyword" placeholder="搜索 名称" @keyup.enter="search" />
|
||||
<select v-model="typeFilter" @change="search">
|
||||
<option value="">全部类型</option>
|
||||
<option :value="1">散单工作台</option>
|
||||
<option :value="2">团购工作台</option>
|
||||
</select>
|
||||
<button class="btn" :disabled="loading" @click="search">搜索</button>
|
||||
<button class="btn" @click="openCreate">+ 新增工作台</button>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table class="table table-list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>名称</th>
|
||||
<th>类型</th>
|
||||
<th>录制范围</th>
|
||||
<th>摄像头</th>
|
||||
<th>扫码通道</th>
|
||||
<th>创建时间</th>
|
||||
<th style="width: 260px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in list" :key="item.id">
|
||||
<td>{{ item.name || '—' }}</td>
|
||||
<td>
|
||||
<span :class="['badge', Number(item.wsType) === 2 ? 'badge-group' : 'badge-single']">
|
||||
{{ Number(item.wsType) === 2 ? '团购' : '散单' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="range-cell">
|
||||
{{ Number(item.wsType) === 2 ? '扫码' : '任务结束' }}前 {{ item.recordBeforeSec ?? 60 }}s /
|
||||
后 {{ item.recordAfterSec ?? 60 }}s
|
||||
<span v-if="Number(item.wsType) !== 2" class="hint">(≤ {{ item.recordMaxSec ?? 240 }}s)</span>
|
||||
</td>
|
||||
<td>{{ item.cameraCount ?? 0 }}</td>
|
||||
<td>{{ item.scanChannelCount ?? 0 }}</td>
|
||||
<td>{{ formatTime(item.created_at || item.createdAt) }}</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-primary" @click="openMergedPreview(item)">预览</button>
|
||||
<button class="btn btn-sm" @click="openDetail(item)">绑定管理</button>
|
||||
<button class="btn btn-sm btn-ghost" @click="openEdit(item)">编辑</button>
|
||||
<button class="btn btn-sm btn-danger" @click="doDelete(item)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!list.length && !loading">
|
||||
<td colspan="7" class="empty">还没有工作台,点右上角「新增工作台」创建。</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
||||
unit="个" @update:page="load" @update:page-size="size => (pageSize = size)" />
|
||||
</div>
|
||||
|
||||
<!-- 新增 / 编辑 -->
|
||||
<ModalBox :open="formOpen" :title="editing ? '编辑工作台' : '新增工作台'" @close="formOpen = false">
|
||||
<label class="field"><span>名称</span>
|
||||
<input v-model="form.name" placeholder="例如:1号打包台" />
|
||||
</label>
|
||||
<label class="field"><span>类型</span>
|
||||
<select v-model.number="form.wsType">
|
||||
<option :value="1">散单工作台</option>
|
||||
<option :value="2">团购工作台</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div class="range-box">
|
||||
<p class="range-title">录制范围(秒)</p>
|
||||
<p class="range-tip">
|
||||
<template v-if="form.wsType === 2">
|
||||
团购:以 <strong>扫码时间</strong> 为基准,录「扫码前」+「扫码后」两段,总时长 = 两段之和;
|
||||
</template>
|
||||
<template v-else>
|
||||
散单:以 <strong>任务结束时间</strong> 为基准,录「任务结束前」+「任务结束后」两段;
|
||||
两段合计超过「最大录制时长」时,按最大时长裁切(默认 240 秒)。
|
||||
</template>
|
||||
仅录接入本工作台的摄像头。
|
||||
</p>
|
||||
<div class="range-fields">
|
||||
<label class="field">
|
||||
<span>{{ rangeBaseLabel }}前</span>
|
||||
<input v-model.number="form.recordBeforeSec" type="number" min="0" max="3600" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>{{ rangeBaseLabel }}后</span>
|
||||
<input v-model.number="form.recordAfterSec" type="number" min="0" max="3600" />
|
||||
</label>
|
||||
<label v-if="form.wsType !== 2" class="field">
|
||||
<span>最大录制时长</span>
|
||||
<input v-model.number="form.recordMaxSec" type="number" min="10" max="7200" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<label class="field"><span>备注</span>
|
||||
<input v-model="form.remark" placeholder="可选" />
|
||||
</label>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="formOpen = false">取消</button>
|
||||
<button class="btn" :disabled="saving" @click="save">{{ saving ? '保存中…' : '保存' }}</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 绑定管理 -->
|
||||
<ModalBox :open="detailOpen" :title="`绑定管理 · ${detail?.name || detail?.code || ''}`" width="820px" @close="detailOpen = false">
|
||||
<div v-if="detailError" class="alert alert-error">{{ detailError }}</div>
|
||||
<p v-if="detailLoading" class="hint">加载中…</p>
|
||||
|
||||
<div v-if="detail" class="bind-wrap">
|
||||
<!-- 摄像头:合成画面布局 -->
|
||||
<section class="bind-section camera-section">
|
||||
<header class="bind-head">
|
||||
<strong>摄像头({{ detail.cameras.length }})· 合成画面</strong>
|
||||
<span class="bind-actions">
|
||||
<button class="btn btn-sm btn-primary" @click="openCameraPicker">+ 绑定摄像头</button>
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div v-if="showCameraPicker" class="picker">
|
||||
<p class="hint">一个摄像头只能属于一个工作台;已被其他工作台绑定的不可选,请先在那台工作台解绑。</p>
|
||||
<div class="picker-list">
|
||||
<label v-for="cam in cameraPickable"
|
||||
:key="cam.id"
|
||||
:class="['pick-item', { 'pick-taken': cameraTakenByOther(cam) }]">
|
||||
<input type="checkbox"
|
||||
:disabled="cameraTakenByOther(cam)"
|
||||
:checked="pickedCameras.has(Number(cam.id))"
|
||||
@change="toggleCamera(Number(cam.id))" />
|
||||
<span>{{ cam.name || `通道${cam.channelNo}` }}</span>
|
||||
<span class="pick-sub">{{ cam.nvr?.name || cam.nvr?.host }} · 通道 {{ cam.channelNo }}</span>
|
||||
<span v-if="cameraTakenByOther(cam)" class="pick-badge">
|
||||
已被「{{ cam.boundWorkstation?.name || cam.boundWorkstation?.code }}」绑定
|
||||
</span>
|
||||
</label>
|
||||
<p v-if="!cameraOptions.length" class="hint">还没有摄像头,请先到 NVR 页导入通道。</p>
|
||||
<p v-else-if="!cameraPickable.length" class="hint">没有可添加的摄像头(已全部绑定)。</p>
|
||||
</div>
|
||||
<div class="picker-actions">
|
||||
<button class="btn btn-ghost btn-sm" @click="showCameraPicker = false">取消</button>
|
||||
<button class="btn btn-sm" :disabled="busy || !pickedCameras.size" @click="confirmBindCameras">
|
||||
绑定所选({{ pickedCameras.size }})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CameraLayoutCanvas
|
||||
v-if="detail.cameras.length"
|
||||
:workstation-id="detail.id"
|
||||
:canvas-width="detail.canvasWidth || 1920"
|
||||
:canvas-height="detail.canvasHeight || 1080"
|
||||
:links="detail.cameras"
|
||||
editable
|
||||
@changed="onLayoutChanged"
|
||||
/>
|
||||
|
||||
<ul class="bind-list">
|
||||
<li v-for="link in detail.cameras" :key="link.id">
|
||||
<span class="bind-name">{{ link.camera?.name || `通道${link.camera?.channelNo}` }}</span>
|
||||
<span class="hint">
|
||||
{{ link.camera?.nvr?.name || link.camera?.nvr?.host }} · 通道 {{ link.camera?.channelNo }}
|
||||
<template v-if="link.x !== undefined">· {{ link.width }}×{{ link.height }} @{{ link.x }},{{ link.y }}</template>
|
||||
· {{ Number(link.streamType) === 1 ? '子码流' : '主码流' }}
|
||||
</span>
|
||||
<button class="btn btn-sm btn-danger" :disabled="busy" @click="unbindCamera(link.cameraId)">解绑</button>
|
||||
</li>
|
||||
<li v-if="!detail.cameras.length" class="hint">还没有绑定摄像头</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- 扫码通道 -->
|
||||
<section class="bind-section scan-section">
|
||||
<header class="bind-head">
|
||||
<strong>扫码通道({{ detail.scanChannels.length }})</strong>
|
||||
<button class="btn btn-sm btn-scan" @click="openScanPicker">+ 绑定扫码通道</button>
|
||||
</header>
|
||||
|
||||
<div v-if="showScanPicker" class="picker">
|
||||
<p class="hint">一个扫码通道只能属于一个工作台;已被其他工作台绑定的不可选。</p>
|
||||
<div class="picker-list">
|
||||
<label v-for="item in scanPickable"
|
||||
:key="`${item.scannerId}:${item.channelId}`"
|
||||
:class="['pick-item', { 'pick-taken': channelTakenByOther(item) }]">
|
||||
<input type="checkbox"
|
||||
:disabled="channelTakenByOther(item)"
|
||||
:checked="pickedChannels.has(`${item.scannerId}:${item.channelId}`)"
|
||||
@change="toggleChannel(`${item.scannerId}:${item.channelId}`)" />
|
||||
<span>{{ item.channelName || item.channelId }}</span>
|
||||
<span class="pick-sub">{{ item.scanner?.name || item.scanner?.sn || '中控' }} · {{ item.channelId }}</span>
|
||||
<span v-if="channelTakenByOther(item)" class="pick-badge">
|
||||
已被「{{ item.boundWorkstation?.name || item.boundWorkstation?.code }}」绑定
|
||||
</span>
|
||||
</label>
|
||||
<p v-if="!scanOptions.length" class="hint">还没有中控上报的通道(可先在「测试页」模拟上报)。</p>
|
||||
<p v-else-if="!scanPickable.length" class="hint">没有可添加的扫码通道(已全部绑定)。</p>
|
||||
</div>
|
||||
<div class="picker-actions">
|
||||
<button class="btn btn-ghost btn-sm" @click="showScanPicker = false">取消</button>
|
||||
<button class="btn btn-sm" :disabled="busy || !pickedChannels.size" @click="confirmBindChannels">
|
||||
绑定所选({{ pickedChannels.size }})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="bind-list">
|
||||
<li v-for="link in detail.scanChannels" :key="link.id">
|
||||
<span class="bind-name">{{ link.channelName || link.channelId }}</span>
|
||||
<span class="hint">{{ link.scanner?.name || link.scanner?.sn || '中控' }} · {{ link.channelId }}</span>
|
||||
<button class="btn btn-sm btn-danger" :disabled="busy" @click="unbindScan(link.id)">解绑</button>
|
||||
</li>
|
||||
<li v-if="!detail.scanChannels.length" class="hint">还没有绑定扫码通道</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="detailOpen = false">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
|
||||
<!-- 合并输出预览(按布局合成的输出画面) -->
|
||||
<ModalBox :open="showMergedPreview" :title="`合并输出预览 · ${previewDetail?.name || previewDetail?.code || ''}`" width="1000px" @close="showMergedPreview = false">
|
||||
<div v-if="previewError" class="alert alert-error">{{ previewError }}</div>
|
||||
<p v-if="previewLoading" class="hint">加载布局…</p>
|
||||
<template v-else-if="previewDetail">
|
||||
<CameraLayoutCanvas
|
||||
v-if="previewDetail.cameras.length"
|
||||
:workstation-id="previewDetail.id"
|
||||
:canvas-width="previewDetail.canvasWidth || 1920"
|
||||
:canvas-height="previewDetail.canvasHeight || 1080"
|
||||
:links="previewDetail.cameras"
|
||||
/>
|
||||
<p v-else class="hint">这个工作台还没有绑定摄像头,请先到「绑定管理」里绑定。</p>
|
||||
<p class="hint">
|
||||
输出画面 {{ previewDetail.canvasWidth || 1920 }}×{{ previewDetail.canvasHeight || 1080 }}:
|
||||
上面就是按绑定布局合成后的效果(录制时按这个布局分别拉流)。
|
||||
</p>
|
||||
</template>
|
||||
<template #footer>
|
||||
<button class="btn btn-ghost" @click="showMergedPreview = false">关闭</button>
|
||||
</template>
|
||||
</ModalBox>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.empty {
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
padding: 28px 0;
|
||||
}
|
||||
|
||||
.bind-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.bind-section {
|
||||
border: 1px solid #eef0f4;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.bind-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
/* 摄像头 / 扫码通道两类操作按钮区分:左边蓝色主操作,右边绿色扫码操作 */.bind-actions {
|
||||
display: inline-flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.btn-scan {
|
||||
background: #ecfdf5;
|
||||
border: 1px solid #6ee7b7;
|
||||
color: #047857;
|
||||
}
|
||||
|
||||
.btn-scan:hover {
|
||||
background: #d1fae5;
|
||||
}
|
||||
|
||||
.camera-section {
|
||||
border-left: 3px solid #3b82f6;
|
||||
}
|
||||
|
||||
.scan-section {
|
||||
border-left: 3px solid #10b981;
|
||||
}
|
||||
|
||||
/* 录制范围说明块 */
|
||||
.range-box {
|
||||
border: 1px dashed #cbd5e1;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin: 4px 0 10px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.range-title {
|
||||
margin: 0 0 4px;
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.range-tip {
|
||||
margin: 0 0 8px;
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.range-fields {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.range-fields .field {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.range-fields input {
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
.range-cell {
|
||||
font-size: 12px;
|
||||
color: #475569;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bind-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.bind-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
background: #f8fafc;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.bind-list li.hint {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.bind-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.bind-list .hint {
|
||||
margin-left: auto;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.picker {
|
||||
border: 1px dashed #cbd5e1;
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.picker-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
|
||||
gap: 6px;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.pick-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pick-sub {
|
||||
margin-left: auto;
|
||||
color: #94a3b8;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 已被其他工作台占用:置灰 + 不可勾选 */
|
||||
.pick-taken {
|
||||
opacity: 0.65;
|
||||
cursor: not-allowed;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.pick-badge {
|
||||
color: #b45309;
|
||||
background: #fff7ed;
|
||||
border: 1px solid #fed7aa;
|
||||
border-radius: 4px;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.picker-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
</style>
|
||||
@ -6,11 +6,12 @@ import vue from '@vitejs/plugin-vue';
|
||||
* ⚠️ 端口约定(本机同时跑很多项目,**不要用 Vite 默认的 5173**,很容易撞)
|
||||
* - 前端 dev :7301(`VITE_PORT` 可覆盖)
|
||||
* - 前端 preview:7302(预览 dist 构建产物)
|
||||
* - 后端 dev :7001,后端 dev:test:7300
|
||||
* - 后端 dev :7300(后端默认端口,`VITE_BACKEND` 可覆盖)
|
||||
* - 前端 preview:7302(预览 dist 构建产物)
|
||||
* `strictPort: true` → 端口被占用时**直接报错**,不会悄悄换到 5174(否则和后端反代对不上)
|
||||
* 开发时前端调接口走同源代理:/api、/health → 后端(`VITE_BACKEND` 可覆盖,默认 127.0.0.1:7001)
|
||||
* 开发时前端调接口走同源代理:/api、/health → 后端(`VITE_BACKEND` 可覆盖,默认 127.0.0.1:7300)
|
||||
*/
|
||||
const backend = process.env.VITE_BACKEND || 'http://127.0.0.1:7001';
|
||||
const backend = process.env.VITE_BACKEND || 'http://127.0.0.1:7300';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
@ -24,9 +25,11 @@ export default defineConfig({
|
||||
port: Number(process.env.VITE_PORT || 7301),
|
||||
strictPort: true,
|
||||
// 前端只调接口:/api 与 /health 反代到 Egg(同源,没有跨域,也不用带 cookie)
|
||||
// /download 是安装包与 version.json(浏览器取不着本机软件时给下载入口用)
|
||||
proxy: {
|
||||
'/api': { target: backend, changeOrigin: true },
|
||||
'/health': { target: backend, changeOrigin: true },
|
||||
'/download': { target: backend, changeOrigin: true },
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user