This commit is contained in:
yin 2026-07-20 18:21:57 +08:00
parent 292e69a6d1
commit 77f54c1151
35 changed files with 5323 additions and 284 deletions

Binary file not shown.

View File

@ -0,0 +1,68 @@
import request from '@/utils/request'
const v = '1.0'
/** order.packing.list 查询参数 */
export type PackingListPagination = {
page?: number
pageSize?: number
}
export type PackingListWhere = Record<string, unknown> & {
status?: number
pack_mode?: number
waybill_code?: string
wave_no?: string
order_id?: number
workbench_id?: number
quickWhere?: string
start_time_start?: string
start_time_end?: string
}
export type PackingListSort = {
sortField?: string
sortOrder?: 'asc' | 'desc' | 'ASC' | 'DESC'
}
export type PackingListParams = {
pagination?: PackingListPagination
where?: PackingListWhere
sort?: PackingListSort
}
/** order.packing.list:打包任务列表查询(仓库侧) */
export function packingList(data: PackingListParams = {}): Promise<any> {
return request({
url: '/system',
method: 'post',
params: {
method: 'order.packing.list',
v,
timestamp: new Date().getTime(),
},
data,
isSystemApi: true,
} as any)
}
/** order.packing.get 请求参数 */
export type PackingDetailParams = {
/** 打包任务ID(必填) */
id: number
}
/** order.packing.get:打包任务详情查询(仓库侧) */
export function packingDetail(data: PackingDetailParams): Promise<any> {
return request({
url: '/system',
method: 'post',
params: {
method: 'order.packing.get',
v,
timestamp: new Date().getTime(),
},
data,
isSystemApi: true,
} as any)
}

View File

@ -703,3 +703,48 @@ export function queryEntryLogs(data: QueryEntryLogsParams = {}): Promise<any> {
isSystemApi: true,
} as any)
}
/** storage.entry.export 导出参数(异步任务模式) */
export type EntryExportParams = {
where?: Record<string, unknown>
sort?: {
sortField?: string
sortOrder?: 'asc' | 'desc' | 'ASC' | 'DESC'
}
}
/** storage.entry.export:导出入库单列表及明细(异步任务模式),返回 task_id */
export function entryExport(data: EntryExportParams = {}): Promise<any> {
return request({
url: '/system',
method: 'post',
params: {
method: 'storage.entry.export',
v,
timestamp: new Date().getTime(),
},
data,
isSystemApi: true,
} as any)
}
/** storage.entry.exportTaskProgress 查询参数 */
export type EntryExportTaskProgressParams = {
task_id?: string
taskId?: string
}
/** storage.entry.exportTaskProgress:查询入库单导出任务进度与下载链接 */
export function entryExportTaskProgress(data: EntryExportTaskProgressParams): Promise<any> {
return request({
url: '/system',
method: 'post',
params: {
method: 'storage.entry.exportTaskProgress',
v,
timestamp: new Date().getTime(),
},
data,
isSystemApi: true,
} as any)
}

View File

@ -63,7 +63,7 @@ export const componentMap: Record<string, any> = {
'material/packageMaterial/index':() => import('@/views/material/packageMaterial/index.vue'),
'material/packageSupplier/index':() => import('@/views/material/packageSupplier/index.vue'),
'system/setting/pickcart/index':() => import('@/views/system/setting/pickcart/index.vue'),
'video/cameraServer/index': () => import('@/views/video/cameraServer/index.vue'),
'video/cameraServer/index': () => import('@/views/video/newcamaraserver/index.vue'),
'video/camera/index': () => import('@/views/video/newcamara/index.vue'),
'data/packingflow': () => import('@/views/data/packingflow/index.vue'),
};

View File

