feat(aiot-device): 重写 ROI 配置页面,迁移 WVP 画布式交互

从 WVP 的 roiConfig 整套组件迁移至 Vue3 + Ant Design:

ROI 配置主页面 (roi/index.vue):
- 无参数时显示摄像头选择器,有参数时直接进入配置
- 左侧画布面板 + 右侧 ROI 列表/属性/算法侧边栏
- 画矩形(拖拽)、画多边形(点击+双击完成)
- ROI 属性编辑:名称、颜色、优先级、描述
- 推送配置到边缘端

RoiCanvas 组件 (roi/components/RoiCanvas.vue):
- Canvas 叠加在摄像头截图上,归一化坐标 (0-1)
- 矩形拖拽绘制、多边形逐点绘制
- ROI 选中高亮、点击选择、右键删除
- 窗口 resize 自适应

RoiAlgorithmBind 组件 (roi/components/RoiAlgorithmBind.vue):
- 算法列表加载、绑定/解绑操作
- 启用/禁用开关、参数配置入口

AlgorithmParamEditor 组件 (roi/components/AlgorithmParamEditor.vue):
- 根据 JSON Schema 动态生成表单
- 支持 int(数字输入)、list(标签列表)、string(文本输入)
- 参数保存到后端

删除旧的 data.ts(VxeGrid 列定义,已不再使用)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-08 23:24:48 +08:00
parent b72839622e
commit e2bde76f20
5 changed files with 1243 additions and 112 deletions

View File

@@ -0,0 +1,165 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import {
Button,
Form,
Input,
InputNumber,
message,
Modal,
Tag,
} from 'ant-design-vue';
import { updateAlgoParams } from '#/api/aiot/device';
interface Props {
open: boolean;
paramSchema: string;
currentParams: string;
bindId: string;
}
const props = withDefaults(defineProps<Props>(), {
open: false,
paramSchema: '{}',
currentParams: '{}',
bindId: '',
});
const emit = defineEmits<{
'update:open': [val: boolean];
saved: [data: Record<string, any>];
}>();
const formData = ref<Record<string, any>>({});
const newListItem = ref('');
const parsedSchema = computed(() => {
try {
return JSON.parse(props.paramSchema);
} catch {
return {};
}
});
watch(
() => props.open,
(val) => {
if (val) initForm();
},
);
function initForm() {
const schema = parsedSchema.value;
let current: Record<string, any> = {};
try {
current = JSON.parse(props.currentParams) || {};
} catch {
/* empty */
}
const form: Record<string, any> = {};
Object.keys(schema).forEach((key) => {
if (current[key] !== undefined) {
form[key] = current[key];
} else {
form[key] =
schema[key].type === 'list'
? schema[key].default || []
: schema[key].default;
}
});
formData.value = form;
}
function addListItem(key: string) {
if (!newListItem.value) return;
if (!Array.isArray(formData.value[key])) {
formData.value[key] = [];
}
formData.value[key].push(newListItem.value);
newListItem.value = '';
}
function removeListItem(key: string, idx: number) {
formData.value[key].splice(idx, 1);
}
async function handleSave() {
try {
await updateAlgoParams({
bindId: props.bindId,
params: JSON.stringify(formData.value),
});
message.success('参数保存成功');
emit('saved', formData.value);
emit('update:open', false);
} catch {
message.error('参数保存失败');
}
}
</script>
<template>
<Modal
:open="open"
title="参数配置"
:width="500"
@cancel="emit('update:open', false)"
@ok="handleSave"
>
<Form
layout="horizontal"
:label-col="{ span: 8 }"
:wrapper-col="{ span: 16 }"
>
<Form.Item
v-for="(schema, key) in parsedSchema"
:key="key"
:label="String(key)"
>
<InputNumber
v-if="schema.type === 'int'"
v-model:value="formData[String(key)]"
:min="schema.min"
:placeholder="`默认: ${schema.default}`"
style="width: 100%"
/>
<div v-else-if="schema.type === 'list'">
<div style="margin-bottom: 8px">
<Tag
v-for="(item, idx) in formData[String(key)]"
:key="idx"
closable
style="margin-bottom: 4px"
@close="removeListItem(String(key), idx as number)"
>
{{ item }}
</Tag>
</div>
<Input
v-model:value="newListItem"
placeholder="添加项"
style="width: 180px"
@press-enter="addListItem(String(key))"
>
<template #addonAfter>
<Button
size="small"
type="link"
@click="addListItem(String(key))"
>
添加
</Button>
</template>
</Input>
</div>
<Input
v-else
v-model:value="formData[String(key)]"
:placeholder="`默认: ${schema.default}`"
/>
</Form.Item>
</Form>
</Modal>
</template>

View File

@@ -0,0 +1,229 @@
<script setup lang="ts">
import type { AiotDeviceApi } from '#/api/aiot/device';
import { ref, watch } from 'vue';
import {
Button,
Card,
message,
Modal,
Select,
Switch,
Tag,
} from 'ant-design-vue';
import {
bindAlgo,
getAlgorithmList,
unbindAlgo,
updateAlgoParams,
} from '#/api/aiot/device';
import AlgorithmParamEditor from './AlgorithmParamEditor.vue';
interface Props {
roiId: string;
bindings: AiotDeviceApi.RoiAlgoBinding[];
}
const props = withDefaults(defineProps<Props>(), {
roiId: '',
bindings: () => [],
});
const emit = defineEmits<{
changed: [];
}>();
const showAddDialog = ref(false);
const selectedAlgoCode = ref<string | undefined>(undefined);
const availableAlgorithms = ref<AiotDeviceApi.Algorithm[]>([]);
const paramEditorOpen = ref(false);
const currentParamSchema = ref('{}');
const currentParams = ref('{}');
const currentBindId = ref('');
watch(
() => props.roiId,
() => loadAlgorithms(),
{ immediate: true },
);
async function loadAlgorithms() {
try {
const data = await getAlgorithmList();
availableAlgorithms.value = Array.isArray(data) ? data : [];
} catch {
/* empty */
}
}
function isBound(algoCode: string) {
return props.bindings.some((b) => b.bind.algoCode === algoCode);
}
async function handleBind() {
if (!selectedAlgoCode.value) {
message.warning('请选择算法');
return;
}
try {
await bindAlgo({
roiId: props.roiId,
algoCode: selectedAlgoCode.value,
});
message.success('绑定成功');
showAddDialog.value = false;
selectedAlgoCode.value = undefined;
emit('changed');
} catch (err: any) {
message.error(err?.message || '绑定失败');
}
}
function handleUnbind(bindId: string) {
Modal.confirm({
title: '提示',
content: '确定解绑此算法?',
async onOk() {
try {
await unbindAlgo(bindId);
message.success('解绑成功');
emit('changed');
} catch {
message.error('解绑失败');
}
},
});
}
function openParamEditor(item: AiotDeviceApi.RoiAlgoBinding) {
currentBindId.value = item.bind.bindId || '';
currentParams.value = item.bind.params || '{}';
currentParamSchema.value = item.algorithm?.paramSchema || '{}';
paramEditorOpen.value = true;
}
async function onToggleEnabled(bind: AiotDeviceApi.AlgoBind, val: string | number | boolean) {
bind.enabled = val ? 1 : 0;
try {
await updateAlgoParams({
bindId: bind.bindId!,
enabled: bind.enabled,
});
} catch {
message.error('更新失败');
}
}
function onParamSaved() {
emit('changed');
}
</script>
<template>
<div>
<div
style="
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
"
>
<span style="font-weight: bold; font-size: 14px">绑定算法</span>
<Button size="small" type="primary" @click="showAddDialog = true">
添加算法
</Button>
</div>
<div
v-if="bindings.length === 0"
style="
color: #999;
font-size: 13px;
text-align: center;
padding: 20px 0;
"
>
暂未绑定算法
</div>
<Card
v-for="item in bindings"
:key="item.bind.bindId"
size="small"
style="margin-bottom: 8px"
hoverable
>
<div
style="
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
"
>
<div style="display: flex; align-items: center; gap: 8px">
<Tag color="blue">
{{ item.algorithm?.algoName || item.bind.algoCode }}
</Tag>
<span style="color: #999; font-size: 12px">
{{ item.bind.algoCode }}
</span>
</div>
<div style="display: flex; align-items: center; gap: 8px">
<Switch
:checked="item.bind.enabled === 1"
checked-children="启用"
un-checked-children="禁用"
size="small"
@change="(val: string | number | boolean) => onToggleEnabled(item.bind, val)"
/>
<Button size="small" @click="openParamEditor(item)">
参数配置
</Button>
<Button
size="small"
danger
@click="handleUnbind(item.bind.bindId!)"
>
解绑
</Button>
</div>
</div>
</Card>
<!-- 添加算法对话框 -->
<Modal
v-model:open="showAddDialog"
title="添加算法"
:width="400"
@ok="handleBind"
>
<Select
v-model:value="selectedAlgoCode"
placeholder="选择算法"
style="width: 100%"
:options="
availableAlgorithms.map((algo) => ({
value: algo.algoCode,
label: algo.algoName,
disabled: isBound(algo.algoCode!),
}))
"
/>
</Modal>
<!-- 参数编辑器 -->
<AlgorithmParamEditor
v-model:open="paramEditorOpen"
:param-schema="currentParamSchema"
:current-params="currentParams"
:bind-id="currentBindId"
@saved="onParamSaved"
/>
</div>
</template>