@ -72,9 +72,6 @@
<template #column-videos="{ row }">
<VideoButton :videos="row.videos || []" @click="openVideoList(row)" />
</template>
<template #column-actions="{ row }">
<el-button link type="primary" size="small" @click.stop="openDetail(row)">详情</el-button>
</template>
<template #empty>
<el-empty description="暂无打包任务数据" :image-size="60" />
</template>
@ -189,8 +186,7 @@ const columns = [
{ prop: 'start_time', label: '开始时间', width: 170, sortable: true, formatter: (row: any) => row.start_time ? dayjs(row.start_time).format('YYYY-MM-DD HH:mm:ss') : '—' },
{ prop: 'end_time', label: '结束时间', width: 170, sortable: true, formatter: (row: any) => row.end_time ? dayjs(row.end_time).format('YYYY-MM-DD HH:mm:ss') : '—' },
{ prop: 'create_time', label: '创建时间', width: 170, sortable: true, formatter: (row: any) => row.create_time ? dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') : '—' },
{ prop: 'videos', label: '录像', width: 110, fixed: 'right' },
{ prop: 'actions', label: '操作', width: 80, fixed: 'right' }
{ prop: 'videos', label: '录像', width: 110, fixed: 'right' }
]
// ─── 筛选字段配置 ──────────────────────────────────────────────────────────

View File

@ -1180,6 +1180,7 @@ export const waveOrder2TabPages: TabPageRawConfig[] = [
// ============================================================
// 十、向后兼容导出
// ============================================================
// 单页模式 singlePage
export const WAVEORDER2_PAGE_CONFIG = { showTabArea: true, singlePage: false, enableDetailPanel: true }
export const waveOrder2Tabs = waveOrder2TabPages.map((t) => ({

View File

@ -395,12 +395,6 @@ const validateItemCode = async (rule: any, value: any, callback: any) => {
return
}
if (value.length > 20) {
itemCodeError.value = "条码长度不能超过20个字符"
callback(new Error(itemCodeError.value))
return
}
if (!formData.store_id) {
itemCodeError.value = '请先选择货主'
callback(new Error(itemCodeError.value))

View File

@ -18,7 +18,7 @@
clearable
resize="none"
class="barcode-textarea"
:disabled="!hasPermission('stock.saveWarehouseStockBarcode')"
:disabled="!hasPermission('stock.warehouse.saveWarehouseStockBarcode')"
@blur="handleBlur"
/>
</el-form-item>
@ -30,7 +30,7 @@
<el-button
type="primary"
icon="Check"
:disabled="!hasPermission('stock.saveWarehouseStockBarcode')"
:disabled="!hasPermission('stock.warehouse.saveWarehouseStockBarcode')"
@click="handleSave"
title="保存"
>

View File

@ -1,6 +1,6 @@
<template>
<div class="stock-info-container">
<el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" :disabled="!hasPermission('stock.saveWarehouseStock') || loading">
<el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" :disabled="!hasPermission('stock.warehouse.saveWarehouseStock') || loading">
<el-row :gutter="30">
<!-- 第一列:基础信息 -->
<el-col :span="12">
@ -380,7 +380,7 @@
</el-form>
<!-- 底部操作按钮 -->
<div class="bottom" v-if="hasPermission('stock.saveWarehouseStock')">
<div class="bottom" v-if="hasPermission('stock.warehouse.saveWarehouseStock')">
<el-button-group class="toolbar-btn-group">
<el-button type="primary" icon="Check" @click="handleSave" title="保存">保存
</el-button>
@ -595,13 +595,6 @@ const validateItemCode = async (rule: any, value: string, callback: any) => {
return
}
// 检查长度
if (value.length > 20) {
itemCodeError = "条码长度不能超过20个字符"
callback(new Error('条码长度不能超过20个字符'))
return
}
try {
const u = userStore.user || {}
const ctxWh = u.warehouse_id ?? u.store_id

View File

@ -28,7 +28,7 @@
/>
<el-dropdown
v-if="hasPermission('stock.saveWarehouseStock')"
v-if="hasPermission('stock.warehouse.saveWarehouseStock')"
@command="handleBatchChange"
>
<el-button type="primary" :disabled="!hasSelection" size="small">
@ -340,7 +340,8 @@ const {
exportProgressPercent,
exportProgressStatus,
exportStatusLabel,
submitExportTaskWithMode
submitExportTaskWithMode,
submitExportTask
} = useAsyncExportTask({
storageKey: 'stock:warehouse:exportTaskId',
submitExport: (payload) => stockApi.exportStockWarehouse(payload as any),
@ -353,12 +354,28 @@ function buildExportPayload() {
}
}
async function handleExportWaybill() {
await submitExportTaskWithMode(buildExportPayload(), 'waybill')
function buildExportSelectedPayload() {
const ids = selectionIds.value.map((item: any) => item.id)
return {
where: {
id: {
operator: 'in',
value: ids
}
}
}
}
async function handleExportItem() {
await submitExportTaskWithMode(buildExportPayload(), 'item')
async function handleExportAll() {
await submitExportTask(buildExportPayload())
}
async function handleExportSelected() {
if (!hasSelection.value) {
ElMessage.warning('请先勾选需要导出的商品')
return
}
await submitExportTask(buildExportSelectedPayload())
}
const tableSize = ref('small')
@ -447,8 +464,8 @@ const toolbarActionMap: Record<string, () => void> = {
handleAdd: () => handleAdd(),
confirmBatchDelete: () => confirmBatchDelete(),
handleClearData: () => handleClearData(),
handleExportWaybill: () => handleExportWaybill(),
handleExportItem: () => handleExportItem(),
handleExportAll: () => handleExportAll(),
handleExportSelected: () => handleExportSelected(),
openImportDialog: () => openImportDialog(),
openColumnConfigPanel: () => openColumnConfigPanel(),
toggleDetailVisible: () => toggleDetailVisible()

View File

@ -529,7 +529,7 @@ export const stockToolbarButtons: StockToolbarButtonConfig[] = [
label: '添加',
type: 'primary',
size: 'small',
permissionKey: 'stock.saveWarehouseStock',
permissionKey: 'stock.warehouse.saveWarehouseStock',
action: 'handleAdd'
},
{
@ -537,7 +537,7 @@ export const stockToolbarButtons: StockToolbarButtonConfig[] = [
label: '批量删除',
type: 'danger',
size: 'small',
permissionKey: 'stock.saveWarehouseStock',
permissionKey: 'stock.warehouse.saveWarehouseStock',
disabledKey: 'hasNoSelection',
action: 'confirmBatchDelete'
},
@ -546,13 +546,13 @@ export const stockToolbarButtons: StockToolbarButtonConfig[] = [
key: 'export',
label: '导出',
size: 'small',
permissionKey: 'warehouseExport',
permissionKey: 'stock.warehouse.export',
loadingKey: 'exportLoading',
action: 'handleExportWaybill',
action: 'handleExportAll',
buttonType: 'dropdown',
dropdownOptions: [
{ label: '不含明细', action: 'handleExportWaybill' },
{ label: '含明细', action: 'handleExportItem', divided: true }
{ label: '导出选中', action: 'handleExportSelected' },
{ label: '导出全部', action: 'handleExportAll', divided: true }
]
},
{ key: 'import', label: '导入', type: 'primary', plain: true, size: 'small', action: 'openImportDialog' },

View File

@ -20,7 +20,15 @@
<el-button size="small" type="primary" @click="loadData">刷新</el-button>
<!-- <el-button size="small" @click="handleCreateEntry">新建入库单</el-button> -->
<el-button size="small" :disabled="!hasSelection" @click="confirmBatchCancel">批量作废</el-button>
<ExportModeDropdown :loading="exportLoading" @action="handleExportAction" />
<el-dropdown trigger="click" split-button size="small" :loading="exportLoading" @click="handleExportAll" @command="handleExportCommand">
导出
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item command="handleExportSelected">导出选中</el-dropdown-item>
<el-dropdown-item command="handleExportAll" divided>导出全部</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
<el-button size="small" @click="handleImport">导入</el-button>
<el-button size="small" @click="openColumnConfigPanel">字段设置</el-button>
<el-button size="small" @click="toggleDetailVisible">{{ detailVisible ? '隐藏详情' : '显示详情' }}</el-button>
@ -318,6 +326,19 @@
:fetch-print-data="fetchEntryPrintData"
:business-type-options="[{ label: '入库单 (ENTRY_ORDER)', value: 'ENTRY_ORDER' }]"
/>
<AsyncExportProgressDialog
v-model:visible="exportDialogVisible"
title="入库单导出进度"
:loading="exportLoading"
:progress-percent="exportProgressPercent"
:progress-status="exportProgressStatus"
:status-label="exportStatusLabel"
:task-id="exportTaskProgress.taskId"
:message="exportTaskProgress.message"
:error="exportTaskProgress.error"
:update-time="exportTaskProgress.updateTime"
/>
</div>
</template>
@ -330,7 +351,6 @@ import UpperTable from '@/components/UpperTable/index.vue'
import * as indexApi from '@/api/index/index'
import * as entryApi from '@/api/storage.entry/entry'
import type { StorageEntryListParams } from '@/api/storage.entry/entry'
import * as XLSX from 'xlsx'
import {
availableFields,
@ -356,8 +376,9 @@ import entryoperate from './component/entryoperate.vue'
import BindReceivingToEntryDialog from './component/BindReceivingToEntryDialog.vue'
import DirectInboundLogs from './component/DirectInboundLogs.vue'
import EntryBindingRelations from './component/EntryBindingRelations.vue'
import ExportModeDropdown from '@/components/ExportModeDropdown.vue'
import BatchReceivingPrintDialog from '@/components/BatchReceivingPrintDialog.vue'
import AsyncExportProgressDialog from '@/components/AsyncExportProgressDialog.vue'
import { useAsyncExportTask } from '@/composables/useAsyncExportTask'
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
import { useSettingsStore } from '@/stores/modules/settings'
@ -421,9 +442,22 @@ const activeTab = ref('details')
const list = ref<any[]>([])
const loading = ref(false)
const exportLoading = ref(false)
const queryTime = ref(0)
const {
exportLoading,
exportDialogVisible,
exportTaskProgress,
exportProgressPercent,
exportProgressStatus,
exportStatusLabel,
submitExportTask
} = useAsyncExportTask({
storageKey: 'storage:entry:exportTaskId',
submitExport: (payload) => entryApi.entryExport(payload as any),
queryProgress: (params) => entryApi.entryExportTaskProgress(params)
})
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const tableSize = ref('small')
const columns = ref(entryColums)
@ -436,6 +470,43 @@ const selectedEntryId = ref<number | string | null>(null)
const quickSearch = ref('')
const currentSort = reactive({ prop: '', order: '' })
// 导出相关 —— 使用异步任务模式
function buildExportPayload() {
if (currentCondition.value && currentCondition.value !== 'reset') {
return { where: normalizeToWhere(currentCondition.value) }
}
return { where: normalizeToWhere({}) }
}
function buildExportSelectedPayload() {
const ids = selectionRows.value.map((item: any) => item.id)
return {
where: {
id: { operator: 'in', value: ids }
}
}
}
async function handleExportAll() {
await submitExportTask(buildExportPayload())
}
async function handleExportSelected() {
if (!selectionRows.value.length) {
ElMessage.warning('请先勾选需要导出的入库单')
return
}
await submitExportTask(buildExportSelectedPayload())
}
function handleExportCommand(command: string) {
if (command === 'handleExportSelected') {
handleExportSelected()
} else {
handleExportAll()
}
}
const componentMap: Record<string, any> = {
details: entrydetail,
bindingRelations: EntryBindingRelations,
@ -1093,84 +1164,6 @@ async function confirmBatchCancel() {
}
}
async function handleExport(mode: 'waybill' | 'item' = 'waybill') {
const sourceRows = selectionRows.value.length ? selectionRows.value : list.value
if (!sourceRows.length) {
ElMessage.warning('当前无数据可导出')
return
}
exportLoading.value = true
try {
const exportColumns = columns.value.filter(col => col.prop && col.label)
if (mode === 'waybill') {
const headers = exportColumns.map(col => col.label)
const data = sourceRows.map(row =>
exportColumns.map(col => {
const val = row[col.prop]
if (['order_status', 'order_type', 'sync_status'].includes(col.prop)) {
return translateField(col.prop, val)
}
return val === null || val === undefined ? '' : val
})
)
const ws = XLSX.utils.aoa_to_sheet([headers, ...data])
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, '入库单列表')
XLSX.writeFile(wb, `入库单列表_${new Date().getTime()}.xlsx`)
ElMessage.success('导出成功')
return
}
const detailRows: any[] = []
for (const row of sourceRows) {
try {
const res: any = await entryApi.getEntryDetail({ id: row.id })
const payload = res?.data || res
const bindings = Array.isArray(payload?.bindings)
? payload.bindings
: Array.isArray(payload?.details)
? payload.details
: []
bindings.forEach((item: any) => {
detailRows.push({
'入库单号': row.entry_number || row.order_code || row.id,
'商品编码': item.item_code || item.product_code || '',
'商品名称': item.item_name || item.product_name || '',
'计划数量': item.plan_qty ?? item.quantity ?? '',
'实收数量': item.actual_qty ?? item.received_qty ?? '',
'批次号': item.batch_number || '',
'库位': item.space_id || item.space_name || '',
'备注': item.remark || ''
})
})
} catch (e) {
console.warn(`获取入库单 ${row.id} 明细失败`, e)
}
}
if (!detailRows.length) {
ElMessage.warning('未获取到可导出的入库明细')
return
}
const ws = XLSX.utils.json_to_sheet(detailRows)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, '入库明细')
XLSX.writeFile(wb, `入库明细_${new Date().getTime()}.xlsx`)
ElMessage.success('导出成功')
} catch (e) {
console.error('导出 Excel 失败:', e)
ElMessage.error('导出失败')
} finally {
exportLoading.value = false
}
}
function handleExportAction(action: string) {
void handleExport(action === 'handleExportItem' ? 'item' : 'waybill')
}
function handleImport() {
if (!selectedEntryId.value) {
ElMessage.warning('请先在列表中选择一个入库单')

View File

@ -0,0 +1,65 @@
<!--
ColumnCellRenderer — 通用表格列渲染器
根据传入的 ColumnSlotConfig 决定如何渲染单元格:
- type='tag' → el-tag(支持 tagResolver / tagType 颜色映射)
- type='text' → 纯文本(支持 datetime 格式化)
- type='default' → 默认插槽渲染
- type='operation' → 操作列(由 OperationCellRenderer 处理)
-->
<template>
<template v-if="!config || config.type === 'default'">
<slot />
</template>
<template v-else-if="config.type === 'tag'">
<el-tag size="small" :type="resolvedTagType">
{{ displayValue }}
</el-tag>
</template>
<template v-else>
<span>{{ displayValue }}</span>
</template>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { ColumnSlotConfig } from '../config/template-config'
import { TAG_RESOLVERS, translate, formatTime } from '../config/template-config'
defineOptions({ name: 'ColumnCellRenderer' })
const props = defineProps<{
/** 列插槽渲染配置 */
config: ColumnSlotConfig | undefined
/** 单元格值 */
value: any
}>()
/** 显示文本:translateField 翻译 > format 格式化 > 原始值 */
const displayValue = computed(() => {
const v = props.value
if (props.config?.translateField) {
return translate(props.config.translateField, v)
}
if (props.config?.format === 'datetime') {
return formatTime(v)
}
return v ?? '—'
})
const resolvedTagType = computed(() => {
if (!props.config || props.config.type !== 'tag') return ''
const { tagType, tagResolver } = props.config
// 优先使用 tagResolver(函数名映射)
if (tagResolver && TAG_RESOLVERS[tagResolver]) {
return TAG_RESOLVERS[tagResolver](props.value)
}
// 其次使用 tagType 映射表(用原始值查找)
if (tagType && typeof tagType === 'object') {
return tagType[String(props.value)] ?? 'info'
}
// 最后使用固定值
return (typeof tagType === 'string' ? tagType : 'info')
})
</script>

View File

@ -0,0 +1,175 @@
<!--
OperationCellRenderer — 表格操作列渲染组件
根据 operationButtons 配置渲染按钮列表。
支持的行为类型:
- actionType='action' → 触发 @operation-action 事件(可选配置 confirmMessage 弹确认框)
- actionType='form' → 打开 COMPONENT_REGISTRY 中注册的表单组件
使用方式:在 index.vue 中通过插槽 column-operation 引入:
<OperationCellRenderer
:buttons="currentTabConfig?.operationButtons"
:row="row"
@operation-action="handleOperationAction"
/>
-->
<template>
<div class="operation-cell">
<template v-for="btn in buttons" :key="btn.key">
<!-- action 按钮:支持确认弹窗 -->
<el-button
v-if="btn.actionType === 'action'"
link
:type="btn.type || 'primary'"
size="small"
:loading="actionLoadingMap[btn.key]"
:disabled="isDisabled(btn)"
@click.stop="handleActionClick(btn)"
>
{{ btn.label }}
</el-button>
<!-- form 按钮:打开表单弹窗 -->
<template v-else-if="btn.actionType === 'form'">
<el-button
link
:type="btn.type || 'primary'"
size="small"
:disabled="isDisabled(btn)"
@click.stop="openForm(btn)"
>
{{ btn.label }}
</el-button>
<!-- 表单弹窗 -->
<component
:is="resolvedFormComponents[btn.key]"
v-if="resolvedFormComponents[btn.key] && activeFormKey === btn.key"
v-model:visible="formVisibleMap[btn.key]"
v-bind="buildFormProps(btn)"
@success="handleFormSuccess(btn.key)"
/>
</template>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, type Component } from 'vue'
import { ElMessageBox } from 'element-plus'
import { COMPONENT_REGISTRY } from '../config/template-config'
import type { OperationButtonConfig } from '../config/template-config'
defineOptions({ name: 'OperationCellRenderer' })
const props = defineProps<{
/** 操作按钮配置列表(来自 TabPageConfig.operationButtons) */
buttons?: OperationButtonConfig[]
/** 当前行数据 */
row: Record<string, any>
}>()
const emit = defineEmits<{
/** action 按钮点击事件(key: 按钮标识, row: 行数据) */
(e: 'operation-action', key: string, row: Record<string, any>): void
}>()
// ===== form 弹窗管理 =====
const activeFormKey = ref('')
const formVisibleMap = reactive<Record<string, boolean>>({})
const resolvedFormComponents = ref<Record<string, Component>>({})
const actionLoadingMap = reactive<Record<string, boolean>>({})
// ============================================================
// action 按钮:支持确认弹窗
// ============================================================
async function handleActionClick(btn: OperationButtonConfig) {
if (btn.confirmMessage) {
try {
await ElMessageBox.confirm(
btn.confirmMessage,
btn.confirmTitle || '确认操作',
{
confirmButtonText: btn.confirmButtonText || '确定',
cancelButtonText: '取消',
type: (btn.confirmType || 'warning') as any
}
)
} catch {
return // 取消
}
}
actionLoadingMap[btn.key] = true
try {
emit('operation-action', btn.key, props.row)
} finally {
actionLoadingMap[btn.key] = false
}
}
// ============================================================
// form 按钮:打开表单弹窗
// ============================================================
function openForm(btn: OperationButtonConfig) {
if (!btn.formKey) return
const comp = COMPONENT_REGISTRY[btn.formKey]
if (!comp) {
console.warn(`[OperationCellRenderer] 未注册的表单组件: ${btn.formKey}`)
return
}
activeFormKey.value = btn.key
resolvedFormComponents.value[btn.key] = comp
formVisibleMap[btn.key] = true
}
function buildFormProps(btn: OperationButtonConfig): Record<string, any> {
const props: Record<string, any> = {}
// paramMap: { formProp: rowField } → 从行数据取值注入表单
if (btn.paramMap) {
for (const [formProp, rowField] of Object.entries(btn.paramMap)) {
props[formProp] = props.row[rowField]
}
}
// extraParams: 固定参数直接注入
if (btn.extraParams) {
Object.assign(props, btn.extraParams)
}
return props
}
function handleFormSuccess(key: string) {
emit('operation-action', key, props.row)
}
// ============================================================
// 按钮禁用判断
// ============================================================
function isDisabled(btn: OperationButtonConfig): boolean {
if (btn.disabledOnField) {
const val = props.row[btn.disabledOnField]
if (val === undefined || val === null || val === '' || val === false) {
return true
}
}
return false
}
</script>
<style lang="scss" scoped>
.operation-cell {
display: flex;
flex-wrap: wrap;
gap: 2px;
justify-content: center;
}
</style>

View File

@ -0,0 +1,132 @@
<template>
<div class="tab-area-wrapper">
<el-tabs
v-model="activeTab"
tab-position="top"
type="border-card"
class="tab-container"
@tab-click="handleTabClick"
>
<el-tab-pane
v-for="tab in tabs"
:key="tab.name"
:name="tab.name"
:lazy="false"
>
<template #label>
<span class="custom-tab-label">{{ tab.label }}</span>
</template>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
defineOptions({ name: 'TabArea' })
interface TabItem {
name: string
label: string
}
const props = withDefaults(
defineProps<{
tabs?: TabItem[]
defaultActive?: string
}>(),
{
tabs: () => [],
defaultActive: ''
}
)
const emit = defineEmits<{
(e: 'tab-change', tabName: string): void
}>()
const activeTab = ref(props.defaultActive || props.tabs[0]?.name || '')
const handleTabClick = (pane: any) => {
const name = pane?.name ?? pane?.props?.name ?? ''
if (name) {
activeTab.value = name
emit('tab-change', name)
}
}
</script>
<style lang="scss" scoped>
.tab-area-wrapper {
flex-shrink: 0;
}
.tab-container {
display: flex;
flex-direction: column;
:deep(.el-tabs__header) {
margin-bottom: 0;
flex-shrink: 0;
}
:deep(.el-tabs__header.is-top) {
padding: 4px 12px 0;
background: #f8fbff;
border-bottom: 1px solid #e8eef7;
margin: 0;
}
:deep(.el-tabs__nav-wrap::after) {
display: none;
}
:deep(.el-tabs__item.is-top) {
height: 38px;
line-height: 38px;
padding: 0 20px;
border-radius: 6px 6px 0 0;
color: #606266;
font-size: 14px;
font-weight: 500;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
border: 1px solid transparent;
border-bottom: none;
margin-right: 4px;
}
:deep(.el-tabs__item.is-top:hover) {
color: #409eff;
background-color: rgba(64, 158, 255, 0.05);
}
:deep(.el-tabs__item.is-top.is-active) {
color: #409eff;
font-weight: 600;
background: #ffffff;
border-color: #e8eef7;
border-bottom: 2px solid #ffffff;
margin-bottom: -1px;
position: relative;
z-index: 1;
}
:deep(.el-tabs__active-bar) {
height: 2px;
border-radius: 2px;
background-color: #409eff;
bottom: 0;
}
:deep(.el-tabs__content) {
display: none;
}
}
.custom-tab-label {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>

View File

@ -0,0 +1,159 @@
<!--
DetailPanel — 明细面板(通用)
根据 detailConfig 配置的 sections 渲染 el-descriptions 分区。
支持 text、tag、pre 三种渲染类型。
支持 translateField + tagResolver 集中式翻译。
支持 apiMethod 自动获取详情数据。
-->
<template>
<div class="detail-panel">
<div v-if="!row" class="empty-tip">请从上方列表中选择一项查看明细</div>
<template v-else>
<div v-for="(section, si) in detailConfig" :key="si" class="section">
<div class="section-title">{{ section.title }}</div>
<el-descriptions :column="section.columnCount" border size="small" class="detail-descriptions">
<el-descriptions-item
v-for="(field, fi) in section.fields"
:key="fi"
:label="field.label"
:span="field.span ?? 1"
>
<!-- tag 渲染 -->
<template v-if="field.renderType === 'tag'">
<el-tag size="small" :type="resolveTagType(field, getRowData()?.[field.key])">
{{ resolveDisplayValue(field, getRowData()?.[field.key]) }}
</el-tag>
</template>
<!-- pre 渲染 -->
<template v-else-if="field.renderType === 'pre'">
<pre class="order-list-pre">{{ getRowData()?.[field.key] ?? '—' }}</pre>
</template>
<!-- 默认文本渲染 -->
<template v-else>
{{ resolveDisplayValue(field, getRowData()?.[field.key]) }}
</template>
</el-descriptions-item>
</el-descriptions>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { TAG_RESOLVERS, translate } from '../template-config'
import type { DetailSectionConfig, DetailFieldConfig } from '../template-config'
defineOptions({ name: 'DetailPanel' })
const props = defineProps<{
row: Record<string, any> | null
detailConfig: DetailSectionConfig[]
/** 可选的 detail API 方法,传入后自动调用获取完整明细数据 */
apiMethod?: (...args: any[]) => Promise<any>
}>()
/** 通过 API 获取的增强数据(与 row 合并) */
const enrichedData = ref<Record<string, any> | null>(null)
watch(() => props.row, async (newRow) => {
if (newRow && props.apiMethod) {
try {
const res = await props.apiMethod({
id: newRow.id,
code: newRow.code
})
if (res && (res.code === 1 || res.code === 200)) {
enrichedData.value = res.data ?? res
} else {
enrichedData.value = null
}
} catch {
enrichedData.value = null
}
} else {
enrichedData.value = null
}
}, { immediate: true })
/** 合并 row + API 增强数据 */
function getRowData(): Record<string, any> | null {
if (!props.row) return null
if (enrichedData.value) {
return { ...props.row, ...enrichedData.value }
}
return props.row
}
/** 解析显示值:优先使用 translateField 翻译,否则显示原始值 */
function resolveDisplayValue(field: DetailFieldConfig, value: any): string {
if (field.translateField) {
return translate(field.translateField, value)
}
return value ?? '—'
}
/** 解析 tag 颜色 */
function resolveTagType(field: DetailFieldConfig, value: any): string {
if (field.tagResolver) {
const resolver = TAG_RESOLVERS[field.tagResolver]
if (resolver) return resolver(value)
}
if (field.tagType) {
if (typeof field.tagType === 'object') {
return field.tagType[String(value)] ?? 'info'
}
return field.tagType
}
return 'info'
}
</script>
<style lang="scss" scoped>
.detail-panel {
padding: 8px 0;
}
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 40px 0;
}
.section {
margin-bottom: 12px;
&:last-child {
margin-bottom: 0;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: #303133;
margin-bottom: 10px;
padding-left: 8px;
border-left: 3px solid #409eff;
line-height: 1.4;
}
}
.detail-descriptions {
:deep(.el-descriptions__label) {
width: 120px;
background: #fafbfc;
font-weight: 500;
}
}
.order-list-pre {
margin: 0;
font-family: inherit;
font-size: 13px;
line-height: 1.8;
white-space: pre-wrap;
color: #606266;
}
</style>

View File

@ -0,0 +1,227 @@
<!--
LogPanel — 操作日志面板(通用)
支持两种数据来源:
- apiMethod 传入 → 调用真实接口获取日志
- 无 apiMethod → 基于 row 生成模拟日志(开发调试用)
-->
<template>
<div class="log-panel">
<div class="section-title">操作日志</div>
<div v-if="apiLoading" v-loading="true" class="empty-tip">加载中…</div>
<div v-else-if="!logs.length" class="empty-tip">暂无操作日志</div>
<div v-else class="log-timeline">
<div v-for="(log, i) in logs" :key="i" class="log-item">
<div class="log-dot" :class="log.level" />
<div class="log-content">
<div class="log-header">
<span class="log-operator">{{ log.operator }}</span>
<span class="log-action">{{ log.action }}</span>
<el-tag v-if="log.result === '成功'" size="small" type="success">成功</el-tag>
<el-tag v-else-if="log.result === '失败'" size="small" type="danger">失败</el-tag>
<el-tag v-else size="small" type="info">{{ log.result }}</el-tag>
</div>
<div v-if="log.detail" class="log-detail">{{ log.detail }}</div>
<div class="log-time">{{ log.time }}</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
defineOptions({ name: 'LogPanel' })
interface LogItem {
operator: string
action: string
result: string
detail?: string
time: string
level: 'success' | 'info' | 'warning' | 'error'
}
const props = defineProps<{
/** 当前选中行数据(用于生成关联日志) */
row: Record<string, any> | null
/** 可选的日志 API 方法,传入后自动调用获取真实日志 */
apiMethod?: (...args: any[]) => Promise<any>
}>()
/** 通过 API 获取的真实日志列表 */
const apiLogs = ref<LogItem[] | null>(null)
const apiLoading = ref(false)
watch(() => props.row, async (newRow) => {
if (newRow && props.apiMethod) {
apiLoading.value = true
try {
const res = await props.apiMethod({
id: newRow.id,
code: newRow.code,
page: 1,
pageSize: 100
})
if (res && (res.code === 1 || res.code === 200)) {
const list = res.data?.list ?? res.data?.logs ?? res.list ?? res.logs ?? []
apiLogs.value = Array.isArray(list) ? list.map((item: any) => ({
operator: item.operator ?? item.creator ?? '—',
action: item.action ?? item.operation ?? '—',
result: item.result ?? item.status ?? '—',
detail: item.detail ?? item.description ?? '',
time: item.time ?? item.create_time ?? '—',
level: (item.result === '成功' || item.status === 'success') ? 'success'
: (item.result === '失败' || item.status === 'error') ? 'error'
: 'info'
})) : []
} else {
apiLogs.value = []
}
} catch {
apiLogs.value = []
} finally {
apiLoading.value = false
}
} else {
apiLogs.value = null
}
}, { immediate: true })
/** 基于 row 生成模拟日志(无 apiMethod 时使用) */
const mockLogs = computed<LogItem[]>(() => {
if (!props.row) return []
const rowName = props.row.name ?? props.row.code ?? '—'
const now = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
const fmt = (d: Date) =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
return [
{
operator: '系统',
action: `创建了「${rowName}」`,
result: '成功',
time: fmt(new Date(now.getTime() - 3600000 * 3)),
level: 'success'
},
{
operator: props.row.creator ?? '管理员',
action: `更新了「${rowName}」`,
result: '成功',
detail: `修改了状态和相关配置`,
time: fmt(new Date(now.getTime() - 3600000)),
level: 'success'
}
]
})
/** 最终展示的日志:优先使用 API 日志,否则使用 mock 日志 */
const logs = computed<LogItem[]>(() => {
if (apiLogs.value !== null) {
return apiLogs.value
}
return mockLogs.value
})
</script>
<style lang="scss" scoped>
.log-panel {
padding: 8px 0;
}
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 40px 0;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: #303133;
margin-bottom: 12px;
padding-left: 4px;
border-left: 3px solid #409eff;
}
.log-timeline {
padding-left: 8px;
.log-item {
display: flex;
gap: 12px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px dashed #ebeef5;
&:last-child {
border-bottom: none;
margin-bottom: 0;
}
}
.log-dot {
flex-shrink: 0;
width: 8px;
height: 8px;
margin-top: 6px;
border-radius: 50%;
background: #c0c4cc;
&.success {
background: #67c23a;
}
&.warning {
background: #e6a23c;
}
&.error {
background: #f56c6c;
}
&.info {
background: #409eff;
}
}
.log-content {
flex: 1;
min-width: 0;
}
.log-header {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.log-operator {
font-weight: 600;
font-size: 13px;
color: #303133;
}
.log-action {
font-size: 13px;
color: #606266;
}
.log-detail {
margin-top: 4px;
font-size: 12px;
color: #909399;
}
.log-time {
margin-top: 2px;
font-size: 12px;
color: #c0c4cc;
}
}
</style>

View File

@ -0,0 +1,648 @@
/**
* 【工作台管理】页面配置 — 基于 waveOrder2 架构设计
*/
import type { Component } from 'vue'
import DetailPanel from './components/DetailPanel.vue'
import LogPanel from './components/LogPanel.vue'
import {
list as workbenchList,
detail as workbenchDetail,
create as workbenchCreate,
update as workbenchUpdate,
del as workbenchDelete,
checkBarcode as workbenchCheckBarcode,
bindCamera as workbenchBindCamera
} from '@/api/workbench/workbench'
import { list as cameraList } from '@/api/camera/camera'
// ============================================================
// 〇、全局页面配置
// ============================================================
export const PAGE_CONFIG = {
/** 是否显示顶部多标签栏 */
showTabArea: false,
/** 单页模式:不显示标签栏,仅一个标签页内容 */
singlePage: true,
/** 是否启用详情面板(底部分栏 + 显示/隐藏详情按钮),false 时表格占满全高 */
enableDetailPanel: false
}
// ============================================================
// 〇-A、组件注册表 — 所有可复用组件在此注册
// ============================================================
export const COMPONENT_REGISTRY: Record<string, Component> = {
DetailPanel,
LogPanel
}
// ============================================================
// 〇-B、SCANBOX_GROUPS — ScanBox 分组名称
// ============================================================
export const SCANBOX_GROUPS = {
basic: '基础信息',
process: '流程状态',
time: '时间范围',
custom: '自定义字段'
} as const
// ============================================================
// 一、FIELD_DICT — 全局字段预设表(唯一真相来源)
// ============================================================
// 每个字段拥有:
// label — 唯一翻译文本
// scanBox — ScanBox 渲染配置(type/options/group)
// table — 表格列配置(minWidth/fixed/align/sortable)
// slot — 单元格渲染配置(tag/tagResolver/translateField)
// detailLabel — 明细面板中的标签文本(可选,默认用 label)
// filterParamMap — ScanBox 筛选值 → API 传参值映射
export interface FieldDefinition {
key: string
label: string
scanBox: {
type: 'text' | 'select' | 'daterange' | 'number'
group?: string
options?: { label: string; value: any }[]
} | null
table: {
minWidth?: number
width?: number
fixed?: 'left' | 'right' | boolean
align?: 'left' | 'center' | 'right'
sortable?: boolean
showOverflowTooltip?: boolean
copyAction?: 'copy' | 'copyQr'
copyValue?: (row: any) => any
} | null
slot: {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
} | null
detailLabel?: string
filterParamMap?: Record<string, string>
}
// ============================================================
// VALUE_MAPS — 值翻译映射
// ============================================================
export const VALUE_MAPS: Record<string, Record<string, string>> = {
workbenchStatus: { '1': '启用', '0': '禁用', '启用': '启用', '禁用': '禁用' },
bool: { '1': '是', '0': '否', '是': '是', '否': '否' }
}
/** 从 VALUE_MAPS 衍生 options(优先取中文值作为 option value) */
export function getOptions(field: string): { label: string; value: string }[] {
const map = VALUE_MAPS[field]
if (!map) return []
const seen = new Set<string>()
const opts: { label: string; value: string }[] = []
const chineseKeys: [string, string][] = []
const otherKeys: [string, string][] = []
for (const [v, l] of Object.entries(map)) {
if (/^[\u4e00-\u9fa5]/.test(v)) {
chineseKeys.push([v, l])
} else {
otherKeys.push([v, l])
}
}
for (const [v, l] of [...chineseKeys, ...otherKeys]) {
if (!seen.has(l)) {
seen.add(l)
opts.push({ label: l, value: v })
}
}
return opts
}
/** 翻译 value → label */
export function translate(field: string, value: any): string {
const map = VALUE_MAPS[field]
if (!map) return String(value ?? '—')
return map[String(value)] ?? String(value ?? '—')
}
/** 格式化时间戳为 YYYY-MM-DD HH:mm:ss */
export function formatTime(value: any): string {
if (!value) return '—'
try {
const d = new Date(value)
if (isNaN(d.getTime())) return String(value)
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
} catch {
return String(value)
}
}
// ============================================================
// TAG_RESOLVERS — 标签颜色解析器
// ============================================================
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
resolveWorkbenchStatusTag(v) {
if (v === undefined || v === null) return 'info'
return Number(v) === 1 ? 'success' : 'info'
},
resolveBoolTag(v) {
if (v === undefined || v === null) return 'info'
if (v === '是' || v === true || v === 1 || v === '1') return 'success'
return 'info'
}
}
// ============================================================
// 二、FIELD_DICT 实例 — 工作台管理字段定义
// ============================================================
export const FIELD_DICT: Record<string, FieldDefinition> = {
id: {
key: 'id',
label: 'ID',
scanBox: null,
table: { width: 80, sortable: true },
slot: null,
detailLabel: 'ID'
},
name: {
key: 'name',
label: '工作台名称',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: { minWidth: 140, showOverflowTooltip: true },
slot: null,
detailLabel: '工作台名称'
},
barcode: {
key: 'barcode',
label: '条码',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
table: { minWidth: 120, showOverflowTooltip: true },
slot: null,
detailLabel: '条码'
},
warehouse_id: {
key: 'warehouse_id',
label: '仓库ID',
scanBox: null,
table: { width: 100 },
slot: null,
detailLabel: '仓库ID'
},
status: {
key: 'status',
label: '状态',
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('workbenchStatus') },
table: { width: 80, align: 'center' },
slot: { type: 'tag', tagResolver: 'resolveWorkbenchStatusTag', translateField: 'workbenchStatus' },
detailLabel: '状态',
filterParamMap: { '启用': '1', '禁用': '0' }
},
device_ids: {
key: 'device_ids',
label: '绑定摄像头',
scanBox: null,
table: { width: 120, align: 'center' },
slot: { type: 'tag', tagType: { '0': 'info' } },
detailLabel: '绑定摄像头'
},
remark: {
key: 'remark',
label: '备注',
scanBox: null,
table: { minWidth: 140, showOverflowTooltip: true },
slot: null,
detailLabel: '备注'
},
created_at: {
key: 'created_at',
label: '创建时间',
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
table: { minWidth: 160, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '创建时间'
},
updated_at: {
key: 'updated_at',
label: '更新时间',
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
table: { minWidth: 160, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '更新时间'
},
/** 操作列(虚拟字段,仅用于表格列渲染) */
operation: {
key: 'operation',
label: '操作',
scanBox: null,
table: { minWidth: 260, fixed: 'right', align: 'center' },
slot: { type: 'operation' }
}
}
// ============================================================
// 三、ColumnSlotConfig — 列单元格渲染配置
// ============================================================
export interface ColumnSlotConfig {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
}
// ============================================================
// 三-A、OperationButtonConfig — 操作列按钮配置
// ============================================================
export interface OperationButtonConfig {
key: string
label: string
type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | ''
actionType: 'form' | 'action'
formKey?: string
formTitle?: string
formWidth?: string
paramMap?: Record<string, string>
extraParams?: Record<string, any>
disabledOnField?: string
confirmMessage?: string
confirmTitle?: string
confirmType?: 'warning' | 'danger' | 'info'
confirmButtonText?: string
}
// ============================================================
// 四、DetailFieldConfig / DetailSectionConfig — 明细面板配置
// ============================================================
export interface DetailFieldConfig {
key: string
label?: string
span?: number
renderType?: 'text' | 'tag' | 'pre'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
}
export interface DetailSectionConfig {
title: string
columnCount: number
fields: DetailFieldConfig[]
}
export interface DetailTabConfig {
name: string
label: string
componentKey: string
component?: Component
}
// ============================================================
// 五、TabPageApiConfig — 标签页接口插槽配置
// ============================================================
export type ApiMethod = (...args: any[]) => Promise<any>
export type ApiSource = 'api' | 'list'
export type ComponentApiConfig = { source: 'list' } | ApiMethod
export interface TabPageApiConfig {
/** 列表查询接口 */
list: ApiMethod
/** 明细面板接口(可选,不配则用 row 数据) */
detail?: ComponentApiConfig
/** 操作日志接口(可选) */
log?: ComponentApiConfig
/** 导出接口(可选) */
export?: ApiMethod
/** 导出进度查询接口(可选) */
exportProgress?: ApiMethod
/** ScanBox 下拉选项数据源接口(可选) */
scanBoxOptions?: Record<string, ApiMethod>
/** 工具栏按钮 → API 方法映射(可选) */
toolbar?: Record<string, ApiMethod>
/** 列表响应解析器 */
parseListResponse?: (res: any) => { list: any[]; total: number }
/** 构建列表请求参数 */
buildListParams?: (params: {
pagination: { page: number; pageSize: number }
conditions: Record<string, any>
sort?: { prop: string; order: string }
}) => Record<string, any>
}
// ============================================================
// 六、TabPageRawConfig — 标签页声明配置(仅用 key 引用)
// ============================================================
export interface TabPageRawConfig {
name: string
label: string
scanBoxCacheKey: string
/** ScanBox 需要的字段 key 列表(从 FIELD_DICT 中查找) */
scanBoxFieldKeys: string[]
/** 表格需要的列 key 列表(从 FIELD_DICT 中查找) */
tableColumnKeys: string[]
upperTableDefaults: {
title: string
enableColumnConfig?: boolean
showIndex?: boolean
showSelection?: boolean
emptyText?: string
}
/** 明细面板标签页配置 */
detailTabs?: { name: string; label: string; componentKey: string }[]
/** 明细面板分区配置(字段 key 列表,resolveTabConfig 展开) */
detailSections: {
title: string
columnCount: number
fieldKeys: string[]
}[]
/** 接口配置(有 api 时启用真实接口) */
api?: TabPageApiConfig
/** 操作列按钮配置(需 tableColumnKeys 包含 'operation') */
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 七、TabPageConfig — 展开后的完整配置(给 index.vue 使用)
// ============================================================
export interface TabPageConfig {
name: string
label: string
scanBoxCacheKey: string
scanBoxFields: Record<string, any>[]
upperTable: {
title: string
enableColumnConfig: boolean
showIndex: boolean
showSelection: boolean
emptyText: string
columns: Record<string, any>[]
}
columnSlots: Record<string, ColumnSlotConfig>
detailConfig: DetailSectionConfig[]
detailTabs: DetailTabConfig[]
api?: TabPageApiConfig
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 八、resolveTabConfig — 加载时将 RawConfig 展开为完整配置
// ============================================================
export function resolveTabConfig(raw: TabPageRawConfig): TabPageConfig {
// 展开 ScanBox 字段
const scanBoxFields: Record<string, any>[] = []
for (const key of raw.scanBoxFieldKeys) {
const def = FIELD_DICT[key]
if (!def || !def.scanBox) continue
scanBoxFields.push({
label: def.label,
value: def.key,
type: def.scanBox.type,
options: def.scanBox.options ? [...def.scanBox.options] : undefined,
group: def.scanBox.group,
required: (def.scanBox as any).required
})
}
// 展开表格列
const columns: Record<string, any>[] = []
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.table) continue
columns.push({
prop: def.key,
label: def.label,
...def.table
})
}
// 展开列插槽
const columnSlots: Record<string, ColumnSlotConfig> = {}
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.slot) continue
columnSlots[def.key] = { ...def.slot }
}
// 展开明细面板配置
const detailConfig: DetailSectionConfig[] = raw.detailSections.map((sec) => ({
title: sec.title,
columnCount: sec.columnCount,
fields: sec.fieldKeys
.map((key): DetailFieldConfig | null => {
const def = FIELD_DICT[key]
if (!def) return null
return {
key: def.key,
label: def.detailLabel ?? def.label,
translateField: def.slot?.translateField,
tagResolver: def.slot?.tagResolver,
tagType: def.slot?.tagType,
renderType: def.slot?.type === 'tag' ? 'tag' : 'text'
}
})
.filter((f): f is DetailFieldConfig => f !== null)
}))
// 展开明细标签页(解析 componentKey → Component)
const detailTabs: DetailTabConfig[] = raw.detailTabs
? raw.detailTabs.map((tab) => ({
name: tab.name,
label: tab.label,
componentKey: tab.componentKey,
component: COMPONENT_REGISTRY[tab.componentKey]
}))
: [{ name: 'detail', label: '明细', componentKey: 'DetailPanel', component: COMPONENT_REGISTRY['DetailPanel'] }]
return {
name: raw.name,
label: raw.label,
scanBoxCacheKey: raw.scanBoxCacheKey,
scanBoxFields,
upperTable: {
title: raw.upperTableDefaults.title,
enableColumnConfig: raw.upperTableDefaults.enableColumnConfig ?? true,
showIndex: raw.upperTableDefaults.showIndex ?? true,
showSelection: raw.upperTableDefaults.showSelection ?? true,
emptyText: raw.upperTableDefaults.emptyText ?? '暂无数据',
columns
},
columnSlots,
detailConfig,
detailTabs,
api: raw.api,
operationButtons: raw.operationButtons
}
}
// ============================================================
// 九、buildWhereConditions — 将 ScanBox 条件转为 API where 参数
// ============================================================
export function buildWhereConditions(rawConditions: Record<string, any>): Record<string, any> {
const where: Record<string, any> = {}
for (const [key, cond] of Object.entries(rawConditions || {})) {
let value: any = undefined
if (cond && typeof cond === 'object' && 'operator' in cond) {
value = (cond as any).value
} else if (cond !== undefined && cond !== null && cond !== '') {
value = Array.isArray(cond) ? cond[0] ?? '' : cond
}
if (value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
continue
}
const def = FIELD_DICT[key]
if (def?.filterParamMap) {
const mapped = def.filterParamMap[String(value)]
if (mapped !== undefined) {
where[key] = mapped
continue
}
}
where[key] = value
}
return where
}
// ============================================================
// 十、工具栏按钮系统
// ============================================================
export interface ToolbarButtonConfig {
key: string
label: string
category: 'common' | 'function' | 'basic'
size?: '' | 'default' | 'small' | 'large'
type?: '' | 'primary' | 'success' | 'warning' | 'info' | 'danger'
plain?: boolean
loadingKey?: string
disabledKey?: string
action: string
dynamicLabelKey?: string
onlyForTabs?: string[]
buttonType?: 'default' | 'dropdown'
dropdownOptions?: Array<{ label: string; action: string; divided?: boolean }>
formKey?: string
}
export const TOOLBAR_BUTTONS: Record<string, ToolbarButtonConfig> = {
refresh: {
key: 'refresh',
label: '刷新',
category: 'common',
type: 'primary',
size: 'small',
loadingKey: 'loading',
action: 'loadData'
},
addWorkbench: {
key: 'addWorkbench',
label: '新增工作台',
category: 'function',
type: 'success',
size: 'small',
action: 'openCreateDialog'
},
toggleDetail: {
key: 'toggleDetail',
label: '显示详情',
category: 'basic',
dynamicLabelKey: 'detailToggleLabel',
size: 'small',
action: 'toggleDetailVisible'
}
}
/** 按标签页名称获取工具栏按钮列表 */
export function getTabToolbarButtons(tabName: string): ToolbarButtonConfig[] {
return Object.values(TOOLBAR_BUTTONS).filter((btn) => {
if (btn.onlyForTabs && !btn.onlyForTabs.includes(tabName)) return false
if (!PAGE_CONFIG.enableDetailPanel && btn.key === 'toggleDetail') return false
return true
})
}
// ============================================================
// 十一、标签页注册表 — 工作台管理
// ============================================================
export const tabPages: TabPageRawConfig[] = [
{
name: 'workbench',
label: '工作台管理',
scanBoxCacheKey: 'setting-workbench',
scanBoxFieldKeys: ['name', 'barcode', 'status', 'created_at'],
tableColumnKeys: ['id', 'name', 'barcode', 'warehouse_id', 'status', 'device_ids', 'remark', 'created_at', 'updated_at', 'operation'],
upperTableDefaults: {
title: '工作台列表',
showSelection: false,
showIndex: true,
emptyText: '暂无工作台数据,可调整左侧筛选条件或点击新增'
},
detailTabs: [
{ name: 'detail', label: '明细', componentKey: 'DetailPanel' }
],
detailSections: [
{
title: '基础信息',
columnCount: 1,
fieldKeys: ['id', 'warehouse_id', 'name', 'barcode', 'status', 'remark']
},
{
title: '时间信息',
columnCount: 2,
fieldKeys: ['created_at', 'updated_at']
}
],
api: {
list: workbenchList,
detail: workbenchDetail,
parseListResponse(res) {
const data = res?.data || res
return {
list: (data as any)?.list ?? [],
total: Number((data as any)?.pagination?.total ?? (data as any)?.total ?? 0)
}
},
buildListParams({ pagination, conditions, sort }) {
return {
pagination: { page: pagination.page, pageSize: pagination.pageSize },
where: buildWhereConditions(conditions),
...(sort?.prop ? { sortField: sort.prop, sortOrder: sort.order === 'ascending' ? 'ASC' : 'DESC' } : {})
}
}
},
operationButtons: [
{
key: 'viewDetail',
label: '详情',
actionType: 'action',
type: 'primary'
},
{
key: 'edit',
label: '编辑',
actionType: 'action',
type: 'primary'
},
{
key: 'bindCamera',
label: '摄像头',
actionType: 'action',
type: 'success'
},
{
key: 'delete',
label: '删除',
actionType: 'action',
type: 'danger',
confirmMessage: '确定要删除该工作台吗?删除后数据不可恢复。',
confirmTitle: '删除确认',
confirmType: 'warning',
confirmButtonText: '确定'
}
]
}
]
// ============================================================
// 十三、向后兼容导出
// ============================================================
export const templateTabs = tabPages.map((t) => ({ name: t.name, label: t.label, scanBoxCacheKey: t.scanBoxCacheKey }))

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,107 @@
<!--
ExampleFormDialog — 示例表单弹窗(模板)
功能按钮对应的表单组件放在 pages/ 目录下。
使用方式:
1. 在 template-config.ts 的 COMPONENT_REGISTRY 中注册
2. 在 template-config.ts 的 TOOLBAR_BUTTONS 中添加功能按钮,设置 formKey
3. index.vue 中通过工具栏按钮触发打开
-->
<template>
<el-dialog
:model-value="visible"
title="示例操作"
width="500px"
align-center
destroy-on-close
:close-on-click-modal="false"
@closed="handleClosed"
>
<div class="form-body">
<el-form ref="formRef" :model="form" label-width="100px" size="small">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" placeholder="请输入名称" />
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="form.description"
type="textarea"
:rows="3"
placeholder="请输入描述"
/>
</el-form-item>
</el-form>
</div>
<template #footer>
<el-button size="small" @click="handleClosed">取消</el-button>
<el-button size="small" type="primary" :loading="submitting" @click="handleSubmit">
确认
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
defineOptions({ name: 'ExampleFormDialog' })
const props = defineProps<{
visible: boolean
/** 从行数据注入的初始值(由 OperationCellRenderer 的 paramMap 传递) */
id?: string | number
code?: string
name?: string
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
(e: 'success'): void
}>()
const formRef = ref<any>(null)
const submitting = ref(false)
const form = reactive({
name: '',
description: ''
})
// 重置表单
watch(() => props.visible, (v) => {
if (v) {
form.name = props.name ?? ''
form.description = ''
}
})
function handleClosed() {
emit('update:visible', false)
}
async function handleSubmit() {
submitting.value = true
try {
// ★ 替换为真实 API 调用
// const res = await yourApi.submit({ id: props.id, ...form })
await new Promise((r) => setTimeout(r, 500))
ElMessage.success('操作成功')
emit('update:visible', false)
emit('success')
} catch (e: any) {
ElMessage.error(e?.message || '操作失败')
} finally {
submitting.value = false
}
}
</script>
<style lang="scss" scoped>
.form-body {
padding: 12px 0;
}
</style>

View File

@ -23,8 +23,8 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { ColumnSlotConfig } from '../config/template-config'
import { TAG_RESOLVERS, translate, formatTime } from '../config/template-config'
import type { ColumnSlotConfig } from '../config/camara-config'
import { TAG_RESOLVERS, translate, formatTime } from '../config/camara-config'
defineOptions({ name: 'ColumnCellRenderer' })

View File

@ -58,8 +58,8 @@
<script setup lang="ts">
import { ref, reactive, watch, type Component } from 'vue'
import { ElMessageBox } from 'element-plus'
import { COMPONENT_REGISTRY } from '../config/template-config'
import type { OperationButtonConfig } from '../config/template-config'
import { COMPONENT_REGISTRY } from '../config/camara-config'
import type { OperationButtonConfig } from '../config/camara-config'
defineOptions({ name: 'OperationCellRenderer' })

View File

@ -42,8 +42,8 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { TAG_RESOLVERS, translate } from '../template-config'
import type { DetailSectionConfig, DetailFieldConfig } from '../template-config'
import { TAG_RESOLVERS, translate } from '../camara-config'
import type { DetailSectionConfig, DetailFieldConfig } from '../camara-config'
defineOptions({ name: 'DetailPanel' })

View File

@ -6,7 +6,7 @@
===== 快速复制使用 =====
1. 复制整个 views/mode/ 文件夹 → 重命名为你的页面名(如 views/order/myPage/)
2. 修改 defineOptions name(如 'MyPage')
3. 编辑 config/template-config.ts:
3. 编辑 config/camara-config.ts:
a. 在 FIELD_DICT 中添加页面字段
b. 在 tabPages 中配置标签页(引用 FIELD_DICT 的 key)
c. 在 TabPageApiConfig 中接入真实接口
@ -270,7 +270,7 @@ import {
type TabPageConfig,
type DetailTabConfig,
type ToolbarButtonConfig,
} from './config/template-config'
} from './config/camara-config'
// ============================================================
// 容器高度
@ -694,6 +694,9 @@ onMounted(() => {
</script>
<style lang="scss" scoped>
/* ===== 引入 waveOrder 共享样式(scan-box / toolbar / split-stack / pane-resizer / lower-level 等) ===== */
@use "../../order/orderManagement/styles/order-sub.scss";
/* ================================================================
整体布局
================================================================ */
@ -719,7 +722,7 @@ onMounted(() => {
}
/* ================================================================
2. 主内容区
2. 主内容区容器
================================================================ */
.main-container {
flex: 1;
@ -727,33 +730,66 @@ onMounted(() => {
flex-direction: column;
min-height: 0;
background: #fff;
border: 1px solid #e8eef7;
border-radius: 0 0 6px 6px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
overflow: hidden;
}
.order-sub-container {
display: flex;
height: 100%;
width: 100%;
background-color: #f0f2f5;
:deep(.scan-box-container) {
flex: 0 0 250px;
/* ================================================================
3. ScanBox"筛选/过滤"标签样式(对齐页面顶部 TabArea 风格)
================================================================ */
.main-container {
:deep(.scan-box-container .scan-tabs) {
flex-shrink: 0;
height: 100%;
border-bottom: 1px solid #e8eef7;
background: #f8fbff;
}
:deep(.scan-box-container .scan-tabs .el-tabs__header) {
margin: 0;
padding: 4px 8px 0;
}
:deep(.scan-box-container .scan-tabs .el-tabs__nav-wrap::after) {
display: none;
}
:deep(.scan-box-container .scan-tabs .el-tabs__active-bar) {
display: none;
}
:deep(.scan-box-container .scan-tabs .el-tabs__item) {
height: 38px;
line-height: 38px;
font-size: 14px;
font-weight: 500;
padding: 0 20px;
color: #606266;
border: 1px solid transparent;
border-bottom: none;
border-radius: 6px 6px 0 0;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
margin-right: 4px;
}
:deep(.scan-box-container .scan-tabs .el-tabs__item:hover) {
color: #409eff;
background-color: rgba(64, 158, 255, 0.05);
}
:deep(.scan-box-container .scan-tabs .el-tabs__item.is-active) {
color: #409eff;
font-weight: 600;
background: #ffffff;
border-color: #e8eef7;
border-bottom-color: #fff;
}
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
padding: 10px;
overflow: hidden;
min-width: 0;
}
/* ================================================================
4. 过渡动画
================================================================ */
.tab-content-inner {
flex: 1;
display: flex;
@ -761,141 +797,6 @@ onMounted(() => {
min-height: 0;
}
/* ================================================================
3. 工具栏
================================================================ */
.toolbar {
margin-bottom: 3px;
padding: 6px 10px;
border: 1px solid #ebeef5;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
min-width: 0;
overflow: hidden;
.toolbar-left {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 10px;
overflow: hidden;
}
.toolbar-right {
flex: 0 0 auto;
margin-left: 10px;
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
}
}
/* ================================================================
4. 分栏区域
================================================================ */
.split-stack {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
:deep(.el-card__header) {
padding: 2px 12px;
font-size: 13px;
}
}
.upper-wrapper {
flex: 1 1 62%;
min-height: 0;
overflow: hidden;
}
/* 详情面板禁用时,表格占满全高 */
.upper-wrapper--full {
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
.pane-resizer {
flex-shrink: 0;
height: 5px;
cursor: row-resize;
background-color: #f0f2f5;
border-top: 1px solid #ebeef5;
border-bottom: 1px solid #ebeef5;
transition: background-color 0.2s;
user-select: none;
&:hover {
background-color: #d3d9e3;
}
}
.lower-level {
flex: 1 1 38%;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
:deep(.el-card) {
height: 100%;
display: flex;
flex-direction: column;
}
}
.no-selection {
flex: 1 1 38%;
min-height: 0;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ebeef5;
border-radius: 4px;
.empty-tip p {
font-size: 14px;
color: #909399;
}
}
/* ================================================================
5. 明细面板
================================================================ */
.detail-header {
flex-shrink: 0;
border-bottom: 1px solid #e8eef7;
background: #fff;
padding: 0 12px;
.detail-tab {
:deep(.el-tabs__header) {
margin-bottom: 0;
}
:deep(.el-tabs__nav-wrap::after) {
height: 1px;
}
}
}
.detail-container {
flex: 1;
overflow: auto;
padding: 12px;
background: #fff;
}
/* ================================================================
6. 过渡动画
================================================================ */
.tab-fade-enter-active,
.tab-fade-leave-active {
transition: opacity 0.2s ease;
@ -908,7 +809,7 @@ onMounted(() => {
}
/* ================================================================
7. 空状态
5. 空状态
================================================================ */
.empty-tip {
font-size: 13px;

View File

@ -4,8 +4,8 @@
功能按钮对应的表单组件放在 pages/ 目录下。
使用方式:
1. 在 template-config.ts 的 COMPONENT_REGISTRY 中注册
2. 在 template-config.ts 的 TOOLBAR_BUTTONS 中添加功能按钮,设置 formKey
1. 在 camara-config.ts 的 COMPONENT_REGISTRY 中注册
2. 在 camara-config.ts 的 TOOLBAR_BUTTONS 中添加功能按钮,设置 formKey
3. index.vue 中通过工具栏按钮触发打开
-->
<template>

View File

@ -0,0 +1,65 @@
<!--
ColumnCellRenderer — 通用表格列渲染器
根据传入的 ColumnSlotConfig 决定如何渲染单元格:
- type='tag' → el-tag(支持 tagResolver / tagType 颜色映射)
- type='text' → 纯文本(支持 datetime 格式化)
- type='default' → 默认插槽渲染
- type='operation' → 操作列(由 OperationCellRenderer 处理)
-->
<template>
<template v-if="!config || config.type === 'default'">
<slot />
</template>
<template v-else-if="config.type === 'tag'">
<el-tag size="small" :type="resolvedTagType">
{{ displayValue }}
</el-tag>
</template>
<template v-else>
<span>{{ displayValue }}</span>
</template>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import type { ColumnSlotConfig } from '../config/camaraserver-config'
import { TAG_RESOLVERS, translate, formatTime } from '../config/camaraserver-config'
defineOptions({ name: 'ColumnCellRenderer' })
const props = defineProps<{
/** 列插槽渲染配置 */
config: ColumnSlotConfig | undefined
/** 单元格值 */
value: any
}>()
/** 显示文本:translateField 翻译 > format 格式化 > 原始值 */
const displayValue = computed(() => {
const v = props.value
if (props.config?.translateField) {
return translate(props.config.translateField, v)
}
if (props.config?.format === 'datetime') {
return formatTime(v)
}
return v ?? '—'
})
const resolvedTagType = computed(() => {
if (!props.config || props.config.type !== 'tag') return ''
const { tagType, tagResolver } = props.config
// 优先使用 tagResolver(函数名映射)
if (tagResolver && TAG_RESOLVERS[tagResolver]) {
return TAG_RESOLVERS[tagResolver](props.value)
}
// 其次使用 tagType 映射表(用原始值查找)
if (tagType && typeof tagType === 'object') {
return tagType[String(props.value)] ?? 'info'
}
// 最后使用固定值
return (typeof tagType === 'string' ? tagType : 'info')
})
</script>

View File

@ -0,0 +1,175 @@
<!--
OperationCellRenderer — 表格操作列渲染组件
根据 operationButtons 配置渲染按钮列表。
支持的行为类型:
- actionType='action' → 触发 @operation-action 事件(可选配置 confirmMessage 弹确认框)
- actionType='form' → 打开 COMPONENT_REGISTRY 中注册的表单组件
使用方式:在 index.vue 中通过插槽 column-operation 引入:
<OperationCellRenderer
:buttons="currentTabConfig?.operationButtons"
:row="row"
@operation-action="handleOperationAction"
/>
-->
<template>
<div class="operation-cell">
<template v-for="btn in buttons" :key="btn.key">
<!-- action 按钮:支持确认弹窗 -->
<el-button
v-if="btn.actionType === 'action'"
link
:type="btn.type || 'primary'"
size="small"
:loading="actionLoadingMap[btn.key]"
:disabled="isDisabled(btn)"
@click.stop="handleActionClick(btn)"
>
{{ btn.label }}
</el-button>
<!-- form 按钮:打开表单弹窗 -->
<template v-else-if="btn.actionType === 'form'">
<el-button
link
:type="btn.type || 'primary'"
size="small"
:disabled="isDisabled(btn)"
@click.stop="openForm(btn)"
>
{{ btn.label }}
</el-button>
<!-- 表单弹窗 -->
<component
:is="resolvedFormComponents[btn.key]"
v-if="resolvedFormComponents[btn.key] && activeFormKey === btn.key"
v-model:visible="formVisibleMap[btn.key]"
v-bind="buildFormProps(btn)"
@success="handleFormSuccess(btn.key)"
/>
</template>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, type Component } from 'vue'
import { ElMessageBox } from 'element-plus'
import { COMPONENT_REGISTRY } from '../config/camaraserver-config'
import type { OperationButtonConfig } from '../config/camaraserver-config'
defineOptions({ name: 'OperationCellRenderer' })
const props = defineProps<{
/** 操作按钮配置列表(来自 TabPageConfig.operationButtons) */
buttons?: OperationButtonConfig[]
/** 当前行数据 */
row: Record<string, any>
}>()
const emit = defineEmits<{
/** action 按钮点击事件(key: 按钮标识, row: 行数据) */
(e: 'operation-action', key: string, row: Record<string, any>): void
}>()
// ===== form 弹窗管理 =====
const activeFormKey = ref('')
const formVisibleMap = reactive<Record<string, boolean>>({})
const resolvedFormComponents = ref<Record<string, Component>>({})
const actionLoadingMap = reactive<Record<string, boolean>>({})
// ============================================================
// action 按钮:支持确认弹窗
// ============================================================
async function handleActionClick(btn: OperationButtonConfig) {
if (btn.confirmMessage) {
try {
await ElMessageBox.confirm(
btn.confirmMessage,
btn.confirmTitle || '确认操作',
{
confirmButtonText: btn.confirmButtonText || '确定',
cancelButtonText: '取消',
type: (btn.confirmType || 'warning') as any
}
)
} catch {
return // 取消
}
}
actionLoadingMap[btn.key] = true
try {
emit('operation-action', btn.key, props.row)
} finally {
actionLoadingMap[btn.key] = false
}
}
// ============================================================
// form 按钮:打开表单弹窗
// ============================================================
function openForm(btn: OperationButtonConfig) {
if (!btn.formKey) return
const comp = COMPONENT_REGISTRY[btn.formKey]
if (!comp) {
console.warn(`[OperationCellRenderer] 未注册的表单组件: ${btn.formKey}`)
return
}
activeFormKey.value = btn.key
resolvedFormComponents.value[btn.key] = comp
formVisibleMap[btn.key] = true
}
function buildFormProps(btn: OperationButtonConfig): Record<string, any> {
const props: Record<string, any> = {}
// paramMap: { formProp: rowField } → 从行数据取值注入表单
if (btn.paramMap) {
for (const [formProp, rowField] of Object.entries(btn.paramMap)) {
props[formProp] = props.row[rowField]
}
}
// extraParams: 固定参数直接注入
if (btn.extraParams) {
Object.assign(props, btn.extraParams)
}
return props
}
function handleFormSuccess(key: string) {
emit('operation-action', key, props.row)
}
// ============================================================
// 按钮禁用判断
// ============================================================
function isDisabled(btn: OperationButtonConfig): boolean {
if (btn.disabledOnField) {
const val = props.row[btn.disabledOnField]
if (val === undefined || val === null || val === '' || val === false) {
return true
}
}
return false
}
</script>
<style lang="scss" scoped>
.operation-cell {
display: flex;
flex-wrap: wrap;
gap: 2px;
justify-content: center;
}
</style>

View File

@ -0,0 +1,132 @@
<template>
<div class="tab-area-wrapper">
<el-tabs
v-model="activeTab"
tab-position="top"
type="border-card"
class="tab-container"
@tab-click="handleTabClick"
>
<el-tab-pane
v-for="tab in tabs"
:key="tab.name"
:name="tab.name"
:lazy="false"
>
<template #label>
<span class="custom-tab-label">{{ tab.label }}</span>
</template>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
defineOptions({ name: 'TabArea' })
interface TabItem {
name: string
label: string
}
const props = withDefaults(
defineProps<{
tabs?: TabItem[]
defaultActive?: string
}>(),
{
tabs: () => [],
defaultActive: ''
}
)
const emit = defineEmits<{
(e: 'tab-change', tabName: string): void
}>()
const activeTab = ref(props.defaultActive || props.tabs[0]?.name || '')
const handleTabClick = (pane: any) => {
const name = pane?.name ?? pane?.props?.name ?? ''
if (name) {
activeTab.value = name
emit('tab-change', name)
}
}
</script>
<style lang="scss" scoped>
.tab-area-wrapper {
flex-shrink: 0;
}
.tab-container {
display: flex;
flex-direction: column;
:deep(.el-tabs__header) {
margin-bottom: 0;
flex-shrink: 0;
}
:deep(.el-tabs__header.is-top) {
padding: 4px 12px 0;
background: #f8fbff;
border-bottom: 1px solid #e8eef7;
margin: 0;
}
:deep(.el-tabs__nav-wrap::after) {
display: none;
}
:deep(.el-tabs__item.is-top) {
height: 38px;
line-height: 38px;
padding: 0 20px;
border-radius: 6px 6px 0 0;
color: #606266;
font-size: 14px;
font-weight: 500;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
border: 1px solid transparent;
border-bottom: none;
margin-right: 4px;
}
:deep(.el-tabs__item.is-top:hover) {
color: #409eff;
background-color: rgba(64, 158, 255, 0.05);
}
:deep(.el-tabs__item.is-top.is-active) {
color: #409eff;
font-weight: 600;
background: #ffffff;
border-color: #e8eef7;
border-bottom: 2px solid #ffffff;
margin-bottom: -1px;
position: relative;
z-index: 1;
}
:deep(.el-tabs__active-bar) {
height: 2px;
border-radius: 2px;
background-color: #409eff;
bottom: 0;
}
:deep(.el-tabs__content) {
display: none;
}
}
.custom-tab-label {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>

View File

@ -0,0 +1,703 @@
/**
* 【录像服务器管理】配置文件 — 基于 newcamara 页面模板 v2 架构
*
* ===== 核心设计 =====
* 1. FIELD_DICT — 全局字段预设表,每个字段拥有唯一翻译(label)和完整元数据
* 2. VALUE_MAPS — 值翻译映射表(select options 和 tag 翻译共用)
* 3. TAG_RESOLVERS — 标签颜色解析器(集中管理 tag 颜色逻辑)
* 4. 各标签页通过 key 引用所需字段(scanBoxFieldKeys / tableColumnKeys)
* 5. resolveTabConfig() — 加载时将 key 列表展开为完整配置
*/
import type { Component } from 'vue'
import DetailPanel from './components/DetailPanel.vue'
import LogPanel from './components/LogPanel.vue'
import ServerFormDialog from '../pages/ServerFormDialog.vue'
// ============================================================
// 〇、全局页面配置
// ============================================================
export const PAGE_CONFIG = {
/** 是否显示顶部多标签栏 */
showTabArea: false,
/** 单页模式:不显示标签栏,仅一个标签页内容 */
singlePage: true,
/** 是否启用详情面板(底部分栏 + 显示/隐藏详情按钮),false 时表格占满全高 */
enableDetailPanel: false
}
// ============================================================
// 〇-A、组件注册表 — 所有可复用组件在此注册
// ============================================================
export const COMPONENT_REGISTRY: Record<string, Component> = {
DetailPanel,
LogPanel,
ServerFormDialog
}
// ============================================================
// 〇-B、SCANBOX_GROUPS — ScanBox 分组名称
// ============================================================
export const SCANBOX_GROUPS = {
basic: '基础信息',
status: '状态筛选'
} as const
// ============================================================
// 一、FIELD_DICT — 全局字段预设表(唯一真相来源)
// ============================================================
export interface FieldDefinition {
key: string
label: string
scanBox: {
type: 'text' | 'select' | 'daterange' | 'number'
group?: string
options?: { label: string; value: any }[]
placeholder?: string
operators?: string[]
defaultOperator?: string
} | null
table: {
minWidth?: number
width?: number
fixed?: 'left' | 'right' | boolean
align?: 'left' | 'center' | 'right'
sortable?: boolean
showOverflowTooltip?: boolean
copyAction?: 'copy' | 'copyQr'
copyValue?: (row: any) => any
} | null
slot: {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
} | null
detailLabel?: string
filterParamMap?: Record<string, string>
}
// ============================================================
// VALUE_MAPS — 值翻译映射(select options 和 tag 翻译共用)
// ============================================================
export const VALUE_MAPS: Record<string, Record<string, string>> = {
serverStatus: { '1': '启用', '0': '禁用', '启用': '启用', '禁用': '禁用' }
}
/** 从 VALUE_MAPS 衍生 options(优先取中文值作为 option value) */
export function getOptions(field: string): { label: string; value: string }[] {
const map = VALUE_MAPS[field]
if (!map) return []
const seen = new Set<string>()
const opts: { label: string; value: string }[] = []
const chineseKeys: [string, string][] = []
const otherKeys: [string, string][] = []
for (const [v, l] of Object.entries(map)) {
if (/^[\u4e00-\u9fa5]/.test(v)) {
chineseKeys.push([v, l])
} else {
otherKeys.push([v, l])
}
}
for (const [v, l] of [...chineseKeys, ...otherKeys]) {
if (!seen.has(l)) {
seen.add(l)
opts.push({ label: l, value: v })
}
}
return opts
}
/** 翻译 value → label */
export function translate(field: string, value: any): string {
const map = VALUE_MAPS[field]
if (!map) return String(value ?? '—')
return map[String(value)] ?? String(value ?? '—')
}
/** 格式化时间戳为 YYYY-MM-DD HH:mm:ss */
export function formatTime(value: any): string {
if (!value) return '—'
try {
const d = new Date(value)
if (isNaN(d.getTime())) return String(value)
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
} catch {
return String(value)
}
}
// ============================================================
// TAG_RESOLVERS — 标签颜色解析器
// ============================================================
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
resolveServerStatusTag(v) {
if (v === 1 || v === '1' || v === '启用') return 'success'
return 'info'
}
}
// ============================================================
// 二、FIELD_DICT 实例 — 录像服务器页面字段
// ============================================================
export const FIELD_DICT: Record<string, FieldDefinition> = {
/** 关键词搜索(虚拟字段,仅用于 ScanBox) */
quickWhere: {
key: 'quickWhere',
label: '关键词',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic, placeholder: '服务器名称/IP', operators: ['contains'], defaultOperator: 'contains' },
table: null,
slot: null,
detailLabel: '关键词'
},
id: {
key: 'id',
label: 'ID',
scanBox: null,
table: { width: 80, sortable: true },
slot: null,
detailLabel: 'ID'
},
name: {
key: 'name',
label: '服务器名称',
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic, placeholder: '请输入名称', operators: ['contains'], defaultOperator: 'contains' },
table: { minWidth: 160, showOverflowTooltip: true },
slot: null,
detailLabel: '服务器名称'
},
brand: {
key: 'brand',
label: '品牌',
scanBox: { type: 'select', group: SCANBOX_GROUPS.basic, options: getOptions('brand') },
table: { width: 120, align: 'center' },
slot: { type: 'tag', tagResolver: 'resolveBrandTag', translateField: 'brand' },
detailLabel: '品牌'
},
public_ip: {
key: 'public_ip',
label: '公网IP',
scanBox: null,
table: { width: 150, showOverflowTooltip: true },
slot: null,
detailLabel: '公网IP'
},
internal_ip: {
key: 'internal_ip',
label: '内网IP',
scanBox: null,
table: { width: 150, showOverflowTooltip: true },
slot: null,
detailLabel: '内网IP'
},
port: {
key: 'port',
label: '端口',
scanBox: null,
table: { width: 80, align: 'center' },
slot: null,
detailLabel: '端口'
},
username: {
key: 'username',
label: '用户名',
scanBox: null,
table: { width: 120 },
slot: null,
detailLabel: '用户名'
},
status: {
key: 'status',
label: '状态',
scanBox: { type: 'select', group: SCANBOX_GROUPS.status, options: getOptions('serverStatus') },
table: { width: 90, align: 'center' },
slot: { type: 'tag', tagResolver: 'resolveServerStatusTag', translateField: 'serverStatus' },
detailLabel: '状态',
filterParamMap: { '启用': '1', '禁用': '0' }
},
remark: {
key: 'remark',
label: '备注',
scanBox: null,
table: { minWidth: 160, showOverflowTooltip: true },
slot: null,
detailLabel: '备注'
},
connectivity: {
key: 'connectivity',
label: '连通',
scanBox: null,
table: { width: 110, align: 'center' },
slot: { type: 'default' },
detailLabel: '连通状态'
},
created_at: {
key: 'created_at',
label: '创建时间',
scanBox: null,
table: { minWidth: 170, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '创建时间'
},
updated_at: {
key: 'updated_at',
label: '更新时间',
scanBox: null,
table: { minWidth: 170, sortable: true },
slot: { type: 'text', format: 'datetime' },
detailLabel: '更新时间'
},
/** 操作列(虚拟字段,仅用于表格列渲染) */
operation: {
key: 'operation',
label: '操作',
scanBox: null,
table: { width: 150, fixed: 'right', align: 'center' },
slot: { type: 'operation' }
}
}
// ============================================================
// 三、ColumnSlotConfig — 列单元格渲染配置
// ============================================================
export interface ColumnSlotConfig {
type: 'tag' | 'text' | 'default' | 'operation'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
format?: 'datetime'
}
// ============================================================
// 三-A、OperationButtonConfig — 操作列按钮配置
// ============================================================
export interface OperationButtonConfig {
key: string
label: string
type?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | ''
actionType: 'form' | 'action'
formKey?: string
formTitle?: string
formWidth?: string
paramMap?: Record<string, string>
extraParams?: Record<string, any>
disabledOnField?: string
confirmMessage?: string
confirmTitle?: string
confirmType?: 'warning' | 'danger' | 'info'
confirmButtonText?: string
}
// ============================================================
// 四、DetailFieldConfig / DetailSectionConfig — 明细面板配置
// ============================================================
export interface DetailFieldConfig {
key: string
label?: string
span?: number
renderType?: 'text' | 'tag' | 'pre'
tagType?: string | Record<string, string>
tagResolver?: string
translateField?: string
}
export interface DetailSectionConfig {
title: string
columnCount: number
fields: DetailFieldConfig[]
}
export interface DetailTabConfig {
name: string
label: string
componentKey: string
component?: Component
}
// ============================================================
// 五、TabPageApiConfig — 标签页接口插槽配置
// ============================================================
export type ApiMethod = (...args: any[]) => Promise<any>
export type ApiSource = 'api' | 'list'
export type ComponentApiConfig = { source: 'list' } | ApiMethod
export interface TabPageApiConfig {
/** 列表查询接口 */
list: ApiMethod
/** 明细面板接口(可选,不配则用 row 数据) */
detail?: ComponentApiConfig
/** 操作日志接口(可选) */
log?: ComponentApiConfig
/** 导出接口(可选) */
export?: ApiMethod
/** 导出进度查询接口(可选) */
exportProgress?: ApiMethod
/** ScanBox 下拉选项数据源接口(可选) */
scanBoxOptions?: Record<string, ApiMethod>
/** 工具栏按钮 → API 方法映射(可选) */
toolbar?: Record<string, ApiMethod>
/** 列表响应解析器 */
parseListResponse?: (res: any) => { list: any[]; total: number }
/** 构建列表请求参数 */
buildListParams?: (params: {
pagination: { page: number; pageSize: number }
conditions: Record<string, any>
sort?: { prop: string; order: string }
}) => Record<string, any>
}
// ============================================================
// 六、TabPageRawConfig — 标签页声明配置(仅用 key 引用)
// ============================================================
export interface TabPageRawConfig {
name: string
label: string
scanBoxCacheKey: string
/** ScanBox 需要的字段 key 列表(从 FIELD_DICT 中查找) */
scanBoxFieldKeys: string[]
/** 表格需要的列 key 列表(从 FIELD_DICT 中查找) */
tableColumnKeys: string[]
upperTableDefaults: {
title: string
enableColumnConfig?: boolean
showIndex?: boolean
showSelection?: boolean
emptyText?: string
}
/** 明细面板标签页配置 */
detailTabs?: { name: string; label: string; componentKey: string }[]
/** 明细面板分区配置(字段 key 列表,resolveTabConfig 展开) */
detailSections: {
title: string
columnCount: number
fieldKeys: string[]
}[]
/** 接口配置(有 api 时启用真实接口) */
api?: TabPageApiConfig
/** 操作列按钮配置(需 tableColumnKeys 包含 'operation') */
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 七、TabPageConfig — 展开后的完整配置(给 index.vue 使用)
// ============================================================
export interface TabPageConfig {
name: string
label: string
scanBoxCacheKey: string
scanBoxFields: Record<string, any>[]
upperTable: {
title: string
enableColumnConfig: boolean
showIndex: boolean
showSelection: boolean
emptyText: string
columns: Record<string, any>[]
}
columnSlots: Record<string, ColumnSlotConfig>
detailConfig: DetailSectionConfig[]
detailTabs: DetailTabConfig[]
api?: TabPageApiConfig
operationButtons?: OperationButtonConfig[]
}
// ============================================================
// 八、resolveTabConfig — 加载时将 RawConfig 展开为完整配置
// ============================================================
export function resolveTabConfig(raw: TabPageRawConfig): TabPageConfig {
// 展开 ScanBox 字段
const scanBoxFields: Record<string, any>[] = []
for (const key of raw.scanBoxFieldKeys) {
const def = FIELD_DICT[key]
if (!def || !def.scanBox) continue
scanBoxFields.push({
label: def.label,
value: def.key,
type: def.scanBox.type,
options: def.scanBox.options ? [...def.scanBox.options] : undefined,
group: def.scanBox.group,
placeholder: def.scanBox.placeholder,
operators: def.scanBox.operators,
defaultOperator: def.scanBox.defaultOperator,
required: (def.scanBox as any).required
})
}
// 展开表格列
const columns: Record<string, any>[] = []
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.table) continue
columns.push({
prop: def.key,
label: def.label,
...def.table
})
}
// 展开列插槽
const columnSlots: Record<string, ColumnSlotConfig> = {}
for (const key of raw.tableColumnKeys) {
const def = FIELD_DICT[key]
if (!def || !def.slot) continue
columnSlots[def.key] = { ...def.slot }
}
// 展开明细面板配置
const detailConfig: DetailSectionConfig[] = raw.detailSections.map((sec) => ({
title: sec.title,
columnCount: sec.columnCount,
fields: sec.fieldKeys
.map((key): DetailFieldConfig | null => {
const def = FIELD_DICT[key]
if (!def) return null
return {
key: def.key,
label: def.detailLabel ?? def.label,
translateField: def.slot?.translateField,
tagResolver: def.slot?.tagResolver,
tagType: def.slot?.tagType,
renderType: def.slot?.type === 'tag' ? 'tag' : 'text'
}
})
.filter((f): f is DetailFieldConfig => f !== null)
}))
// 展开明细标签页(解析 componentKey → Component)
const detailTabs: DetailTabConfig[] = raw.detailTabs
? raw.detailTabs.map((tab) => ({
name: tab.name,
label: tab.label,
componentKey: tab.componentKey,
component: COMPONENT_REGISTRY[tab.componentKey]
}))
: [{ name: 'detail', label: '明细', componentKey: 'DetailPanel', component: COMPONENT_REGISTRY['DetailPanel'] }]
return {
name: raw.name,
label: raw.label,
scanBoxCacheKey: raw.scanBoxCacheKey,
scanBoxFields,
upperTable: {
title: raw.upperTableDefaults.title,
enableColumnConfig: raw.upperTableDefaults.enableColumnConfig ?? true,
showIndex: raw.upperTableDefaults.showIndex ?? true,
showSelection: raw.upperTableDefaults.showSelection ?? false,
emptyText: raw.upperTableDefaults.emptyText ?? '暂无录像服务器数据',
columns
},
columnSlots,
detailConfig,
detailTabs,
api: raw.api,
operationButtons: raw.operationButtons
}
}
// ============================================================
// 九、buildWhereConditions — 将 ScanBox 条件转为 API where 参数
// ============================================================
export function buildWhereConditions(rawConditions: Record<string, any>): Record<string, any> {
const where: Record<string, any> = {}
for (const [key, cond] of Object.entries(rawConditions || {})) {
let value: any = undefined
if (cond && typeof cond === 'object' && 'operator' in cond) {
value = (cond as any).value
} else if (cond !== undefined && cond !== null && cond !== '') {
value = Array.isArray(cond) ? cond[0] ?? '' : cond
}
if (value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
continue
}
// quickWhere 特殊处理
if (key === 'quickWhere') {
where.quickWhere = String(value)
continue
}
const def = FIELD_DICT[key]
if (def?.filterParamMap) {
const mapped = def.filterParamMap[String(value)]
if (mapped !== undefined) {
where[key] = mapped
continue
}
}
where[key] = value
}
return where
}
// ============================================================
// 十、工具栏按钮系统
// ============================================================
export interface ToolbarButtonConfig {
key: string
label: string
category: 'common' | 'function' | 'basic'
size?: '' | 'default' | 'small' | 'large'
type?: '' | 'primary' | 'success' | 'warning' | 'info' | 'danger'
plain?: boolean
loadingKey?: string
disabledKey?: string
action: string
dynamicLabelKey?: string
onlyForTabs?: string[]
buttonType?: 'default' | 'dropdown'
dropdownOptions?: Array<{ label: string; action: string; divided?: boolean }>
formKey?: string
}
/** ★ 录像服务器工具栏按钮 */
export const TOOLBAR_BUTTONS: Record<string, ToolbarButtonConfig> = {
// ===== 公共按钮 =====
refresh: {
key: 'refresh',
label: '刷新',
category: 'common',
type: 'primary',
size: 'small',
loadingKey: 'loading',
action: 'loadData'
},
// ===== 功能按钮 =====
addServer: {
key: 'addServer',
label: '新增录像服务器',
category: 'function',
type: 'success',
size: 'small',
action: 'openAddServerDialog',
formKey: 'ServerFormDialog'
},
// ===== 基础操作 =====
columnConfig: {
key: 'columnConfig',
label: '字段设置',
category: 'basic',
size: 'small',
action: 'openColumnConfigPanel'
}
}
/** 按标签页名称获取工具栏按钮列表(自动根据 PAGE_CONFIG 过滤) */
export function getTabToolbarButtons(tabName: string): ToolbarButtonConfig[] {
return Object.values(TOOLBAR_BUTTONS).filter((btn) => {
if (btn.onlyForTabs && !btn.onlyForTabs.includes(tabName)) return false
return true
})
}
// ============================================================
// 十一、批量操作配置(录像服务器暂无需批量操作)
// ============================================================
export interface BatchOperationConfig {
action: string
title: string
confirmText: string
confirmType?: 'warning' | 'error' | 'info' | 'success'
confirmButtonText: string
successText: string
failText: string
apiMethod: (...args: any[]) => Promise<any>
payloadKey?: string
idField?: string | string[]
payloadBuilder?: (rows: Record<string, any>[]) => Record<string, any>
useProgress?: boolean
progressApiMethod?: (...args: any[]) => Promise<any>
}
export const BATCH_OPERATION_CONFIGS: Record<string, BatchOperationConfig> = {}
// ============================================================
// 十二、标签页注册表 — 录像服务器管理
// ============================================================
import { list, create, update, del } from '@/api/camera_server/camera_server'
export const tabPages: TabPageRawConfig[] = [
{
name: 'server',
label: '录像服务器管理',
scanBoxCacheKey: 'video-camera-server',
scanBoxFieldKeys: ['quickWhere', 'name', 'status'],
tableColumnKeys: [
'id', 'name', 'public_ip',
'internal_ip', 'port', 'username', 'status',
'remark', 'connectivity', 'created_at', 'updated_at', 'operation'
],
upperTableDefaults: {
title: '录像服务器列表',
showIndex: true,
showSelection: false,
emptyText: '暂无录像服务器数据,可调整左侧筛选条件'
},
detailTabs: [
{ name: 'detail', label: '明细', componentKey: 'DetailPanel' }
],
detailSections: [
{
title: '基础信息',
columnCount: 3,
fieldKeys: ['id', 'name', 'public_ip', 'internal_ip', 'port', 'username', 'status', 'remark'],
},
{
title: '时间信息',
columnCount: 2,
fieldKeys: ['created_at', 'updated_at']
}
],
api: {
list,
detail: { source: 'list' },
parseListResponse(res) {
return {
list: res?.list ?? [],
total: Number(res?.pagination?.total ?? res?.total ?? 0)
}
},
buildListParams({ pagination, conditions }) {
return {
pagination: { page: pagination.page, pageSize: pagination.pageSize },
where: buildWhereConditions(conditions)
}
},
toolbar: { delete: del, create, update }
},
operationButtons: [
{
key: 'edit',
label: '编辑',
actionType: 'action',
type: 'primary'
},
{
key: 'delete',
label: '删除',
actionType: 'action',
type: 'danger',
confirmTitle: '提示',
confirmMessage: '确认删除该录像服务器吗?删除后关联的摄像头将不可用',
confirmType: 'warning',
confirmButtonText: '确认删除'
},
{
key: 'testConnection',
label: '连通测试',
actionType: 'action',
type: 'warning'
}
]
}
]
// ============================================================
// 十三、向后兼容导出
// ============================================================
export const templateTabs = tabPages.map((t) => ({
name: t.name,
label: t.label,
scanBoxCacheKey: t.scanBoxCacheKey
}))

View File

@ -0,0 +1,159 @@
<!--
DetailPanel — 明细面板(通用)
根据 detailConfig 配置的 sections 渲染 el-descriptions 分区。
支持 text、tag、pre 三种渲染类型。
支持 translateField + tagResolver 集中式翻译。
支持 apiMethod 自动获取详情数据。
-->
<template>
<div class="detail-panel">
<div v-if="!row" class="empty-tip">请从上方列表中选择一项查看明细</div>
<template v-else>
<div v-for="(section, si) in detailConfig" :key="si" class="section">
<div class="section-title">{{ section.title }}</div>
<el-descriptions :column="section.columnCount" border size="small" class="detail-descriptions">
<el-descriptions-item
v-for="(field, fi) in section.fields"
:key="fi"
:label="field.label"
:span="field.span ?? 1"
>
<!-- tag 渲染 -->
<template v-if="field.renderType === 'tag'">
<el-tag size="small" :type="resolveTagType(field, getRowData()?.[field.key])">
{{ resolveDisplayValue(field, getRowData()?.[field.key]) }}
</el-tag>
</template>
<!-- pre 渲染 -->
<template v-else-if="field.renderType === 'pre'">
<pre class="order-list-pre">{{ getRowData()?.[field.key] ?? '—' }}</pre>
</template>
<!-- 默认文本渲染 -->
<template v-else>
{{ resolveDisplayValue(field, getRowData()?.[field.key]) }}
</template>
</el-descriptions-item>
</el-descriptions>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { TAG_RESOLVERS, translate } from '../camaraserver-config'
import type { DetailSectionConfig, DetailFieldConfig } from '../camaraserver-config'
defineOptions({ name: 'DetailPanel' })
const props = defineProps<{
row: Record<string, any> | null
detailConfig: DetailSectionConfig[]
/** 可选的 detail API 方法,传入后自动调用获取完整明细数据 */
apiMethod?: (...args: any[]) => Promise<any>
}>()
/** 通过 API 获取的增强数据(与 row 合并) */
const enrichedData = ref<Record<string, any> | null>(null)
watch(() => props.row, async (newRow) => {
if (newRow && props.apiMethod) {
try {
const res = await props.apiMethod({
id: newRow.id,
code: newRow.code
})
if (res && (res.code === 1 || res.code === 200)) {
enrichedData.value = res.data ?? res
} else {
enrichedData.value = null
}
} catch {
enrichedData.value = null
}
} else {
enrichedData.value = null
}
}, { immediate: true })
/** 合并 row + API 增强数据 */
function getRowData(): Record<string, any> | null {
if (!props.row) return null
if (enrichedData.value) {
return { ...props.row, ...enrichedData.value }
}
return props.row
}
/** 解析显示值:优先使用 translateField 翻译,否则显示原始值 */
function resolveDisplayValue(field: DetailFieldConfig, value: any): string {
if (field.translateField) {
return translate(field.translateField, value)
}
return value ?? '—'
}
/** 解析 tag 颜色 */
function resolveTagType(field: DetailFieldConfig, value: any): string {
if (field.tagResolver) {
const resolver = TAG_RESOLVERS[field.tagResolver]
if (resolver) return resolver(value)
}
if (field.tagType) {
if (typeof field.tagType === 'object') {
return field.tagType[String(value)] ?? 'info'
}
return field.tagType
}
return 'info'
}
</script>
<style lang="scss" scoped>
.detail-panel {
padding: 8px 0;
}
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 40px 0;
}
.section {
margin-bottom: 12px;
&:last-child {
margin-bottom: 0;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: #303133;
margin-bottom: 10px;
padding-left: 8px;
border-left: 3px solid #409eff;
line-height: 1.4;
}
}
.detail-descriptions {
:deep(.el-descriptions__label) {
width: 120px;
background: #fafbfc;
font-weight: 500;
}
}
.order-list-pre {
margin: 0;
font-family: inherit;
font-size: 13px;
line-height: 1.8;
white-space: pre-wrap;
color: #606266;
}
</style>

View File

@ -0,0 +1,227 @@
<!--
LogPanel — 操作日志面板(通用)
支持两种数据来源:
- apiMethod 传入 → 调用真实接口获取日志
- 无 apiMethod → 基于 row 生成模拟日志(开发调试用)
-->
<template>
<div class="log-panel">
<div class="section-title">操作日志</div>
<div v-if="apiLoading" v-loading="true" class="empty-tip">加载中…</div>
<div v-else-if="!logs.length" class="empty-tip">暂无操作日志</div>
<div v-else class="log-timeline">
<div v-for="(log, i) in logs" :key="i" class="log-item">
<div class="log-dot" :class="log.level" />
<div class="log-content">
<div class="log-header">
<span class="log-operator">{{ log.operator }}</span>
<span class="log-action">{{ log.action }}</span>
<el-tag v-if="log.result === '成功'" size="small" type="success">成功</el-tag>
<el-tag v-else-if="log.result === '失败'" size="small" type="danger">失败</el-tag>
<el-tag v-else size="small" type="info">{{ log.result }}</el-tag>
</div>
<div v-if="log.detail" class="log-detail">{{ log.detail }}</div>
<div class="log-time">{{ log.time }}</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
defineOptions({ name: 'LogPanel' })
interface LogItem {
operator: string
action: string
result: string
detail?: string
time: string
level: 'success' | 'info' | 'warning' | 'error'
}
const props = defineProps<{
/** 当前选中行数据(用于生成关联日志) */
row: Record<string, any> | null
/** 可选的日志 API 方法,传入后自动调用获取真实日志 */
apiMethod?: (...args: any[]) => Promise<any>
}>()
/** 通过 API 获取的真实日志列表 */
const apiLogs = ref<LogItem[] | null>(null)
const apiLoading = ref(false)
watch(() => props.row, async (newRow) => {
if (newRow && props.apiMethod) {
apiLoading.value = true
try {
const res = await props.apiMethod({
id: newRow.id,
code: newRow.code,
page: 1,
pageSize: 100
})
if (res && (res.code === 1 || res.code === 200)) {
const list = res.data?.list ?? res.data?.logs ?? res.list ?? res.logs ?? []
apiLogs.value = Array.isArray(list) ? list.map((item: any) => ({
operator: item.operator ?? item.creator ?? '—',
action: item.action ?? item.operation ?? '—',
result: item.result ?? item.status ?? '—',
detail: item.detail ?? item.description ?? '',
time: item.time ?? item.create_time ?? '—',
level: (item.result === '成功' || item.status === 'success') ? 'success'
: (item.result === '失败' || item.status === 'error') ? 'error'
: 'info'
})) : []
} else {
apiLogs.value = []
}
} catch {
apiLogs.value = []
} finally {
apiLoading.value = false
}
} else {
apiLogs.value = null
}
}, { immediate: true })
/** 基于 row 生成模拟日志(无 apiMethod 时使用) */
const mockLogs = computed<LogItem[]>(() => {
if (!props.row) return []
const rowName = props.row.name ?? props.row.code ?? '—'
const now = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
const fmt = (d: Date) =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
return [
{
operator: '系统',
action: `创建了「${rowName}」`,
result: '成功',
time: fmt(new Date(now.getTime() - 3600000 * 3)),
level: 'success'
},
{
operator: props.row.creator ?? '管理员',
action: `更新了「${rowName}」`,
result: '成功',
detail: `修改了状态和相关配置`,
time: fmt(new Date(now.getTime() - 3600000)),
level: 'success'
}
]
})
/** 最终展示的日志:优先使用 API 日志,否则使用 mock 日志 */
const logs = computed<LogItem[]>(() => {
if (apiLogs.value !== null) {
return apiLogs.value
}
return mockLogs.value
})
</script>
<style lang="scss" scoped>
.log-panel {
padding: 8px 0;
}
.empty-tip {
text-align: center;
font-size: 13px;
color: #909399;
padding: 40px 0;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: #303133;
margin-bottom: 12px;
padding-left: 4px;
border-left: 3px solid #409eff;
}
.log-timeline {
padding-left: 8px;
.log-item {
display: flex;
gap: 12px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px dashed #ebeef5;
&:last-child {
border-bottom: none;
margin-bottom: 0;
}
}
.log-dot {
flex-shrink: 0;
width: 8px;
height: 8px;
margin-top: 6px;
border-radius: 50%;
background: #c0c4cc;
&.success {
background: #67c23a;
}
&.warning {
background: #e6a23c;
}
&.error {
background: #f56c6c;
}
&.info {
background: #409eff;
}
}
.log-content {
flex: 1;
min-width: 0;
}
.log-header {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.log-operator {
font-weight: 600;
font-size: 13px;
color: #303133;
}
.log-action {
font-size: 13px;
color: #606266;
}
.log-detail {
margin-top: 4px;
font-size: 12px;
color: #909399;
}
.log-time {
margin-top: 2px;
font-size: 12px;
color: #c0c4cc;
}
}
</style>

View File

@ -0,0 +1,555 @@
<!--
╔══════════════════════════════════════════════════════════════╗
║ 录像服务器管理 — 基于 newcamara 页面模板 v2 架构 ║
╚══════════════════════════════════════════════════════════════╝
-->
<template>
<div class="page-wrapper" :style="{ height: containerHeight }">
<!-- ===== 多标签模式:显示顶部标签栏 ===== -->
<template v-if="PAGE_CONFIG.showTabArea && !PAGE_CONFIG.singlePage">
<div class="tab-section">
<TabArea
:tabs="tabList"
:default-active="activeTabName"
@tab-change="handleTabChange"
/>
</div>
</template>
<!-- ===== 主内容区 ===== -->
<div class="main-container">
<div class="order-sub-container">
<!-- 左侧:ScanBox 筛选面板 -->
<ScanBox
ref="scanBoxRef"
:cache-key="currentScanBoxCacheKey"
width="250px"
:tree-props="{ children: 'children', label: 'label' }"
:auto-submit="false"
:preset-tree="presetTree"
:available-fields="currentScanBoxFields"
@condition-change="handleConditionChange"
@reset="handleConditionReset"
@condition-clear="handleConditionClear"
/>
<!-- 右侧:内容区 -->
<div class="main-content">
<transition name="tab-fade" mode="out-in">
<div :key="activeTabName" class="tab-content-inner">
<!-- 工具栏按钮组 -->
<div class="toolbar">
<div class="toolbar-left">
<OrderToolbarButtonGroup
:buttons="currentToolbarButtons"
:resolve-disabled="resolveButtonDisabled"
:resolve-loading="resolveButtonLoading"
:resolve-label="resolveButtonLabel"
:layout-key="toolbarLayoutKey"
@action="handleToolbarButtonClick"
/>
</div>
</div>
<!-- 表格占满全高 -->
<div class="upper-wrapper upper-wrapper--full">
<UpperTable
ref="upperTableRef"
:title="currentTabConfig?.upperTable.title ?? '列表'"
default-align="center"
:enable-column-config="currentTabConfig?.upperTable.enableColumnConfig ?? true"
:column-config-schema-version="1"
:table-id="`server-table-${activeTabName}`"
:data="listData"
:row-key="'id'"
:columns="currentColumns"
table-size="small"
:pagination="pagination"
:show-index="currentTabConfig?.upperTable.showIndex ?? true"
:show-selection="currentTabConfig?.upperTable.showSelection ?? false"
:loading="loading"
:query-time="queryTime"
@current-change="handleRowClick"
@row-click="handleRowClick"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
@refresh="loadData"
@sort-change="handleSortChange"
@selection-change="handleSelectionChange"
>
<template
v-for="(slotConfig, colProp) in currentColumnSlots"
:key="`columnSlots-${colProp}`"
#[`column-${colProp}`]="{ row }"
>
<!-- 操作列 -->
<template v-if="colProp === 'operation'">
<div class="operation-cell">
<el-button link type="primary" size="small" @click.stop="openServerForm('edit', getRowById(row['id']))">编辑</el-button>
<el-button link type="danger" size="small" @click.stop="handleDeleteServer(getRowById(row['id'])!)">删除</el-button>
</div>
</template>
<!-- 连通列 -->
<template v-else-if="colProp === 'connectivity'">
<el-button
size="small"
type="warning"
plain
:loading="testLoadingMap[row['id']]"
@click.stop="handleTestConnection(row)"
>
连通测试
</el-button>
</template>
<!-- 其他列 -->
<ColumnCellRenderer
v-else
:config="slotConfig"
:value="row[colProp]"
/>
</template>
<template #empty>
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
</template>
</UpperTable>
</div>
</div>
</transition>
</div>
</div>
</div>
<!-- ===== 新增/编辑弹窗 ===== -->
<ServerFormDialog
v-model:visible="serverFormVisible"
:row="serverFormRow"
:mode="serverFormMode"
@success="handleFormSuccess"
/>
</div>
</template>
<script setup lang="ts">
// ============================================================
// ★ 录像服务器管理页面
// ============================================================
defineOptions({ name: 'NewCameraServer' })
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useSettingsStore } from '@/stores/modules/settings'
import ScanBox from '@/components/ScanBox/index.vue'
import UpperTable from '@/components/UpperTable/index.vue'
import TabArea from './components/TabArea.vue'
import ColumnCellRenderer from './components/ColumnCellRenderer.vue'
import ServerFormDialog from './pages/ServerFormDialog.vue'
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
import type { ToolbarButtonConfig as OrderToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
import { del } from '@/api/camera_server/camera_server'
import { testConnection } from '@/api/camera_server/localServerApi'
import {
PAGE_CONFIG,
tabPages,
resolveTabConfig,
getTabToolbarButtons,
type TabPageConfig,
type DetailTabConfig,
type ToolbarButtonConfig,
} from './config/camaraserver-config'
// ============================================================
// 容器高度
// ============================================================
const settingsStore = useSettingsStore()
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
const containerHeight = computed(() =>
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
)
// ============================================================
// 标签页
// ============================================================
const tabList = computed(() =>
tabPages.map((t) => ({ name: t.name, label: t.label }))
)
const activeTabName = ref(tabPages[0]?.name ?? 'server')
const currentTabConfig = computed<TabPageConfig | undefined>(() => {
const raw = tabPages.find((t) => t.name === activeTabName.value)
if (!raw) return undefined
return resolveTabConfig(raw)
})
const currentScanBoxCacheKey = computed(
() => currentTabConfig.value?.scanBoxCacheKey ?? 'server-default'
)
const currentScanBoxFields = computed(
() => currentTabConfig.value?.scanBoxFields ?? []
)
const currentColumns = computed(
() => currentTabConfig.value?.upperTable.columns ?? []
)
const currentColumnSlots = computed(
() => currentTabConfig.value?.columnSlots ?? {}
)
const currentDetailConfig = computed(
() => currentTabConfig.value?.detailConfig ?? []
)
const currentDetailTabs = computed<DetailTabConfig[]>(
() => currentTabConfig.value?.detailTabs ?? []
)
const activeDetailTabComponent = computed(() => {
const tab = currentDetailTabs.value.find(
(t) => t.name === activeDetailTab.value
)
return tab?.component ?? null
})
const currentDetailTabApiMethod = computed(() => {
const cfg = currentTabConfig.value
if (!cfg?.api) return undefined
const tab = currentDetailTabs.value.find((t) => t.name === activeDetailTab.value)
if (!tab) return undefined
let componentCfg: unknown
switch (tab.componentKey) {
case 'DetailPanel': componentCfg = cfg.api.detail; break
case 'LogPanel': componentCfg = cfg.api.log; break
default: return undefined
}
if (typeof componentCfg === 'function') return componentCfg
return undefined
})
// ============================================================
// 工具栏
// ============================================================
const currentToolbarButtons = computed<OrderToolbarButtonConfig[]>(() => {
const btns = getTabToolbarButtons(activeTabName.value)
return btns.map((btn: ToolbarButtonConfig) => ({
key: btn.key, label: btn.label, size: btn.size, type: btn.type,
plain: btn.plain, loadingKey: btn.loadingKey, disabledKey: btn.disabledKey,
action: btn.action, dynamicLabelKey: btn.dynamicLabelKey,
buttonType: btn.buttonType, dropdownOptions: btn.dropdownOptions
}))
})
const buttonDisabledMap = computed<Record<string, boolean>>(() => ({
noSelection: selectedRows.value.length === 0
}))
const buttonLoadingMap = computed<Record<string, boolean>>(() => ({
loading: loading.value
}))
const buttonLabelMap = computed<Record<string, string>>(() => ({}))
const toolbarLayoutKey = computed(() =>
JSON.stringify({ loading: buttonLoadingMap.value, disabled: buttonDisabledMap.value, labels: buttonLabelMap.value })
)
function resolveButtonLoading(loadingKey?: string) { return loadingKey ? Boolean(buttonLoadingMap.value[loadingKey]) : false }
function resolveButtonDisabled(disabledKey?: string) { return disabledKey ? Boolean(buttonDisabledMap.value[disabledKey]) : false }
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
return dynamicLabelKey ? (buttonLabelMap.value[dynamicLabelKey] || defaultLabel) : defaultLabel
}
const toolbarActionMap: Record<string, () => void> = {
loadData: () => { void loadData() },
openColumnConfigPanel: () => { upperTableRef.value?.openColumnConfig?.() },
openAddServerDialog: () => { openServerForm('create') }
}
function handleToolbarButtonClick(action: string) {
const handler = toolbarActionMap[action]
if (handler) { handler(); return }
console.warn('[NewCameraServer] 未处理的工具栏动作:', action)
}
// ============================================================
// ServerFormDialog
// ============================================================
const serverFormVisible = ref(false)
const serverFormMode = ref<'create' | 'edit'>('create')
const serverFormRow = ref<Record<string, any> | null>(null)
function openServerForm(mode: 'create' | 'edit', row?: Record<string, any>) {
serverFormMode.value = mode
serverFormRow.value = row ?? null
serverFormVisible.value = true
}
function getRowById(id: any): Record<string, any> | undefined {
if (id === undefined || id === null) return undefined
return (listData.value as any[]).find((item: any) => item.id === id)
}
function handleFormSuccess() { loadData() }
// ============================================================
// 操作列
// ============================================================
async function handleDeleteServer(row: Record<string, any>) {
if (!row.id) return
const name = row.name || String(row.id)
try {
await ElMessageBox.confirm(`确认删除录像服务器「${name}」吗?删除后关联的摄像头将不可用`, '提示', { type: 'warning' })
} catch { return }
try {
const res: any = await del({ id: row.id })
if (res && [0, 1, 200].includes(res.code)) {
ElMessage.success('删除成功')
if (listData.value.length === 1 && pagination.currentPage > 1) pagination.currentPage -= 1
loadData()
} else {
ElMessage.error(res?.message || '删除失败')
}
} catch { ElMessage.error('删除失败') }
}
// ============================================================
// 连通测试
// ============================================================
const testLoadingMap = ref<Record<number, boolean>>({})
async function handleTestConnection(row: Record<string, any>) {
const id = row.id
if (testLoadingMap.value[id]) return
const internalIp = (row.internal_ip || '').trim()
const publicIp = (row.public_ip || '').trim()
const username = (row.username || '').trim()
let password = (row.password || '').trim()
if (!internalIp && !publicIp) { ElMessage.warning('该服务器未配置内网IP与公网IP,无法测试连通'); return }
if (!username) { ElMessage.warning('缺少用户名,无法测试连通'); return }
if (!password) {
try {
const { value } = await ElMessageBox.prompt('请输入录像服务器密码', '连通测试', {
inputType: 'password', confirmButtonText: '开始测试', cancelButtonText: '取消', inputPlaceholder: '请输入密码'
})
if (!value?.trim()) { ElMessage.warning('密码不能为空'); return }
password = value.trim()
} catch { return }
}
testLoadingMap.value = { ...testLoadingMap.value, [id]: true }
const localBaseUrl = 'http://localhost:17311'
const tryIp = async (label: string, ip: string, port?: number): Promise<boolean> => {
try {
await testConnection(localBaseUrl, { ip, port: port || row.port, user: username, pass: password })
ElMessage.success(`「${row.name || row.id}」连通成功(${label}:${ip})`)
return true
} catch (e: any) { console.warn(`[连通测试] ${label} ${ip} 失败:`, e?.message || e); return false }
}
if (internalIp) {
const ok = await tryIp('内网IP', internalIp, row.internal_port)
if (ok) { testLoadingMap.value = { ...testLoadingMap.value, [id]: false }; return }
}
if (publicIp && publicIp !== internalIp) {
const ok = await tryIp('公网IP', publicIp, row.public_port)
if (ok) { testLoadingMap.value = { ...testLoadingMap.value, [id]: false }; return }
}
testLoadingMap.value = { ...testLoadingMap.value, [id]: false }
const triedIps = [internalIp, publicIp].filter(Boolean).join('、')
ElMessage.error(`「${row.name || row.id}」连通失败(已尝试:${triedIps})`)
}
// ============================================================
// 数据加载
// ============================================================
const listData = ref<Record<string, any>[]>([])
const loading = ref(false)
const queryTime = ref(0)
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
const currentSort = reactive({ prop: '', order: '' })
const loadData = async () => {
const cfg = currentTabConfig.value
if (!cfg) return
loading.value = true
const startTime = performance.now()
try {
if (cfg.api) {
const conditions = scanBoxRef.value?.getConditions?.() || {}
const params = cfg.api.buildListParams
? cfg.api.buildListParams({
pagination: { page: pagination.currentPage, pageSize: pagination.pageSize },
conditions,
sort: currentSort.prop ? { prop: currentSort.prop, order: currentSort.order } : undefined
})
: { pagination: { page: pagination.currentPage, pageSize: pagination.pageSize }, where: conditions }
const res = await cfg.api.list(params)
if (res && [0, 1, 200].includes(res.code)) {
const parsed = cfg.api.parseListResponse
? cfg.api.parseListResponse(res)
: { list: res.data?.list ?? res.list ?? [], total: res.data?.pagination?.total ?? res.total ?? 0 }
listData.value = parsed.list
pagination.total = parsed.total
} else { throw new Error(res?.message || '接口返回异常') }
} else { listData.value = []; pagination.total = 0 }
} catch (e: any) {
console.error('[NewCameraServer] 加载列表失败:', e)
ElMessage.error(e?.message || '获取列表数据失败')
listData.value = []; pagination.total = 0
} finally {
loading.value = false
queryTime.value = Math.round(performance.now() - startTime)
}
}
// ============================================================
// ScanBox / UpperTable 事件
// ============================================================
const scanBoxRef = ref<any>(null)
const presetTree = ref<any[]>([])
const upperTableRef = ref<any>(null)
const selectedRows = ref<Record<string, any>[]>([])
const handleConditionChange = () => { pagination.currentPage = 1; loadData() }
const handleConditionReset = () => { pagination.currentPage = 1; loadData() }
const handleConditionClear = () => { pagination.currentPage = 1; loadData() }
const handleSortChange = ({ prop, order }: any) => { currentSort.prop = prop; currentSort.order = order; pagination.currentPage = 1; loadData() }
const handlePageChange = (page: number) => { pagination.currentPage = page; loadData() }
const handlePageSizeChange = (size: number) => { pagination.pageSize = size; pagination.currentPage = 1; loadData() }
const handleSelectionChange = (rows: Record<string, any>[]) => { selectedRows.value = rows }
// ============================================================
// 明细面板(未启用)
// ============================================================
const selectedRow = ref<Record<string, any> | null>(null)
const selectedDetail = ref<Record<string, any> | null>(null)
const activeDetailTab = ref('detail')
const handleRowClick = async (row: Record<string, any>) => {
if (!PAGE_CONFIG.enableDetailPanel) return
const cfg = currentTabConfig.value
if (!cfg) return
selectedRow.value = row
const detailCfg = cfg.api?.detail
if (typeof detailCfg === 'function') {
try {
const detailRes = await detailCfg({ id: row.id, code: row.code })
if (detailRes && [0, 1, 200].includes(detailRes.code)) { selectedDetail.value = detailRes.data ?? detailRes }
else { selectedDetail.value = { ...row } }
} catch { selectedDetail.value = { ...row } }
} else { selectedDetail.value = { ...row } }
}
const handleTabChange = (tabName: string) => {
if (activeTabName.value === tabName) return
activeTabName.value = tabName
pagination.currentPage = 1; currentSort.prop = ''; currentSort.order = ''
selectedRow.value = null; selectedDetail.value = null; selectedRows.value = []
activeDetailTab.value = 'detail'
loadData()
}
onMounted(() => { loadData() })
</script>
<style lang="scss" scoped>
@use "../../order/orderManagement/styles/order-sub.scss";
.page-wrapper {
position: relative;
width: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.tab-section {
flex-shrink: 0;
background: #fff;
border: 1px solid #e8eef7;
border-bottom: none;
border-radius: 6px 6px 0 0;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
overflow: hidden;
}
.main-container {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
background: #fff;
border: 1px solid #e8eef7;
border-radius: 0 0 6px 6px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
overflow: hidden;
:deep(.scan-box-container .scan-tabs) {
flex-shrink: 0;
border-bottom: 1px solid #e8eef7;
background: #f8fbff;
}
:deep(.scan-box-container .scan-tabs .el-tabs__header) {
margin: 0;
padding: 4px 8px 0;
}
:deep(.scan-box-container .scan-tabs .el-tabs__nav-wrap::after) {
display: none;
}
:deep(.scan-box-container .scan-tabs .el-tabs__active-bar) {
display: none;
}
:deep(.scan-box-container .scan-tabs .el-tabs__item) {
height: 38px;
line-height: 38px;
font-size: 14px;
font-weight: 500;
padding: 0 20px;
color: #606266;
border: 1px solid transparent;
border-bottom: none;
border-radius: 6px 6px 0 0;
transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
margin-right: 4px;
}
:deep(.scan-box-container .scan-tabs .el-tabs__item:hover) {
color: #409eff;
background-color: rgba(64, 158, 255, 0.05);
}
:deep(.scan-box-container .scan-tabs .el-tabs__item.is-active) {
color: #409eff;
font-weight: 600;
background: #ffffff;
border-color: #e8eef7;
border-bottom-color: #fff;
}
}
.tab-content-inner {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.tab-fade-enter-active,
.tab-fade-leave-active {
transition: opacity 0.2s ease;
opacity: 1;
}
.tab-fade-enter-from,
.tab-fade-leave-to {
opacity: 0;
}
.empty-tip {
font-size: 13px;
color: #909399;
}
.operation-cell {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
flex-wrap: wrap;
}
</style>

View File

@ -0,0 +1,107 @@
<!--
ExampleFormDialog — 示例表单弹窗(模板)
功能按钮对应的表单组件放在 pages/ 目录下。
使用方式:
1. 在 camaraserver-config.ts 的 COMPONENT_REGISTRY 中注册
2. 在 camaraserver-config.ts 的 TOOLBAR_BUTTONS 中添加功能按钮,设置 formKey
3. index.vue 中通过工具栏按钮触发打开
-->
<template>
<el-dialog
:model-value="visible"
title="示例操作"
width="500px"
align-center
destroy-on-close
:close-on-click-modal="false"
@closed="handleClosed"
>
<div class="form-body">
<el-form ref="formRef" :model="form" label-width="100px" size="small">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" placeholder="请输入名称" />
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="form.description"
type="textarea"
:rows="3"
placeholder="请输入描述"
/>
</el-form-item>
</el-form>
</div>
<template #footer>
<el-button size="small" @click="handleClosed">取消</el-button>
<el-button size="small" type="primary" :loading="submitting" @click="handleSubmit">
确认
</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
defineOptions({ name: 'ExampleFormDialog' })
const props = defineProps<{
visible: boolean
/** 从行数据注入的初始值(由 OperationCellRenderer 的 paramMap 传递) */
id?: string | number
code?: string
name?: string
}>()
const emit = defineEmits<{
(e: 'update:visible', v: boolean): void
(e: 'success'): void
}>()
const formRef = ref<any>(null)
const submitting = ref(false)
const form = reactive({
name: '',
description: ''
})
// 重置表单
watch(() => props.visible, (v) => {
if (v) {
form.name = props.name ?? ''
form.description = ''
}
})
function handleClosed() {
emit('update:visible', false)
}
async function handleSubmit() {
submitting.value = true
try {
// ★ 替换为真实 API 调用
// const res = await yourApi.submit({ id: props.id, ...form })
await new Promise((r) => setTimeout(r, 500))
ElMessage.success('操作成功')
emit('update:visible', false)
emit('success')
} catch (e: any) {
ElMessage.error(e?.message || '操作失败')
} finally {
submitting.value = false
}
}
</script>
<style lang="scss" scoped>
.form-body {
padding: 12px 0;
}
</style>

View File

@ -0,0 +1,221 @@
<!--
ServerFormDialog — 录像服务器新增/编辑表单弹窗
-->
<template>
<el-dialog
:model-value="visible"
:title="isEdit ? '编辑录像服务器' : '新增录像服务器'"
width="560px"
align-center
destroy-on-close
:close-on-click-modal="false"
append-to-body
@closed="handleClosed"
>
<div class="form-body">
<el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small">
<el-form-item label="服务器名称" prop="name">
<el-input v-model="form.name" placeholder="请输入服务器名称" maxlength="100" show-word-limit />
</el-form-item>
<el-form-item label="公网IP" prop="public_ip">
<div class="ip-port-row">
<el-input v-model="form.public_ip" placeholder="请输入公网IP" maxlength="50" class="ip-input" />
<el-input-number v-model="form.public_port" :min="1" :max="65535" placeholder="端口" class="port-input" controls-position="right" />
</div>
</el-form-item>
<el-form-item label="内网IP" prop="internal_ip">
<div class="ip-port-row">
<el-input v-model="form.internal_ip" placeholder="请输入内网IP" maxlength="50" class="ip-input" />
<el-input-number v-model="form.internal_port" :min="1" :max="65535" placeholder="端口" class="port-input" controls-position="right" />
</div>
</el-form-item>
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" placeholder="请输入用户名" maxlength="50" />
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" type="password" placeholder="请输入密码" maxlength="50" show-password />
</el-form-item>
<el-form-item label="状态" prop="status">
<el-switch
v-model="form.status"
:active-value="1"
:inactive-value="0"
active-text="启用"
inactive-text="禁用"
/>
</el-form-item>
<el-form-item label="备注" prop="remark">
<el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="200" show-word-limit />
</el-form-item>
</el-form>
</div>
<template #footer>
<el-button @click="handleClosed">取消</el-button>
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { create, update } from '@/api/camera_server/camera_server'
defineOptions({ name: 'ServerFormDialog' })
const props = defineProps<{
visible: boolean
mode?: 'create' | 'edit'
row?: Record<string, any> | null
}>()
const emit = defineEmits<{
(e: 'update:visible', val: boolean): void
(e: 'success'): void
}>()
const isEdit = computed(() => props.mode === 'edit')
const formRef = ref<FormInstance>()
const saving = ref(false)
const form = reactive({
id: undefined as number | undefined,
name: '',
public_ip: '',
public_port: undefined as number | undefined,
internal_ip: '',
internal_port: undefined as number | undefined,
username: '',
password: '',
status: 1 as number,
remark: ''
})
const rules: FormRules = {
name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }]
}
function isSuccess(res: any) {
return res && [0, 1, 200].includes(res.code)
}
function resetForm() {
form.id = undefined
form.name = ''
form.public_ip = ''
form.public_port = undefined
form.internal_ip = ''
form.internal_port = undefined
form.username = ''
form.password = ''
form.status = 1
form.remark = ''
formRef.value?.clearValidate()
}
watch(() => props.visible, (val) => {
if (val) {
if (props.mode === 'edit' && props.row) {
const r = props.row
form.id = r.id
form.name = r.name || ''
form.public_ip = r.public_ip || ''
form.public_port = r.public_port
form.internal_ip = r.internal_ip || ''
form.internal_port = r.internal_port
form.username = r.username || ''
form.password = ''
form.status = r.status ?? 1
form.remark = r.remark || ''
formRef.value?.clearValidate()
} else {
resetForm()
}
}
})
function handleClosed() {
emit('update:visible', false)
}
async function submitForm() {
if (!formRef.value || saving.value) return
const valid = await formRef.value.validate().catch(() => false)
if (!valid) return
saving.value = true
try {
if (isEdit.value) {
if (!form.id) {
ElMessage.error('缺少服务器ID')
return
}
const res: any = await update({
id: form.id,
name: form.name.trim() || undefined,
public_ip: form.public_ip.trim() || undefined,
public_port: form.public_port,
internal_ip: form.internal_ip.trim() || undefined,
internal_port: form.internal_port,
username: form.username.trim() || undefined,
password: form.password || undefined,
status: form.status,
remark: form.remark.trim() || undefined
})
if (!isSuccess(res)) {
ElMessage.error(res?.message || '更新失败')
return
}
ElMessage.success('更新成功')
} else {
const res: any = await create({
name: form.name.trim(),
public_ip: form.public_ip.trim() || undefined,
public_port: form.public_port,
internal_ip: form.internal_ip.trim() || undefined,
internal_port: form.internal_port,
username: form.username.trim() || undefined,
password: form.password || undefined,
status: form.status,
remark: form.remark.trim() || undefined
})
if (!isSuccess(res)) {
ElMessage.error(res?.message || '新增失败')
return
}
ElMessage.success('新增成功')
}
emit('update:visible', false)
emit('success')
} catch {
ElMessage.error('保存失败')
} finally {
saving.value = false
}
}
</script>
<style lang="scss" scoped>
.form-body {
max-height: 60vh;
overflow-y: auto;
padding-right: 8px;
}
.ip-port-row {
display: flex;
gap: 8px;
width: 100%;
}
.ip-input {
flex: 1;
min-width: 0;
}
.port-input {
width: 130px;
flex-shrink: 0;
}
</style>