View File

@@ -0,0 +1,354 @@
<script setup lang="ts">
import type { AiotDeviceApi } from '#/api/aiot/device';
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
interface Props {
rois: AiotDeviceApi.Roi[];
drawMode: string | null;
selectedRoiId: string | null;
snapUrl: string;
}
const props = withDefaults(defineProps<Props>(), {
rois: () => [],
drawMode: null,
selectedRoiId: null,
snapUrl: '',
});
const emit = defineEmits<{
'roi-drawn': [data: { roi_type: string; coordinates: string }];
'roi-selected': [roiId: string | null];
'roi-deleted': [roiId: string];
}>();
const wrapper = ref<HTMLDivElement>();
const canvas = ref<HTMLCanvasElement>();
let ctx: CanvasRenderingContext2D | null = null;
let canvasWidth = 0;
let canvasHeight = 0;
const isDrawing = ref(false);
let startPoint: { x: number; y: number } | null = null;
let currentPoint: { x: number; y: number } | null = null;
const polygonPoints = ref<{ x: number; y: number }[]>([]);
const loading = ref(true);
const errorMsg = ref('');
watch(() => props.rois, () => redraw(), { deep: true });
watch(() => props.selectedRoiId, () => redraw());
watch(() => props.drawMode, () => {
polygonPoints.value = [];
isDrawing.value = false;
redraw();
});
watch(() => props.snapUrl, () => {
loading.value = true;
errorMsg.value = '';
});
onMounted(() => {
nextTick(() => {
initCanvas();
window.addEventListener('resize', handleResize);
});
});
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
});
function onImageLoad() {
loading.value = false;
nextTick(() => initCanvas());
}
function onImageError() {
loading.value = false;
errorMsg.value = '截图加载失败,请确认摄像头正在拉流';
}
function initCanvas() {
if (!canvas.value || !wrapper.value) return;
canvasWidth = wrapper.value.clientWidth;
canvasHeight = wrapper.value.clientHeight;
canvas.value.width = canvasWidth;
canvas.value.height = canvasHeight;
ctx = canvas.value.getContext('2d');
redraw();
}
function handleResize() {
initCanvas();
}
function getCanvasPoint(e: MouseEvent) {
const rect = canvas.value!.getBoundingClientRect();
return {
x: (e.clientX - rect.left) / canvasWidth,
y: (e.clientY - rect.top) / canvasHeight,
};
}
function onMouseDown(e: MouseEvent) {
if (e.button !== 0) return;
const pt = getCanvasPoint(e);
if (props.drawMode === 'rectangle') {
isDrawing.value = true;
startPoint = pt;
currentPoint = pt;
} else if (props.drawMode === 'polygon') {
polygonPoints.value.push(pt);
redraw();
drawPolygonInProgress();
} else {
const clickedRoi = findRoiAtPoint(pt);
emit('roi-selected', clickedRoi?.roiId ?? null);
}
}
function onMouseMove(e: MouseEvent) {
if (!isDrawing.value || props.drawMode !== 'rectangle') return;
currentPoint = getCanvasPoint(e);
redraw();
drawRectInProgress();
}
function onMouseUp(e: MouseEvent) {
if (!isDrawing.value || props.drawMode !== 'rectangle') return;
isDrawing.value = false;
const endPoint = getCanvasPoint(e);
const x = Math.min(startPoint!.x, endPoint.x);
const y = Math.min(startPoint!.y, endPoint.y);
const w = Math.abs(endPoint.x - startPoint!.x);
const h = Math.abs(endPoint.y - startPoint!.y);
if (w > 0.01 && h > 0.01) {
emit('roi-drawn', {
roi_type: 'rectangle',
coordinates: JSON.stringify({ x, y, w, h }),
});
}
startPoint = null;
currentPoint = null;
redraw();
}
function onDoubleClick() {
if (props.drawMode === 'polygon' && polygonPoints.value.length >= 3) {
emit('roi-drawn', {
roi_type: 'polygon',
coordinates: JSON.stringify(
polygonPoints.value.map((p) => ({ x: p.x, y: p.y })),
),
});
polygonPoints.value = [];
redraw();
}
}
function onContextMenu(e: MouseEvent) {
e.preventDefault();
const pt = getCanvasPoint(e);
const roi = findRoiAtPoint(pt);
if (roi?.roiId) {
emit('roi-deleted', roi.roiId);
}
}
function findRoiAtPoint(pt: { x: number; y: number }) {
for (let i = props.rois.length - 1; i >= 0; i--) {
const roi = props.rois[i]!;
try {
const coords =
typeof roi.coordinates === 'string'
? JSON.parse(roi.coordinates)
: roi.coordinates;
if (roi.roiType === 'rectangle') {
if (
pt.x >= coords.x &&
pt.x <= coords.x + coords.w &&
pt.y >= coords.y &&
pt.y <= coords.y + coords.h
) {
return roi;
}
} else if (roi.roiType === 'polygon') {
if (isPointInPolygon(pt, coords)) return roi;
}
} catch {
/* skip */
}
}
return null;
}
function isPointInPolygon(
pt: { x: number; y: number },
polygon: { x: number; y: number }[],
) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i]!.x;
const yi = polygon[i]!.y;
const xj = polygon[j]!.x;
const yj = polygon[j]!.y;
const intersect =
yi > pt.y !== yj > pt.y &&
pt.x < ((xj - xi) * (pt.y - yi)) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
function redraw() {
if (!ctx) return;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
props.rois.forEach((roi) => {
try {
const coords =
typeof roi.coordinates === 'string'
? JSON.parse(roi.coordinates)
: roi.coordinates;
const color = roi.color || '#FF0000';
const isSelected = roi.roiId === props.selectedRoiId;
ctx!.strokeStyle = color;
ctx!.lineWidth = isSelected ? 3 : 2;
ctx!.fillStyle = `${color}33`;
if (roi.roiType === 'rectangle') {
const rx = coords.x * canvasWidth;
const ry = coords.y * canvasHeight;
const rw = coords.w * canvasWidth;
const rh = coords.h * canvasHeight;
ctx!.fillRect(rx, ry, rw, rh);
ctx!.strokeRect(rx, ry, rw, rh);
if (roi.name) {
ctx!.fillStyle = color;
ctx!.font = '12px Arial';
ctx!.fillText(roi.name, rx + 4, ry + 14);
}
} else if (roi.roiType === 'polygon') {
ctx!.beginPath();
coords.forEach((p: { x: number; y: number }, idx: number) => {
const px = p.x * canvasWidth;
const py = p.y * canvasHeight;
if (idx === 0) ctx!.moveTo(px, py);
else ctx!.lineTo(px, py);
});
ctx!.closePath();
ctx!.fill();
ctx!.stroke();
if (roi.name && coords.length > 0) {
ctx!.fillStyle = color;
ctx!.font = '12px Arial';
ctx!.fillText(
roi.name,
coords[0].x * canvasWidth + 4,
coords[0].y * canvasHeight + 14,
);
}
}
} catch {
/* skip */
}
});
}
function drawRectInProgress() {
if (!startPoint || !currentPoint || !ctx) return;
const x = Math.min(startPoint.x, currentPoint.x) * canvasWidth;
const y = Math.min(startPoint.y, currentPoint.y) * canvasHeight;
const w = Math.abs(currentPoint.x - startPoint.x) * canvasWidth;
const h = Math.abs(currentPoint.y - startPoint.y) * canvasHeight;
ctx.strokeStyle = '#00FF00';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
ctx.strokeRect(x, y, w, h);
ctx.setLineDash([]);
}
function drawPolygonInProgress() {
if (polygonPoints.value.length < 1 || !ctx) return;
ctx.strokeStyle = '#00FF00';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
ctx.beginPath();
polygonPoints.value.forEach((p, idx) => {
const px = p.x * canvasWidth;
const py = p.y * canvasHeight;
if (idx === 0) ctx!.moveTo(px, py);
else ctx!.lineTo(px, py);
ctx!.fillStyle = '#00FF00';
ctx!.fillRect(px - 3, py - 3, 6, 6);
});
ctx.stroke();
ctx.setLineDash([]);
}
</script>
<template>
<div ref="wrapper" class="roi-canvas-wrapper">
<img
v-if="snapUrl"
:src="snapUrl"
class="bg-image"
@load="onImageLoad"
@error="onImageError"
/>
<div v-else class="video-placeholder">
<span v-if="loading">正在截取画面...</span>
<span v-else>{{ errorMsg || '暂无画面' }}</span>
</div>
<canvas
ref="canvas"
class="roi-overlay"
@mousedown="onMouseDown"
@mousemove="onMouseMove"
@mouseup="onMouseUp"
@dblclick="onDoubleClick"
@contextmenu="onContextMenu"
/>
</div>
</template>
<style scoped>
.roi-canvas-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 400px;
background: #000;
}
.bg-image {
width: 100%;
height: 100%;
object-fit: contain;
display: block;
}
.video-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: #666;
font-size: 18px;
background: #1a1a2e;
}
.roi-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: crosshair;
}
</style>

View File

@@ -1,40 +0,0 @@
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
/** ROI 列表字段 */
export function useRoiGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'name',
title: 'ROI 名称',
minWidth: 150,
},
{
field: 'channelName',
title: '摄像头',
minWidth: 150,
},
{
field: 'type',
title: '类型',
minWidth: 100,
},
{
field: 'enabled',
title: '启用状态',
minWidth: 90,
slots: { default: 'enabled' },
},
{
field: 'createdAt',
title: '创建时间',
minWidth: 170,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 120,
fixed: 'right',
slots: { default: 'actions' },
},
];
}

View File

@@ -1,99 +1,522 @@
<script setup lang="ts">
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AiotDeviceApi } from '#/api/aiot/device';
import { ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { message, Modal, Tag } from 'ant-design-vue';
import {
Button,
Divider,
Form,
Input,
InputNumber,
message,
Modal,
Select,
Switch,
Tag,
} from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRoi, getRoiPage } from '#/api/aiot/device';
import {
deleteRoi,
getCameraList,
getRoiByCameraId,
getRoiDetail,
getSnapUrl,
pushConfig,
saveRoi,
} from '#/api/aiot/device';
import { useRoiGridColumns } from './data';
import RoiAlgorithmBind from './components/RoiAlgorithmBind.vue';
import RoiCanvas from './components/RoiCanvas.vue';
defineOptions({ name: 'AiotDeviceRoi' });
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
const route = useRoute();
const router = useRouter();
// Route params
const cameraId = ref('');
const app = ref('');
const stream = ref('');
// Camera selector (when no cameraId in route)
const showCameraSelector = ref(false);
const cameraOptions = ref<
{ value: string; label: string; camera: AiotDeviceApi.Camera }[]
>([]);
const selectedCamera = ref<string | undefined>(undefined);
const cameraLoading = ref(false);
// ROI state
const drawMode = ref<string | null>(null);
const roiList = ref<AiotDeviceApi.Roi[]>([]);
const selectedRoiId = ref<string | null>(null);
const selectedRoiBindings = ref<AiotDeviceApi.RoiAlgoBinding[]>([]);
const snapUrl = ref('');
const selectedRoi = computed(() => {
if (!selectedRoiId.value) return null;
return roiList.value.find((r) => r.roiId === selectedRoiId.value) || null;
});
onMounted(() => {
const q = route.query;
if (q.cameraId) {
cameraId.value = String(q.cameraId);
app.value = String(q.app || '');
stream.value = String(q.stream || '');
buildSnapUrl();
loadRois();
} else {
showCameraSelector.value = true;
loadCameraOptions();
}
});
async function loadCameraOptions() {
cameraLoading.value = true;
try {
const res = await getCameraList({ page: 1, count: 200 });
const list = res.list || [];
cameraOptions.value = list.map((cam: AiotDeviceApi.Camera) => ({
value: `${cam.app}/${cam.stream}`,
label: `${cam.app}/${cam.stream}${cam.srcUrl ? ` (${cam.srcUrl})` : ''}`,
camera: cam,
}));
} catch {
message.error('加载摄像头列表失败');
} finally {
cameraLoading.value = false;
}
}
/** 删除 ROI */
async function handleDelete(row: AiotDeviceApi.Roi) {
function onCameraSelected(val: string) {
const opt = cameraOptions.value.find((o) => o.value === val);
if (opt) {
cameraId.value = val;
app.value = opt.camera.app || '';
stream.value = opt.camera.stream || '';
showCameraSelector.value = false;
buildSnapUrl();
loadRois();
}
}
function goBack() {
router.push('/aiot/device/camera');
}
function buildSnapUrl() {
if (app.value && stream.value) {
snapUrl.value = getSnapUrl(app.value, stream.value);
}
}
function refreshSnap() {
buildSnapUrl();
}
async function loadRois() {
try {
const data = await getRoiByCameraId(cameraId.value);
roiList.value = Array.isArray(data) ? data : [];
if (selectedRoiId.value) {
loadRoiDetail();
}
} catch {
message.error('加载ROI失败');
}
}
async function loadRoiDetail() {
if (!selectedRoi.value?.id) return;
try {
const data = await getRoiDetail(selectedRoi.value.id);
if (data) {
selectedRoiBindings.value = data.algorithms || [];
}
} catch {
/* empty */
}
}
function startDraw(mode: string) {
drawMode.value = mode;
}
async function onRoiDrawn(data: { roi_type: string; coordinates: string }) {
drawMode.value = null;
const newRoi: Partial<AiotDeviceApi.Roi> = {
cameraId: cameraId.value,
name: `ROI-${roiList.value.length + 1}`,
roiType: data.roi_type,
coordinates: data.coordinates,
color: '#FF0000',
priority: 0,
enabled: 1,
description: '',
};
try {
await saveRoi(newRoi);
message.success('ROI已保存');
loadRois();
} catch {
message.error('保存失败');
}
}
function onRoiSelected(roiId: string | null) {
selectedRoiId.value = roiId;
if (roiId) {
loadRoiDetail();
} else {
selectedRoiBindings.value = [];
}
}
function selectRoi(roi: AiotDeviceApi.Roi) {
selectedRoiId.value = roi.roiId || null;
loadRoiDetail();
}
function onRoiDeleted(roiId: string) {
doDeleteRoi(roiId);
}
function handleDeleteRoi(roi: AiotDeviceApi.Roi) {
Modal.confirm({
title: '删除确认',
content: `确定删除 ROI "${row.name}" 吗?`,
title: '提示',
content: '确定删除ROI?关联的算法绑定也将删除。',
async onOk() {
const hideLoading = message.loading({
content: '正在删除...',
duration: 0,
});
try {
await deleteRoi(row.id as number);
message.success('删除成功');
handleRefresh();
} catch (error) {
console.error('删除失败:', error);
throw error;
} finally {
hideLoading();
}
doDeleteRoi(roi.roiId!);
},
});
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
columns: useRoiGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }) => {
return await getRoiPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
});
},
},
async function doDeleteRoi(roiId: string) {
try {
await deleteRoi(roiId);
message.success('已删除');
if (selectedRoiId.value === roiId) {
selectedRoiId.value = null;
selectedRoiBindings.value = [];
}
loadRois();
} catch {
message.error('删除失败');
}
}
async function updateRoiData(roi: AiotDeviceApi.Roi) {
try {
await saveRoi(roi);
loadRois();
} catch {
message.error('更新失败');
}
}
function handlePush() {
Modal.confirm({
title: '推送配置',
content: '确定将此摄像头的所有ROI配置推送到边缘端',
async onOk() {
try {
await pushConfig(cameraId.value);
message.success('推送成功');
} catch (err: any) {
message.error(err?.message || '推送失败请检查AI服务是否启用');
}
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
},
} as VxeTableGridOptions<AiotDeviceApi.Roi>,
});
});
}
</script>
<template>
<Page auto-content-height>
<Grid table-title="ROI 区域配置">
<!-- 启用状态列 -->
<template #enabled="{ row }">
<Tag :color="row.enabled ? 'success' : 'default'">
{{ row.enabled ? '启用' : '禁用' }}
</Tag>
</template>
<!-- Camera selector when no cameraId -->
<div v-if="showCameraSelector" style="padding: 60px; text-align: center">
<h3 style="margin-bottom: 20px">请选择要配置ROI的摄像头</h3>
<Select
v-model:value="selectedCamera"
placeholder="选择摄像头"
style="width: 500px; max-width: 100%"
show-search
:loading="cameraLoading"
:options="cameraOptions"
@change="(val: any) => onCameraSelected(String(val))"
/>
<div style="margin-top: 16px; color: #999; font-size: 13px">
或从摄像头管理页面点击ROI配置进入
</div>
</div>
<!-- 操作列 -->
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '删除',
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,
onClick: handleDelete.bind(null, row),
},
]"
/>
</template>
</Grid>
<!-- ROI Config Page -->
<div v-else class="roi-config-page">
<!-- Header -->
<div class="page-header">
<div class="header-left">
<Button size="small" @click="goBack">返回</Button>
<h3>{{ cameraId }} - ROI配置</h3>
</div>
<div class="header-right">
<Button
size="small"
type="primary"
:disabled="drawMode === 'rectangle'"
@click="startDraw('rectangle')"
>
画矩形
</Button>
<Button
size="small"
type="primary"
:disabled="drawMode === 'polygon'"
@click="startDraw('polygon')"
>
画多边形
</Button>
<Button size="small" @click="drawMode = null" :disabled="!drawMode">
取消绘制
</Button>
<Button size="small" @click="refreshSnap">刷新截图</Button>
<Button size="small" type="default" @click="handlePush">
推送到边缘端
</Button>
</div>
</div>
<!-- Main Content -->
<div class="main-content">
<!-- Canvas Panel -->
<div class="canvas-panel">
<RoiCanvas
:rois="roiList"
:draw-mode="drawMode"
:selected-roi-id="selectedRoiId"
:snap-url="snapUrl"
@roi-drawn="onRoiDrawn"
@roi-selected="onRoiSelected"
@roi-deleted="onRoiDeleted"
/>
</div>
<!-- Side Panel -->
<div class="side-panel">
<!-- ROI List -->
<div class="section-header">
<span>ROI列表 ({{ roiList.length }})</span>
</div>
<div v-if="roiList.length === 0" class="empty-tip">
暂无ROI请在左侧画面上绘制
</div>
<div
v-for="roi in roiList"
:key="roi.roiId"
:class="['roi-item', { active: selectedRoiId === roi.roiId }]"
@click="selectRoi(roi)"
>
<div class="roi-item-header">
<span
class="roi-color"
:style="{ background: roi.color || '#FF0000' }"
/>
<span class="roi-name">{{ roi.name || '未命名' }}</span>
<Tag
:color="roi.roiType === 'rectangle' ? 'blue' : 'green'"
style="margin-right: 0"
>
{{ roi.roiType === 'rectangle' ? '矩形' : '多边形' }}
</Tag>
<Switch
:checked="roi.enabled === 1"
size="small"
style="margin-left: auto"
@change="
(val: string | number | boolean) => {
roi.enabled = val ? 1 : 0;
updateRoiData(roi);
}
"
@click.stop
/>
<Button
size="small"
type="text"
danger
style="margin-left: 4px"
@click.stop="handleDeleteRoi(roi)"
>
删除
</Button>
</div>
</div>
<Divider />
<!-- ROI Detail -->
<div v-if="selectedRoi" class="roi-detail-section">
<h4>ROI属性</h4>
<Form
layout="horizontal"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
size="small"
>
<Form.Item label="名称">
<Input
v-model:value="selectedRoi.name"
@blur="updateRoiData(selectedRoi!)"
/>
</Form.Item>
<Form.Item label="颜色">
<Input
v-model:value="selectedRoi.color"
type="color"
style="width: 60px; padding: 2px"
@change="updateRoiData(selectedRoi!)"
/>
</Form.Item>
<Form.Item label="优先级">
<InputNumber
v-model:value="selectedRoi.priority"
:min="0"
@change="updateRoiData(selectedRoi!)"
/>
</Form.Item>
<Form.Item label="描述">
<Input.TextArea
v-model:value="selectedRoi.description"
:rows="2"
@blur="updateRoiData(selectedRoi!)"
/>
</Form.Item>
</Form>
<Divider />
<RoiAlgorithmBind
:roi-id="selectedRoi.roiId || ''"
:bindings="selectedRoiBindings"
@changed="loadRoiDetail"
/>
</div>
<div v-else class="empty-tip" style="margin-top: 20px">
点击左侧ROI区域或列表项查看详情
</div>
</div>
</div>
</div>
</Page>
</template>
<style scoped>
.roi-config-page {
padding: 12px;
height: 100%;
display: flex;
flex-direction: column;
}
.page-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.header-left {
display: flex;
align-items: center;
gap: 10px;
}
.header-left h3 {
margin: 0;
}
.header-right {
display: flex;
gap: 8px;
}
.main-content {
display: flex;
flex: 1;
gap: 12px;
overflow: hidden;
}
.canvas-panel {
flex: 6;
background: #000;
border-radius: 4px;
overflow: hidden;
}
.side-panel {
flex: 4;
overflow-y: auto;
background: #fff;
border: 1px solid #f0f0f0;
border-radius: 4px;
padding: 12px;
}
.section-header {
font-weight: bold;
font-size: 14px;
margin-bottom: 10px;
}
.empty-tip {
color: #999;
text-align: center;
padding: 20px 0;
font-size: 13px;
}
.roi-item {
padding: 8px 10px;
border: 1px solid #f0f0f0;
border-radius: 4px;
margin-bottom: 6px;
cursor: pointer;
transition: all 0.2s;
}
.roi-item:hover {
border-color: #1677ff;
}
.roi-item.active {
border-color: #1677ff;
background: #e6f4ff;
}
.roi-item-header {
display: flex;
align-items: center;
gap: 6px;
}
.roi-color {
width: 12px;
height: 12px;
border-radius: 2px;
display: inline-block;
}
.roi-name {
font-size: 13px;
font-weight: 500;
}
.roi-detail-section h4 {
margin: 0 0 10px;
font-size: 14px;
}
</style>