1
This commit is contained in:
parent
1db19bafdd
commit
b370cfd706
3
.gitignore
vendored
3
.gitignore
vendored
@ -47,3 +47,6 @@ __screenshots__/
|
||||
|
||||
# 本地离线二维码工具(独立小工具,不入库)
|
||||
/batchQrcode/
|
||||
|
||||
# 死代码扫描产物(本地产物,不入库)
|
||||
/unused-report.json
|
||||
|
||||
144
docs/项目瘦身-未引用页面清单.md
Normal file
144
docs/项目瘦身-未引用页面清单.md
Normal file
@ -0,0 +1,144 @@
|
||||
# 项目瘦身 · 未引用页面清单
|
||||
|
||||
> 扫描时间:2026-09-22 · 扫描脚本:`scripts/find-unused-modules.mjs` · 原始数据:`unused-report.json`
|
||||
|
||||
## 一、判定方法(为什么不能只看 map.ts)
|
||||
|
||||
`src/router/index.ts` 里有一段兜底逻辑:
|
||||
|
||||
```ts
|
||||
const viewModules = import.meta.glob('@/views/**/*.vue')
|
||||
```
|
||||
|
||||
这意味着 **`src/views` 下的每一个 `.vue` 都会被 Vite 收集进构建图**(各自一个懒加载 chunk),
|
||||
运行时后端菜单只要 `component` 字段能拼出路径,就能命中最上面的 glob。
|
||||
|
||||
所以"未被引用"必须区分两种情况:
|
||||
|
||||
| 口径 | 含义 | 能否直接删 |
|
||||
|---|---|---|
|
||||
| **静态不可达** | 从 `src/main.ts` 出发,经 `import / import() / require()` 到不了 | 需先确认后端菜单没有指向它 |
|
||||
| **完全死代码** | 既静态不可达,也不被任何 glob 模式匹配 | 可以直接删 |
|
||||
|
||||
本次扫描结果(`src` 下共 582 个模块):
|
||||
|
||||
- 静态可达:**480**
|
||||
- 仅被 glob 兜底匹配:**80**(全部在 `src/views` 下)
|
||||
- 完全死代码:**22**
|
||||
- 待处理合计:**102 个文件**(约 974 KB 源码)
|
||||
|
||||
## 二、第一批:整目录废弃(同功能新版已在 map.ts 中生效)
|
||||
|
||||
这批是"做了新版没删旧版"的复制目录,**判断依据充分,可优先处理**。
|
||||
证据:废弃目录的文件修改时间统一停在 `2026-08-11`(模板生成日),而现行目录仍在持续更新。
|
||||
|
||||
| 废弃目录/文件 | 文件数 | 现行替代(map.ts 指向) | 备注 |
|
||||
|---|---|---|---|
|
||||
| `src/views/order/waveOrder2/` | 9 | `order/waveOrder/`(`order/waveOrder`、`wave/index`) | `waveOrder` 最近更新 09-21,`waveOrder2` 停在 08-11 |
|
||||
| `src/views/data/newpackingflow/` | 11 | `data/packingflow/`(`data/packingflow`) | `packingflow` 更新 09-16 |
|
||||
| `src/views/material/packageMaterial2/` | 8 | `material/packageMaterial/`(`material/packageMaterial/index`) | |
|
||||
| `src/views/system/setting/encoding2/` | 8 | `system/setting/encoding/`(`system/setting/encoding/index`) | |
|
||||
| `src/views/mode/` | 8 | — | 页面模板脚手架(`【页面模板 v2】`) |
|
||||
| `src/views/video/camera/` | 3 | `video/newcamara/`(`video/camera/index` 已重指向) | |
|
||||
| `src/views/video/cameraServer/` | 1 | `video/newcamaraserver/`(`video/cameraServer/index` 已重指向) | |
|
||||
| `src/views/store/shipperSigning/` | 1 | `Externalwarehouse/shipperSigning/` | 同名页面两份 |
|
||||
| `src/views/system/setting/workbench/` | 2 | `system/setting/workbench2/` | map.ts 的 key 仍是 `system/setting/workbench/index` |
|
||||
| `src/views/system/setting/basicManagement/`(旧 `index.vue`、`ApiOpenInterface.vue`) | 2 | `system/setting/basicManagement/newview/` | 旧路径已在 map.ts 里重指向 newview |
|
||||
| `src/views/warehouse/` 旧三件套 `zone.vue`、`SpaceList.vue`、`SpaceForm.vue` | 3 | `ZoneManagement.vue` / `RackSpaceManagement.vue` | `warehouse/index.vue` 已不再 import 这三个 |
|
||||
|
||||
## 三、第二批:页面内孤立组件(页面本身在用,组件已废弃)
|
||||
|
||||
| 文件 | 体积 | 说明 |
|
||||
|---|---|---|
|
||||
| `order/orderManagement/component/detail.vue` | 0.3 KB | 只 import 了 `OrderDetailPanel.vue` |
|
||||
| `order/orderManagement/component/orderdetail.vue` | 2.5 KB | |
|
||||
| `order/orderManagement/component/OrderDetailPanel.vue` | 2.1 KB | 仅被上面的 `detail.vue` 引用(链式死) |
|
||||
| `order/orderManagement/component/ManualOutboundPanel.vue` | 6.0 KB | |
|
||||
| `order/orderManagement/component/OrderReviewDialog.vue` | 2.7 KB | |
|
||||
| `order/waveOrder/component/WaveBatchPrintPreviewDialog.vue` | 10.8 KB | |
|
||||
| `express/returnUnpack/components/ExportDialog.vue` | 9.7 KB | 已被通用导出弹窗替代 |
|
||||
| `express/returnUnpack/components/VideoListDialog.vue` | 4.3 KB | 该目录下 `VideoPlayerDialog.vue` 仍在使用 |
|
||||
| `express/waybill/components/TabArea.vue` | 2.6 KB | |
|
||||
| `express/waybill/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `store/stores/component/ExportDialog.vue` | 7.6 KB | |
|
||||
| `storage/entry/component/QuickInboundForm.vue` | 9.2 KB | `storage/entry/index.vue` 未引用 |
|
||||
| `storage/inventory/component/InventoryStockPickerDialog.vue` | 14.7 KB | |
|
||||
| `afterSale/detail/HandleDialog.vue` | 4.6 KB | 处理逻辑已内联在 `detail/index.vue` |
|
||||
| `system/setting/printStation/components/Printer.vue` | 3.2 KB | 该页只 import `info.vue` / `add.vue` |
|
||||
| `system/setting/printStation/components/expressCompany.vue` | 2.4 KB | 同上 |
|
||||
| `system/setting/printStation/components/printComputer.vue` | 2.7 KB | 同上 |
|
||||
| `system/setting/printcomputer/config/components/DetailPanel.vue` | 4.6 KB | |
|
||||
| `system/setting/printcomputer/config/components/LogPanel.vue` | 5.9 KB | |
|
||||
| `system/setting/printcomputer/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `system/setting/workbench2/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `system/setting/basicManagement/newview/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `system/setting/basicManagement/newview/pages/ExportReportDialog.vue` | 6.7 KB | |
|
||||
| `video/newcamaraserver/components/OperationCellRenderer.vue` | 5.1 KB | 该页未 import(`TabArea` / `ColumnCellRenderer` 在用) |
|
||||
| `video/newcamara/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `afterSale/typelist/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `storage/generalreport/pages/ExampleFormDialog.vue` | 2.7 KB | 模板残留 |
|
||||
| `views/account/index.vue` | 0.1 KB | 空壳(注意:map.ts 的 `account/index` 指向 `system/setting/account/index.vue`) |
|
||||
| `views/permission/index.vue` | 0.1 KB | 空壳 |
|
||||
|
||||
## 四、第三批:完全死代码(非页面,共 22 个 / 324 KB)
|
||||
|
||||
### Vue2 迁移残留(8 个 / 43.4 KB)
|
||||
- `src/utils/index.js`(2.7 KB)— vue-element-admin 工具集
|
||||
- `src/utils/warehouseData.js`(20.4 KB)
|
||||
- `src/utils/zhijian.js`(6.3 KB)+ `src/utils/zhijian.ts`(6.9 KB)— 双份同名,均无引用
|
||||
- `src/icons/index.js`(0.3 KB)— SVG 图标已改走 `vite-plugin-svg-icons`
|
||||
- `src/layout/AppMain.vue`(0.1 KB)— 实际使用的是 `src/layout/component/AppMain.vue`
|
||||
- `src/stores/counter.ts`(0.3 KB)— Pinia 示例
|
||||
- `src/stores/modules/localCameraServer.ts`(4.9 KB)
|
||||
|
||||
### 三维可视化遗留(5 个 / 约 114 KB)
|
||||
- `src/utils/threeScene.js`(36.2 KB)
|
||||
- `src/utils/threeUtils.js`(10.8 KB)
|
||||
- `src/utils/overlookControls.js`(11.3 KB)
|
||||
- `src/utils/CanvasRenderer.js`(26.6 KB)+ `src/utils/CanvasRenderer.ts`(28.8 KB)— 双份
|
||||
|
||||
### 模板配置残留
|
||||
- `src/views/mode/config/template-config.ts`(24.7 KB)
|
||||
- `src/views/material/packageMaterial2/config/template-config.ts`(24.6 KB)
|
||||
- `src/views/system/setting/encoding2/config/template-config.ts`(24.6 KB)
|
||||
- `src/views/data/newpackingflow/config/packingflow-config.ts`(26.0 KB)
|
||||
- `src/views/order/waveOrder2/config/waveorder-config.ts`(54.7 KB)
|
||||
- `src/views/system/setting/workbench/workbench-config.ts`(4.6 KB)
|
||||
|
||||
### API 模块(3 个 / 9.3 KB,建议单独确认后再删)
|
||||
- `src/api/order.packing/packing.ts`(7.6 KB)
|
||||
- `src/api/config/config.ts`(1.3 KB)
|
||||
- `src/api/printer.station/printerstation.ts`(0.4 KB)
|
||||
|
||||
> 对照:`src/api/waybill.warehouse/index.ts` 一开始被误判为死代码,实际 `express/waybill` 在用,**不要删**。
|
||||
> (原因是该目录名自带点号,脚本早期用 `path.extname` 判断扩展名导致解析失败,已修复。)
|
||||
|
||||
## 五、删除前必须做的核对
|
||||
|
||||
因为 `import.meta.glob` 兜底的存在,**静态不可达 ≠ 可以删**。删之前请确认后端菜单
|
||||
`component` 字段没有指向待删路径:
|
||||
|
||||
1. 导出菜单表里所有 `component` 字段值(形如 `order/waveOrder`、`system/setting/role/index`)
|
||||
2. 与上表路径求交集,**有交集的一律保留**
|
||||
3. 更省事的做法:直接在浏览器里按后台配的菜单逐个点一遍,确认页面不是待删文件
|
||||
4. 特别注意 map.ts 里那些**值相同、key 不同的兼容项**,例如:
|
||||
- `system/setting/basicManagement` / `system/setting/basicManagement/index` / `basicManagement` → 全部指向 `newview`
|
||||
- `video/camera/index` → `newcamara`;`video/cameraServer/index` → `newcamaraserver`
|
||||
- `system/setting/workbench/index` → `workbench2`
|
||||
- `stock/combo_stock` 相关 key 已注释掉(`combo_stock` 现为 `stockManagement` 内的标签页)
|
||||
|
||||
## 六、如何复跑
|
||||
|
||||
```bash
|
||||
node scripts/find-unused-modules.mjs # 完整报告
|
||||
node scripts/find-unused-modules.mjs --views-only # 只看页面
|
||||
```
|
||||
|
||||
脚本会打印分组清单 + 目录级汇总,并把机器可读结果写到 `unused-report.json`。
|
||||
|
||||
判定口径:
|
||||
- 静态可达:从 `src/main.ts` 经 `import` / `import()` / `require()` / SCSS `@use` / `@import` 可达
|
||||
- glob 兜底:被 `import.meta.glob(...)` 模式匹配
|
||||
- 死代码:以上都不属于
|
||||
|
||||
> 已知盲区:仅覆盖 `src` 目录;不解析 `component` 字段的字符串拼接路径(本项目已确认无此类写法)。
|
||||
318
scripts/find-unused-modules.mjs
Normal file
318
scripts/find-unused-modules.mjs
Normal file
@ -0,0 +1,318 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 死代码扫描:从入口出发对 src 做模块依赖图可达性分析。
|
||||
*
|
||||
* 判定口径
|
||||
* - 静态可达:从入口(src/main.ts)经 import / export-from / import() / require() 能到达
|
||||
* - glob 兜底:被 import.meta.glob(...) 模式匹配到(构建期收集,运行时按后端菜单动态取用)
|
||||
* - 死代码 :以上两类都不属于
|
||||
*
|
||||
* 用法:node scripts/find-unused-modules.mjs [项目根目录] [--views-only]
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const viewsOnly = args.includes('--views-only')
|
||||
const rootArg = args.find((a) => !a.startsWith('--'))
|
||||
const ROOT = rootArg ? path.resolve(rootArg) : process.cwd()
|
||||
const SRC = path.join(ROOT, 'src')
|
||||
const ENTRIES = [path.join(SRC, 'main.ts')]
|
||||
|
||||
const WALK_EXT = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.scss', '.css'])
|
||||
const RESOLVE_EXT = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.json', '.scss', '.css', '.svg']
|
||||
const INDEX_EXT = ['.ts', '.js', '.vue']
|
||||
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'dist-ssr', '.vite'])
|
||||
|
||||
/* ---------- 文件遍历 ---------- */
|
||||
function walk(dir, out = []) {
|
||||
let entries
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true })
|
||||
} catch {
|
||||
return out
|
||||
}
|
||||
for (const e of entries) {
|
||||
const full = path.join(dir, e.name)
|
||||
if (e.isDirectory()) {
|
||||
if (SKIP_DIRS.has(e.name)) continue
|
||||
walk(full, out)
|
||||
} else {
|
||||
const ext = path.extname(e.name)
|
||||
if (WALK_EXT.has(ext) || e.name.endsWith('.d.ts')) out.push(full)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/* ---------- 注释剥离(保留字符串字面量,避免 https:// 被误删) ---------- */
|
||||
function stripComments(code) {
|
||||
let out = ''
|
||||
let i = 0
|
||||
const n = code.length
|
||||
while (i < n) {
|
||||
const c = code[i]
|
||||
const next = code[i + 1]
|
||||
if (c === '/' && next === '/') {
|
||||
while (i < n && code[i] !== '\n') i++
|
||||
continue
|
||||
}
|
||||
if (c === '/' && next === '*') {
|
||||
i += 2
|
||||
while (i < n && !(code[i] === '*' && code[i + 1] === '/')) i++
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (c === '"' || c === "'" || c === '`') {
|
||||
const q = c
|
||||
out += c
|
||||
i++
|
||||
while (i < n) {
|
||||
if (code[i] === '\\') {
|
||||
out += code[i] + code[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
out += code[i]
|
||||
if (code[i] === q) {
|
||||
i++
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
continue
|
||||
}
|
||||
out += c
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const SPEC_RES = [
|
||||
/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g, // 动态 import
|
||||
/\bfrom\s*['"]([^'"]+)['"]/g, // import ... from / export ... from
|
||||
/\bimport\s+['"]([^'"]+)['"]/g, // 副作用 import
|
||||
/\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
|
||||
/new\s+URL\s*\(\s*['"]([^'"]+)['"]/g,
|
||||
/@use\s+['"]([^'"]+)['"]/g, // SCSS
|
||||
/@forward\s+['"]([^'"]+)['"]/g,
|
||||
]
|
||||
const GLOB_RE = /import\.meta\.glob(?:Eager)?\s*\(\s*['"]([^'"]+)['"]/g
|
||||
|
||||
function scanFile(file) {
|
||||
const raw = fs.readFileSync(file, 'utf8')
|
||||
const code = stripComments(raw)
|
||||
const specs = new Set()
|
||||
for (const re of SPEC_RES) {
|
||||
re.lastIndex = 0
|
||||
let m
|
||||
while ((m = re.exec(code))) specs.add(m[1])
|
||||
}
|
||||
const globs = []
|
||||
GLOB_RE.lastIndex = 0
|
||||
let g
|
||||
while ((g = GLOB_RE.exec(code))) globs.push(g[1])
|
||||
return { specs: [...specs], globs }
|
||||
}
|
||||
|
||||
/* ---------- 说明符解析 ---------- */
|
||||
function resolveSpec(spec, fromFile) {
|
||||
if (!spec || typeof spec !== 'string') return null
|
||||
let base = null
|
||||
const s = spec.split('?')[0].split('#')[0]
|
||||
if (s.startsWith('@/')) base = path.join(SRC, s.slice(2))
|
||||
else if (s.startsWith('~@/')) base = path.join(SRC, s.slice(3))
|
||||
else if (s.startsWith('./') || s.startsWith('../')) base = path.resolve(path.dirname(fromFile), s)
|
||||
else return null
|
||||
|
||||
const candidates = [base]
|
||||
for (const ext of RESOLVE_EXT) candidates.push(base + ext)
|
||||
// 注意:目录名可能自带点号(api/order.packing、api/waybill.warehouse),
|
||||
// 不能用 path.extname 判断,必须比对已知扩展名白名单
|
||||
const hasKnownExt = RESOLVE_EXT.includes(path.extname(base).toLowerCase())
|
||||
if (!hasKnownExt) for (const ext of INDEX_EXT) candidates.push(path.join(base, 'index' + ext))
|
||||
for (const c of candidates) {
|
||||
try {
|
||||
if (fs.statSync(c).isFile()) return path.normalize(c)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/* ---------- glob 模式 → 正则 ---------- */
|
||||
function globToRegExp(pattern) {
|
||||
let p = pattern
|
||||
// 统一成相对项目根的路径(@/ 与 / 都指向 src)
|
||||
if (p.startsWith('@/')) p = 'src/' + p.slice(2)
|
||||
else if (p.startsWith('~@/')) p = 'src/' + p.slice(3)
|
||||
p = p.replace(/^\//, '')
|
||||
let re = ''
|
||||
for (let i = 0; i < p.length; i++) {
|
||||
const c = p[i]
|
||||
if (c === '*' && p[i + 1] === '*') {
|
||||
re += '[\\s\\S]*'
|
||||
i++
|
||||
if (p[i + 1] === '/') i++
|
||||
continue
|
||||
}
|
||||
if (c === '*') {
|
||||
re += '[^/]*'
|
||||
continue
|
||||
}
|
||||
re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
}
|
||||
return new RegExp('^' + re + '$')
|
||||
}
|
||||
|
||||
/* ---------- 主流程 ---------- */
|
||||
const allFiles = walk(SRC)
|
||||
const rel = (f) => path.relative(ROOT, f).replace(/\\/g, '/')
|
||||
|
||||
const reachable = new Set()
|
||||
const globOnly = new Set()
|
||||
const queue = []
|
||||
const unresolvedSpecs = []
|
||||
|
||||
for (const f of ENTRIES) {
|
||||
if (!fs.existsSync(f)) {
|
||||
console.error(`入口不存在: ${f}`)
|
||||
process.exit(1)
|
||||
}
|
||||
reachable.add(path.normalize(f))
|
||||
queue.push(path.normalize(f))
|
||||
}
|
||||
|
||||
const globMatchers = []
|
||||
const fileCache = new Map()
|
||||
|
||||
while (queue.length) {
|
||||
const file = queue.pop()
|
||||
let scanned = fileCache.get(file)
|
||||
if (!scanned) {
|
||||
scanned = scanFile(file)
|
||||
fileCache.set(file, scanned)
|
||||
}
|
||||
for (const spec of scanned.specs) {
|
||||
const resolved = resolveSpec(spec, file)
|
||||
if (!resolved) {
|
||||
// 只抱怨“本应能解析”的路径(@/ 与相对路径)
|
||||
if (spec.startsWith('@/') || spec.startsWith('~/') || spec.startsWith('~@/')) {
|
||||
unresolvedSpecs.push(`${rel(file)} -> ${spec}`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (!reachable.has(resolved)) {
|
||||
reachable.add(resolved)
|
||||
if (WALK_EXT.has(path.extname(resolved).toLowerCase())) queue.push(resolved)
|
||||
}
|
||||
}
|
||||
for (const pattern of scanned.globs) {
|
||||
globMatchers.push({ from: file, pattern, re: globToRegExp(pattern) })
|
||||
}
|
||||
}
|
||||
|
||||
for (const f of allFiles) {
|
||||
if (reachable.has(path.normalize(f))) continue
|
||||
if (f.endsWith('.d.ts')) continue
|
||||
const r = rel(f)
|
||||
if (globMatchers.some((g) => g.re.test(r))) globOnly.add(path.normalize(f))
|
||||
}
|
||||
|
||||
/* ---------- 输出 ---------- */
|
||||
const sizeOf = (f) => {
|
||||
try {
|
||||
return fs.statSync(f).size
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
const kb = (n) => (n / 1024).toFixed(1) + ' KB'
|
||||
const norm = (f) => path.normalize(f)
|
||||
|
||||
const dead = allFiles.filter((f) => !reachable.has(norm(f)) && !globOnly.has(norm(f)) && !f.endsWith('.d.ts'))
|
||||
const deadViews = dead.filter((f) => rel(f).startsWith('src/views/') && f.endsWith('.vue'))
|
||||
const deadOther = dead.filter((f) => !(rel(f).startsWith('src/views/') && f.endsWith('.vue')))
|
||||
|
||||
function groupByDir(files, depth = 3) {
|
||||
const map = new Map()
|
||||
for (const f of files) {
|
||||
const r = rel(f)
|
||||
const seg = r.split('/').slice(0, depth).join('/')
|
||||
if (!map.has(seg)) map.set(seg, [])
|
||||
map.get(seg).push(f)
|
||||
}
|
||||
return [...map.entries()].sort((a, b) => b[1].length - a[1].length)
|
||||
}
|
||||
|
||||
console.log('='.repeat(72))
|
||||
console.log(`扫描根目录:${ROOT}`)
|
||||
console.log(`src 下模块总数:${allFiles.length} 静态可达:${reachable.size} 仅 glob 兜底:${globOnly.size} 死代码:${dead.length}`)
|
||||
console.log('='.repeat(72))
|
||||
|
||||
if (deadViews.length) {
|
||||
console.log(`\n## 未被引用的页面 (.vue):${deadViews.length} 个,合计 ${kb(deadViews.reduce((s, f) => s + sizeOf(f), 0))}\n`)
|
||||
for (const [dir, files] of groupByDir(deadViews)) {
|
||||
console.log(`● ${dir} (${files.length} 个, ${kb(files.reduce((s, f) => s + sizeOf(f), 0))})`)
|
||||
for (const f of files.sort()) console.log(` ${rel(f).replace('src/views/', '')} ${kb(sizeOf(f))}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (globOnly.size) {
|
||||
const gv = [...globOnly].filter((f) => f.endsWith('.vue'))
|
||||
console.log(`\n## 仅被 import.meta.glob 兜底匹配的页面:${gv.length} 个(无法静态判定,需核对后端菜单 component 字段)\n`)
|
||||
for (const [dir, files] of groupByDir(gv)) console.log(` ${dir} (${files.length} 个)`)
|
||||
}
|
||||
|
||||
if (!viewsOnly) {
|
||||
console.log(`\n## 未被引用的非页面文件:${deadOther.length} 个,合计 ${kb(deadOther.reduce((s, f) => s + sizeOf(f), 0))}\n`)
|
||||
for (const [dir, files] of groupByDir(deadOther)) {
|
||||
console.log(`● ${dir} (${files.length} 个, ${kb(files.reduce((s, f) => s + sizeOf(f), 0))})`)
|
||||
for (const f of files.sort()) console.log(` ${rel(f).replace('src/', '')} ${kb(sizeOf(f))}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (unresolvedSpecs.length) {
|
||||
const uniq = [...new Set(unresolvedSpecs)]
|
||||
console.log(`\n## 无法解析的 @/ 引用:${uniq.length} 条(疑似路径写错或文件已删)\n`)
|
||||
for (const u of uniq.slice(0, 100)) console.log(' ' + u)
|
||||
}
|
||||
|
||||
/* 机器可读输出 */
|
||||
const aggregate = (files) => {
|
||||
const m = {}
|
||||
for (const f of files) {
|
||||
const seg = rel(f).split('/').slice(0, 4).join('/')
|
||||
if (!m[seg]) m[seg] = { count: 0, bytes: 0 }
|
||||
m[seg].count += 1
|
||||
m[seg].bytes += sizeOf(f)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
console.log('\n## 目录级汇总(按死代码文件数降序,便于分批删除)\n')
|
||||
for (const [dir, v] of Object.entries(aggregate([...dead, ...globOnly])).sort((a, b) => b[1].count - a[1].count)) {
|
||||
console.log(` ${dir} ${v.count} 个 / ${kb(v.bytes)}`)
|
||||
}
|
||||
|
||||
const outFile = path.join(ROOT, 'unused-report.json')
|
||||
fs.writeFileSync(
|
||||
outFile,
|
||||
JSON.stringify(
|
||||
{
|
||||
scannedAt: new Date().toISOString(),
|
||||
totals: { all: allFiles.length, reachable: reachable.size, globOnly: globOnly.size, dead: dead.length },
|
||||
deadViews: deadViews.map(rel),
|
||||
deadOthers: deadOther.map(rel),
|
||||
globOnlyViews: [...globOnly].filter((f) => f.endsWith('.vue')).map(rel),
|
||||
globOnlyOthers: [...globOnly].filter((f) => !f.endsWith('.vue')).map(rel),
|
||||
aggregate: aggregate([...dead, ...globOnly]),
|
||||
unresolvedSpecs: [...new Set(unresolvedSpecs)],
|
||||
},
|
||||
null,
|
||||
2
|
||||
),
|
||||
'utf8'
|
||||
)
|
||||
console.log(`\n完整结果已写入 ${rel(outFile)}`)
|
||||
@ -29,7 +29,48 @@ export interface InboxV2Pagination {
|
||||
total: number
|
||||
}
|
||||
|
||||
function call<T = unknown>(method: string, data?: Record<string, unknown>): Promise<InboxV2Response<T>> {
|
||||
/**
|
||||
* method → 响应业务数据类型映射。
|
||||
*
|
||||
* 调用处直接写 method 字面量(如 `call('inbox.v2.type.list', data)`),
|
||||
* 泛型由该字面量从本映射自动推断,因此调用处**不再写显式泛型实参**;
|
||||
* 这样既保留类型安全,也让接口清单脚本能静态识别 method 与文件的归属关系。
|
||||
*/
|
||||
interface InboxV2MethodMap {
|
||||
'inbox.v2.type.list': InboxV2TypeListData
|
||||
'inbox.v2.type.create': { id: number; message: string }
|
||||
'inbox.v2.type.update': { message: string }
|
||||
'inbox.v2.type.delete': { message: string }
|
||||
'inbox.v2.subType.list': InboxV2SubTypeListData
|
||||
'inbox.v2.subType.create': { id: number; message: string }
|
||||
'inbox.v2.subType.update': { message: string }
|
||||
'inbox.v2.subType.delete': { message: string }
|
||||
'inbox.v2.keyword.list': InboxV2KeywordListData
|
||||
'inbox.v2.keyword.create': { id: number; message: string }
|
||||
'inbox.v2.keyword.update': { message: string }
|
||||
'inbox.v2.keyword.delete': { message: string }
|
||||
'inbox.v2.numberRule.list': { list: InboxV2NumberRuleItem[] }
|
||||
'inbox.v2.function.list': { list: InboxV2FunctionItem[] }
|
||||
'inbox.v2.function.update': { message: string }
|
||||
'inbox.v2.reply.merged': InboxV2ReplyMergedData
|
||||
'inbox.v2.reply.list': InboxV2ReplyListData
|
||||
'inbox.v2.reply.save': InboxV2ReplySaveResult
|
||||
'inbox.v2.reply.restore': { message: string }
|
||||
'inbox.v2.reply.create': { id: number; message: string }
|
||||
'inbox.v2.reply.update': { message: string }
|
||||
'inbox.v2.reply.delete': { message: string }
|
||||
'inbox.v2.relation.function.list': { list: InboxV2SubTypeFunctionItem[] }
|
||||
'inbox.v2.relation.function.set': { message: string }
|
||||
'inbox.v2.relation.rule.list': { list: InboxV2SubTypeRuleItem[] }
|
||||
'inbox.v2.relation.rule.set': { message: string }
|
||||
'inbox.v2.relation.group.list': { list: InboxV2SubTypeGroupItem[] }
|
||||
'inbox.v2.relation.group.set': { message: string }
|
||||
}
|
||||
|
||||
function call<M extends keyof InboxV2MethodMap>(
|
||||
method: M,
|
||||
data?: Record<string, unknown>
|
||||
): Promise<InboxV2Response<InboxV2MethodMap[M]>> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
@ -41,7 +82,7 @@ function call<T = unknown>(method: string, data?: Record<string, unknown>): Prom
|
||||
data: data ?? {},
|
||||
// 自定义标记:request 内部据此走 /system 网关(非 axios 标准字段)
|
||||
isSystemApi: true,
|
||||
} as AxiosRequestConfig) as unknown as Promise<InboxV2Response<T>>
|
||||
} as AxiosRequestConfig) as unknown as Promise<InboxV2Response<InboxV2MethodMap[M]>>
|
||||
}
|
||||
|
||||
/**
|
||||
@ -84,7 +125,7 @@ export interface InboxV2TypeListData {
|
||||
|
||||
/** 类型列表(系统级 + 本仓库自定义,分页) */
|
||||
export function inboxV2TypeList(data: InboxV2TypeListParams = {}) {
|
||||
return call<InboxV2TypeListData>('inbox.v2.type.list', data as Record<string, unknown>)
|
||||
return call('inbox.v2.type.list', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2TypeCreateParams {
|
||||
@ -97,7 +138,7 @@ export interface InboxV2TypeCreateParams {
|
||||
|
||||
/** 创建仓库自定义类型 */
|
||||
export function inboxV2TypeCreate(data: InboxV2TypeCreateParams) {
|
||||
return call<{ id: number; message: string }>('inbox.v2.type.create', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.type.create', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2TypeUpdateParams {
|
||||
@ -109,12 +150,12 @@ export interface InboxV2TypeUpdateParams {
|
||||
|
||||
/** 更新仓库自定义类型(系统预设拒绝修改) */
|
||||
export function inboxV2TypeUpdate(data: InboxV2TypeUpdateParams) {
|
||||
return call<{ message: string }>('inbox.v2.type.update', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.type.update', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/** 删除仓库自定义类型(有子类型引用时拒绝) */
|
||||
export function inboxV2TypeDelete(id: number) {
|
||||
return call<{ message: string }>('inbox.v2.type.delete', { id })
|
||||
return call('inbox.v2.type.delete', { id })
|
||||
}
|
||||
|
||||
// ─────────────────────────── 子类型 ───────────────────────────
|
||||
@ -149,7 +190,7 @@ export interface InboxV2SubTypeListData {
|
||||
|
||||
/** 子类型列表(系统级 + 本仓库自定义,分页) */
|
||||
export function inboxV2SubTypeList(data: InboxV2SubTypeListParams = {}) {
|
||||
return call<InboxV2SubTypeListData>('inbox.v2.subType.list', data as Record<string, unknown>)
|
||||
return call('inbox.v2.subType.list', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2SubTypeCreateParams {
|
||||
@ -164,7 +205,7 @@ export interface InboxV2SubTypeCreateParams {
|
||||
|
||||
/** 创建仓库自定义子类型 */
|
||||
export function inboxV2SubTypeCreate(data: InboxV2SubTypeCreateParams) {
|
||||
return call<{ id: number; message: string }>('inbox.v2.subType.create', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.subType.create', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2SubTypeUpdateParams {
|
||||
@ -176,12 +217,12 @@ export interface InboxV2SubTypeUpdateParams {
|
||||
|
||||
/** 更新仓库自定义子类型(系统预设拒绝修改) */
|
||||
export function inboxV2SubTypeUpdate(data: InboxV2SubTypeUpdateParams) {
|
||||
return call<{ message: string }>('inbox.v2.subType.update', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.subType.update', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/** 删除仓库自定义子类型(有关联引用时拒绝) */
|
||||
export function inboxV2SubTypeDelete(id: number) {
|
||||
return call<{ message: string }>('inbox.v2.subType.delete', { id })
|
||||
return call('inbox.v2.subType.delete', { id })
|
||||
}
|
||||
|
||||
// ─────────────────────────── 关键词 ───────────────────────────
|
||||
@ -213,7 +254,7 @@ export interface InboxV2KeywordListData {
|
||||
|
||||
/** 关键词列表 */
|
||||
export function inboxV2KeywordList(data: InboxV2KeywordListParams = {}) {
|
||||
return call<InboxV2KeywordListData>('inbox.v2.keyword.list', data as Record<string, unknown>)
|
||||
return call('inbox.v2.keyword.list', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2KeywordCreateParams {
|
||||
@ -225,7 +266,7 @@ export interface InboxV2KeywordCreateParams {
|
||||
|
||||
/** 创建仓库自定义关键词 */
|
||||
export function inboxV2KeywordCreate(data: InboxV2KeywordCreateParams) {
|
||||
return call<{ id: number; message: string }>('inbox.v2.keyword.create', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.keyword.create', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2KeywordUpdateParams {
|
||||
@ -238,12 +279,12 @@ export interface InboxV2KeywordUpdateParams {
|
||||
|
||||
/** 更新仓库自定义关键词(系统预设拒绝修改) */
|
||||
export function inboxV2KeywordUpdate(data: InboxV2KeywordUpdateParams) {
|
||||
return call<{ message: string }>('inbox.v2.keyword.update', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.keyword.update', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/** 删除仓库自定义关键词 */
|
||||
export function inboxV2KeywordDelete(id: number) {
|
||||
return call<{ message: string }>('inbox.v2.keyword.delete', { id })
|
||||
return call('inbox.v2.keyword.delete', { id })
|
||||
}
|
||||
|
||||
// ─────────────────────────── 取号规则(全局只读) ───────────────────────────
|
||||
@ -262,7 +303,7 @@ export interface InboxV2NumberRuleItem {
|
||||
|
||||
/** 取号规则列表(只读,供关联配置选择) */
|
||||
export function inboxV2NumberRuleList() {
|
||||
return call<{ list: InboxV2NumberRuleItem[] }>('inbox.v2.numberRule.list')
|
||||
return call('inbox.v2.numberRule.list')
|
||||
}
|
||||
|
||||
// ─────────────────────────── 处理函数 ───────────────────────────
|
||||
@ -286,7 +327,7 @@ export interface InboxV2FunctionListParams {
|
||||
|
||||
/** 处理函数列表 */
|
||||
export function inboxV2FunctionList(data: InboxV2FunctionListParams = {}) {
|
||||
return call<{ list: InboxV2FunctionItem[] }>('inbox.v2.function.list', data as Record<string, unknown>)
|
||||
return call('inbox.v2.function.list', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2FunctionUpdateParams {
|
||||
@ -302,7 +343,7 @@ export interface InboxV2FunctionUpdateParams {
|
||||
* 本方法仅保留后端接口映射以备他用,页面侧不再调用。
|
||||
*/
|
||||
export function inboxV2FunctionUpdate(data: InboxV2FunctionUpdateParams) {
|
||||
return call<{ message: string }>('inbox.v2.function.update', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.function.update', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
// ─────────────────────────── 回复配置 ───────────────────────────
|
||||
@ -376,7 +417,7 @@ export interface InboxV2ReplyMergedData {
|
||||
* 返回结构为 `{ merged, total }`,不分页。
|
||||
*/
|
||||
export function inboxV2ReplyMerged(data: InboxV2ReplyMergedParams = {}) {
|
||||
return call<InboxV2ReplyMergedData>('inbox.v2.reply.merged', data as Record<string, unknown>)
|
||||
return call('inbox.v2.reply.merged', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -384,7 +425,7 @@ export function inboxV2ReplyMerged(data: InboxV2ReplyMergedParams = {}) {
|
||||
* @deprecated 页面展示用 {@link inboxV2ReplyMerged}(合并后的生效配置);本接口保留供排查原始行使用。
|
||||
*/
|
||||
export function inboxV2ReplyList(data: InboxV2ReplyListParams = {}) {
|
||||
return call<InboxV2ReplyListData>('inbox.v2.reply.list', data as Record<string, unknown>)
|
||||
return call('inbox.v2.reply.list', data as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -413,7 +454,7 @@ export interface InboxV2ReplySaveResult {
|
||||
|
||||
/** 保存仓库级回复配置(upsert,推荐接口;未传字段保持原值) */
|
||||
export function inboxV2ReplySave(data: InboxV2ReplySaveParams) {
|
||||
return call<InboxV2ReplySaveResult>('inbox.v2.reply.save', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.reply.save', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -421,7 +462,7 @@ export function inboxV2ReplySave(data: InboxV2ReplySaveParams) {
|
||||
* 无仓库级配置时同样返回成功(message 为「…已是系统级配置」)。
|
||||
*/
|
||||
export function inboxV2ReplyRestore(subTypeId: number) {
|
||||
return call<{ message: string }>('inbox.v2.reply.restore', { subTypeId })
|
||||
return call('inbox.v2.reply.restore', { subTypeId })
|
||||
}
|
||||
|
||||
/** @deprecated 见 {@link InboxV2ReplySaveParams} */
|
||||
@ -442,7 +483,7 @@ export interface InboxV2ReplyCreateParams {
|
||||
* @deprecated 后端保留的兼容接口,页面统一改用 {@link inboxV2ReplySave}(upsert)。
|
||||
*/
|
||||
export function inboxV2ReplyCreate(data: InboxV2ReplyCreateParams) {
|
||||
return call<{ id: number; message: string }>('inbox.v2.reply.create', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.reply.create', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
export interface InboxV2ReplyUpdateParams {
|
||||
@ -459,7 +500,7 @@ export interface InboxV2ReplyUpdateParams {
|
||||
* @deprecated 后端保留的兼容接口,页面统一改用 {@link inboxV2ReplySave}(upsert)。
|
||||
*/
|
||||
export function inboxV2ReplyUpdate(data: InboxV2ReplyUpdateParams) {
|
||||
return call<{ message: string }>('inbox.v2.reply.update', data as unknown as Record<string, unknown>)
|
||||
return call('inbox.v2.reply.update', data as unknown as Record<string, unknown>)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -467,7 +508,7 @@ export function inboxV2ReplyUpdate(data: InboxV2ReplyUpdateParams) {
|
||||
* @deprecated 后端保留的兼容接口,页面统一改用 {@link inboxV2ReplyRestore}(幂等还原)。
|
||||
*/
|
||||
export function inboxV2ReplyDelete(id: number) {
|
||||
return call<{ message: string }>('inbox.v2.reply.delete', { id })
|
||||
return call('inbox.v2.reply.delete', { id })
|
||||
}
|
||||
|
||||
// ─────────────────────────── 子类型关联关系 ───────────────────────────
|
||||
@ -504,7 +545,7 @@ export interface InboxV2SubTypeGroupItem {
|
||||
|
||||
/** 子类型已关联的处理函数列表 */
|
||||
export function inboxV2RelationFunctionList(subTypeId: number) {
|
||||
return call<{ list: InboxV2SubTypeFunctionItem[] }>('inbox.v2.relation.function.list', { subTypeId })
|
||||
return call('inbox.v2.relation.function.list', { subTypeId })
|
||||
}
|
||||
|
||||
/** 全量替换子类型的处理函数关联 */
|
||||
@ -512,7 +553,7 @@ export function inboxV2RelationFunctionSet(
|
||||
subTypeId: number,
|
||||
items: Array<{ functionId: number; sortOrder?: number }>
|
||||
) {
|
||||
return call<{ message: string }>('inbox.v2.relation.function.set', {
|
||||
return call('inbox.v2.relation.function.set', {
|
||||
subTypeId,
|
||||
items,
|
||||
} as unknown as Record<string, unknown>)
|
||||
@ -520,7 +561,7 @@ export function inboxV2RelationFunctionSet(
|
||||
|
||||
/** 子类型已关联的取号规则列表 */
|
||||
export function inboxV2RelationRuleList(subTypeId: number) {
|
||||
return call<{ list: InboxV2SubTypeRuleItem[] }>('inbox.v2.relation.rule.list', { subTypeId })
|
||||
return call('inbox.v2.relation.rule.list', { subTypeId })
|
||||
}
|
||||
|
||||
/** 全量替换子类型的取号规则关联 */
|
||||
@ -528,7 +569,7 @@ export function inboxV2RelationRuleSet(
|
||||
subTypeId: number,
|
||||
items: Array<{ ruleId: number; sortOrder?: number }>
|
||||
) {
|
||||
return call<{ message: string }>('inbox.v2.relation.rule.set', {
|
||||
return call('inbox.v2.relation.rule.set', {
|
||||
subTypeId,
|
||||
items,
|
||||
} as unknown as Record<string, unknown>)
|
||||
@ -536,7 +577,7 @@ export function inboxV2RelationRuleSet(
|
||||
|
||||
/** 子类型已关联的群白名单列表 */
|
||||
export function inboxV2RelationGroupList(subTypeId: number) {
|
||||
return call<{ list: InboxV2SubTypeGroupItem[] }>('inbox.v2.relation.group.list', { subTypeId })
|
||||
return call('inbox.v2.relation.group.list', { subTypeId })
|
||||
}
|
||||
|
||||
/** 替换子类型的群白名单(系统预设行后端自动保留) */
|
||||
@ -544,7 +585,7 @@ export function inboxV2RelationGroupSet(
|
||||
subTypeId: number,
|
||||
items: Array<{ groupType: string; subGroup: string; sortOrder?: number }>
|
||||
) {
|
||||
return call<{ message: string }>('inbox.v2.relation.group.set', {
|
||||
return call('inbox.v2.relation.group.set', {
|
||||
subTypeId,
|
||||
items,
|
||||
} as unknown as Record<string, unknown>)
|
||||
@ -624,6 +624,45 @@ export function orderPendingOrderParseAddress(
|
||||
} as any);
|
||||
}
|
||||
|
||||
/** order.pendingOrder.parseAddressLocal 入参(可选;两者均不传时后端用内置示例地址数据) */
|
||||
export type PendingOrderParseAddressLocalParams = {
|
||||
/** 单条地址解析;也支持传字符串数组批量解析(与 addresses 二选一) */
|
||||
address?: string | string[];
|
||||
/** 批量地址解析(单次最多 50 条) */
|
||||
addresses?: string[];
|
||||
};
|
||||
|
||||
/** order.pendingOrder.parseAddressLocal 响应(结构同 parseAddress,额外含 data.source) */
|
||||
export type PendingOrderParseAddressLocalResponse = PendingOrderParseAddressResponse & {
|
||||
data?: PendingOrderParseAddressData & {
|
||||
list?: PendingOrderParseAddressItem[];
|
||||
/** 未传 address/addresses 时为 sample,表示结果来自内置示例地址数据 */
|
||||
source?: string;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* order.pendingOrder.parseAddressLocal:本地地址解析(不调 AI,内置省市区字典遍历识别)。
|
||||
* 与 parseAddress 解析逻辑等价;区别是可完全无参调用(返回内置示例地址数据的识别结果)。
|
||||
*/
|
||||
export function orderPendingOrderParseAddressLocal(
|
||||
data: PendingOrderParseAddressLocalParams = {},
|
||||
): Promise<PendingOrderParseAddressLocalResponse> {
|
||||
return request({
|
||||
url: "/system",
|
||||
method: "post",
|
||||
params: {
|
||||
method: "order.pendingOrder.parseAddressLocal",
|
||||
v,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
data,
|
||||
isSystemApi: true,
|
||||
// 批量解析(最多 50 条)耗时较长,超时时间延长至 10 分钟
|
||||
timeout: 600000,
|
||||
} as any);
|
||||
}
|
||||
|
||||
/** order.pendingOrder.batchIntercept:批量提交订单拦截请求 */
|
||||
export function orderPendingOrderBatchIntercept(data: PendingOrderBatchInterceptParams): Promise<any> {
|
||||
return request({
|
||||
@ -800,6 +839,7 @@ export type OrderPendingOrderApi = {
|
||||
importOrdersFromExcel: typeof orderPendingOrderImportOrdersFromExcel;
|
||||
downloadCreateTemplate: typeof orderPendingOrderDownloadCreateTemplate;
|
||||
parseAddress: typeof orderPendingOrderParseAddress;
|
||||
parseAddressLocal: typeof orderPendingOrderParseAddressLocal;
|
||||
batchIntercept: typeof orderPendingOrderBatchIntercept;
|
||||
batchInterceptTaskProgress: typeof orderPendingOrderBatchInterceptTaskProgress;
|
||||
batchUnintercept: typeof orderPendingOrderBatchUnintercept;
|
||||
@ -835,6 +875,7 @@ export const orderPendingOrder: OrderPendingOrderApi = {
|
||||
importOrdersFromExcel: orderPendingOrderImportOrdersFromExcel,
|
||||
downloadCreateTemplate: orderPendingOrderDownloadCreateTemplate,
|
||||
parseAddress: orderPendingOrderParseAddress,
|
||||
parseAddressLocal: orderPendingOrderParseAddressLocal,
|
||||
batchIntercept: orderPendingOrderBatchIntercept,
|
||||
batchInterceptTaskProgress: orderPendingOrderBatchInterceptTaskProgress,
|
||||
batchUnintercept: orderPendingOrderBatchUnintercept,
|
||||
|
||||
@ -1266,100 +1266,7 @@ export function orderWaveBatchRemoveOrders(
|
||||
} as any)
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintScan 入参:扫描波次内任一订单的面单号确认打印 */
|
||||
export type WaveConfirmPrintScanParams = {
|
||||
/** 面单号/运单号(必填,用于定位订单及所属波次) */
|
||||
waybill_no: string
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintScan 业务 data */
|
||||
export type WaveConfirmPrintScanResponse = {
|
||||
/** 扫描的面单号 */
|
||||
waybill_no?: string
|
||||
/** 面单号匹配到的订单ID */
|
||||
matched_order_id?: number
|
||||
/** 波次ID */
|
||||
wave_id?: number
|
||||
/** 波次编码 */
|
||||
wave_no?: string
|
||||
/** 波次下总订单数 */
|
||||
total_order_count?: number
|
||||
/** 波次下拦截订单数(跳过确认) */
|
||||
intercepted_order_count?: number
|
||||
/** 已确认打印订单数(confirm_print_status='fin') */
|
||||
confirmed_order_count?: number
|
||||
/** 本次新增确认订单数(仅 status=confirmed 时返回) */
|
||||
newly_confirmed_order_count?: number
|
||||
/** confirmed=本次完成确认 / already_confirmed=已全部确认 */
|
||||
status: 'confirmed' | 'already_confirmed' | string
|
||||
}
|
||||
|
||||
/**
|
||||
* order.wave.confirmPrintScan:扫描波次内任一订单的面单号,将该波次下全部已打印(print_status='fin')
|
||||
* 且非拦截订单批量置 confirm_print_status='fin',并写订单操作日志(ORDER_CONFIRM_PRINT)。
|
||||
* - 拦截订单跳过(不确认、不阻断);
|
||||
* - 波次下存在未打印订单(print_status != 'fin')时阻断:返回 unprinted_order_count;
|
||||
* - 全部已确认时重复扫描返回 status=already_confirmed。
|
||||
*/
|
||||
export function orderWaveConfirmPrintScan(
|
||||
data: WaveConfirmPrintScanParams
|
||||
): Promise<WaveConfirmPrintScanResponse & { code?: number; message?: string; data?: Partial<WaveConfirmPrintScanResponse>; unprinted_order_count?: number }> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'order.wave.confirmPrintScan',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintUnclaimedWaveCount 入参:长轮询上次数量 */
|
||||
export type WaveConfirmPrintUnclaimedWaveCountParams = {
|
||||
/**
|
||||
* 上次返回的数量(长轮询游标):
|
||||
* 不传 → 立即返回当前值(status=current);传入且与当前值不同 → 立即返回新值(status=changed);
|
||||
* 相同 → 挂起等待,最长 60 秒(期间变化立即返回 changed,超时重查后返回 timeout)。
|
||||
*/
|
||||
last_count?: number
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintUnclaimedWaveCount 业务 data */
|
||||
export type WaveConfirmPrintUnclaimedWaveCountResponse = {
|
||||
/** 已确认打印(confirm_print_status='fin')但未领单(claim_status != 'fin')订单涉及的波次数量 */
|
||||
count: number
|
||||
/** current=直接返回当前值 / changed=数量已变化 / timeout=等待超时后返回当前值 */
|
||||
status: 'current' | 'changed' | 'timeout' | string
|
||||
}
|
||||
|
||||
/**
|
||||
* order.wave.confirmPrintUnclaimedWaveCount:查询「已确认打印但未领单」波次数量,支持长轮询。
|
||||
* 注意:长轮询最长挂起 60 秒,超过请求层默认 10 秒超时,故单独放开 timeout。
|
||||
*/
|
||||
export function orderWaveConfirmPrintUnclaimedWaveCount(
|
||||
data: WaveConfirmPrintUnclaimedWaveCountParams = {}
|
||||
): Promise<WaveConfirmPrintUnclaimedWaveCountResponse & { code?: number; message?: string; data?: Partial<WaveConfirmPrintUnclaimedWaveCountResponse> }> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'order.wave.confirmPrintUnclaimedWaveCount',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true,
|
||||
// 长轮询最长等待 60 秒(请求层默认 10 秒会提前中断)
|
||||
timeout: 70000
|
||||
} as any)
|
||||
}
|
||||
|
||||
export const orderWave = {
|
||||
confirmPrintScan: orderWaveConfirmPrintScan,
|
||||
confirmPrintUnclaimedWaveCount: orderWaveConfirmPrintUnclaimedWaveCount,
|
||||
wavePickTaskList: orderWaveWavePickTaskList,
|
||||
wavePickTaskCancel: orderWaveWavePickTaskCancel,
|
||||
wavePickTaskCancelSelf: orderWaveWavePickTaskCancelSelf,
|
||||
|
||||
@ -407,8 +407,106 @@ export function orderModulePendingOrderBatchMarkPrinted(
|
||||
} as any)
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────
|
||||
// 以下两个接口的 method 前缀为 order.wave.*,但文档归属 folder = order,
|
||||
// 故实现放在 src/api/order/(与 order.wave.batchList 同一归属规则)。
|
||||
// ────────────────────────────────────────────────────────────
|
||||
|
||||
/** order.wave.confirmPrintScan 入参:扫描波次内任一订单的面单号确认打印 */
|
||||
export type WaveConfirmPrintScanParams = {
|
||||
/** 面单号/运单号(必填,用于定位订单及所属波次) */
|
||||
waybill_no: string
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintScan 业务 data */
|
||||
export type WaveConfirmPrintScanResponse = {
|
||||
/** 扫描的面单号 */
|
||||
waybill_no?: string
|
||||
/** 面单号匹配到的订单ID */
|
||||
matched_order_id?: number
|
||||
/** 波次ID */
|
||||
wave_id?: number
|
||||
/** 波次编码 */
|
||||
wave_no?: string
|
||||
/** 波次下总订单数 */
|
||||
total_order_count?: number
|
||||
/** 波次下拦截订单数(跳过确认) */
|
||||
intercepted_order_count?: number
|
||||
/** 已确认打印订单数(confirm_print_status='fin') */
|
||||
confirmed_order_count?: number
|
||||
/** 本次新增确认订单数(仅 status=confirmed 时返回) */
|
||||
newly_confirmed_order_count?: number
|
||||
/** confirmed=本次完成确认 / already_confirmed=已全部确认 */
|
||||
status: 'confirmed' | 'already_confirmed' | string
|
||||
}
|
||||
|
||||
/**
|
||||
* order.wave.confirmPrintScan:扫描波次内任一订单的面单号,将该波次下全部已打印(print_status='fin')
|
||||
* 且非拦截订单批量置 confirm_print_status='fin',并写订单操作日志(ORDER_CONFIRM_PRINT)。
|
||||
* - 拦截订单跳过(不确认、不阻断);
|
||||
* - 波次下存在未打印订单(print_status != 'fin')时阻断:返回 unprinted_order_count;
|
||||
* - 全部已确认时重复扫描返回 status=already_confirmed。
|
||||
*/
|
||||
export function orderWaveConfirmPrintScan(
|
||||
data: WaveConfirmPrintScanParams
|
||||
): Promise<WaveConfirmPrintScanResponse & { code?: number; message?: string; data?: Partial<WaveConfirmPrintScanResponse>; unprinted_order_count?: number }> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'order.wave.confirmPrintScan',
|
||||
v,
|
||||
timestamp: Date.now()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintUnclaimedWaveCount 入参:长轮询上次数量 */
|
||||
export type WaveConfirmPrintUnclaimedWaveCountParams = {
|
||||
/**
|
||||
* 上次返回的数量(长轮询游标):
|
||||
* 不传 → 立即返回当前值(status=current);传入且与当前值不同 → 立即返回新值(status=changed);
|
||||
* 相同 → 挂起等待,最长 60 秒(期间变化立即返回 changed,超时重查后返回 timeout)。
|
||||
*/
|
||||
last_count?: number
|
||||
}
|
||||
|
||||
/** order.wave.confirmPrintUnclaimedWaveCount 业务 data */
|
||||
export type WaveConfirmPrintUnclaimedWaveCountResponse = {
|
||||
/** 已确认打印(confirm_print_status='fin')但未领单(claim_status != 'fin')订单涉及的波次数量 */
|
||||
count: number
|
||||
/** current=直接返回当前值 / changed=数量已变化 / timeout=等待超时后返回当前值 */
|
||||
status: 'current' | 'changed' | 'timeout' | string
|
||||
}
|
||||
|
||||
/**
|
||||
* order.wave.confirmPrintUnclaimedWaveCount:查询「已确认打印但未领单」波次数量,支持长轮询。
|
||||
* 注意:长轮询最长挂起 60 秒,超过请求层默认 10 秒超时,故单独放开 timeout。
|
||||
*/
|
||||
export function orderWaveConfirmPrintUnclaimedWaveCount(
|
||||
data: WaveConfirmPrintUnclaimedWaveCountParams = {}
|
||||
): Promise<WaveConfirmPrintUnclaimedWaveCountResponse & { code?: number; message?: string; data?: Partial<WaveConfirmPrintUnclaimedWaveCountResponse> }> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'order.wave.confirmPrintUnclaimedWaveCount',
|
||||
v,
|
||||
timestamp: Date.now()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true,
|
||||
// 长轮询最长等待 60 秒(请求层默认 10 秒会提前中断)
|
||||
timeout: 70000
|
||||
} as any)
|
||||
}
|
||||
|
||||
export const orderModule = {
|
||||
waveBatchList: orderModuleWaveBatchList,
|
||||
confirmPrintScan: orderWaveConfirmPrintScan,
|
||||
confirmPrintUnclaimedWaveCount: orderWaveConfirmPrintUnclaimedWaveCount,
|
||||
pendingOrderDownloadCreateTemplate: orderModulePendingOrderDownloadCreateTemplate,
|
||||
pendingOrderManualWaybill: orderModulePendingOrderManualWaybill,
|
||||
bindExpressPackageMaterialByWaybill: orderBindExpressPackageMaterialByWaybill,
|
||||
|
||||
@ -53,7 +53,20 @@ export function register (data:any):any {
|
||||
|
||||
|
||||
|
||||
export function getInfo(data: Record<string, any>) {
|
||||
/**
|
||||
* user.info 入参
|
||||
* - 支持微信登录态中间层:未绑定真实用户时返回微信层信息(is_bound=false、id=0),不 401
|
||||
* - 可选 wechat_appId:按 wms_wechat_app.appid 反查归属仓库,过滤 employees 列表
|
||||
* (只保留非仓库工号与仅该仓库工号);未传或查不到仓库时保持原逻辑。
|
||||
*/
|
||||
export interface UserInfoParams {
|
||||
/** 小程序 AppID(可选) */
|
||||
wechat_appId?: string
|
||||
/** 其它业务参数(以后端为准) */
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
export function getInfo(data: UserInfoParams = {}) {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
|
||||
@ -39,18 +39,241 @@ export function wechatGetAuthUrl(
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取「代注册小程序」链接(第三方平台快速创建小程序):
|
||||
* 同样由用户点击按钮后才请求,并在新小窗口中打开;注册完成后调用业务侧查询接口刷新。
|
||||
* 若后端方法名不同,仅需改此处 method。
|
||||
* 查询当前仓库小程序的微信认证状态(wechat.queryauth)—— 无需入参,仓库由登录态上下文(ctx.user.store_id)决定。
|
||||
*/
|
||||
export function wechatGetRegisterUrl(
|
||||
data: Record<string, unknown> = {}
|
||||
): Promise<{ code?: number; message?: string; data?: WeChatAuthUrlPayload } & Record<string, unknown>> {
|
||||
export type WeChatQueryAuthData = {
|
||||
/** 小程序 AppID */
|
||||
appid: string
|
||||
/** 认证状态:0 未认证、1 认证中、2 认证通过、3 认证失败 */
|
||||
auth_state: number
|
||||
/** 认证状态中文文案 */
|
||||
auth_state_text: string
|
||||
}
|
||||
|
||||
export function wechatQueryAuth(): Promise<
|
||||
{ code?: number; message?: string; data?: WeChatQueryAuthData } & Record<string, unknown>
|
||||
> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.getRegisterUrl',
|
||||
method: 'wechat.queryauth',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速注册企业小程序(wechat.registerMiniprogram)——
|
||||
* 调微信 fastregisterweapp?action=create(component_access_token)提交企业信息创建注册任务,
|
||||
* 法人微信收到模板消息做人脸核身;审核结果由 notify_third_fasteregister 事件推送到后端授权事件接收 URL。
|
||||
*
|
||||
* 注意:本接口返回 errcode/errmsg,**不返回可打开的链接**,
|
||||
* 前端不应再按「取链接开小窗」的方式处理。
|
||||
*/
|
||||
export type WeChatRegisterMiniprogramParams = {
|
||||
/** 企业名(与工商登记一致;无主体名称个体工商户填「个体户+法人姓名」) */
|
||||
name: string
|
||||
/** 企业代码 */
|
||||
code: string
|
||||
/** 企业代码类型:1 统一社会信用代码(18位)、2 组织机构代码(9位)、3 营业执照注册号(15位) */
|
||||
code_type: 1 | 2 | 3
|
||||
/** 法人微信号(不支持手机号/微信名) */
|
||||
legal_persona_wechat: string
|
||||
/** 法人姓名(绑定银行卡) */
|
||||
legal_persona_name: string
|
||||
/** 第三方联系电话 */
|
||||
component_phone?: string
|
||||
}
|
||||
|
||||
export function wechatRegisterMiniprogram(
|
||||
data: WeChatRegisterMiniprogramParams
|
||||
): Promise<
|
||||
{ code?: number; message?: string; errcode?: number; errmsg?: string } & Record<string, unknown>
|
||||
> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.registerMiniprogram',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板库列表(wechat.getTemplateList)—— 只拉取普通模板(template_type=0),
|
||||
* 后端 Redis 缓存 24h(命中缓存直接返回,from_cache=true),用于「上传代码生成体验版」时选模板。
|
||||
*/
|
||||
export type WeChatTemplateItem = {
|
||||
/** 代码模板 ID(= wechat.commit 的 template_id 入参) */
|
||||
template_id?: number
|
||||
/** 模板版本号 */
|
||||
user_version?: string
|
||||
/** 模板描述 */
|
||||
user_desc?: string
|
||||
/** 模板创建时间(Unix 秒) */
|
||||
create_time?: number
|
||||
/** 草稿 ID */
|
||||
draft_id?: number
|
||||
/** 模板类型:0 普通模板 */
|
||||
template_type?: number
|
||||
/** 源小程序 AppID */
|
||||
source_miniprogram_appid?: string
|
||||
/** 源小程序账号 */
|
||||
source_miniprogram?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type WeChatTemplateListData = {
|
||||
list: WeChatTemplateItem[]
|
||||
/** 是否来自后端缓存(Redis 24h) */
|
||||
from_cache: boolean
|
||||
}
|
||||
|
||||
export function wechatGetTemplateList(): Promise<
|
||||
{ code?: number; message?: string; data?: WeChatTemplateListData } & Record<string, unknown>
|
||||
> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.getTemplateList',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data: {},
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传代码并生成体验版(wechat.commit)——
|
||||
* 后端取当前仓库启用小程序,校验授权权限集 18(代码管理)与模板存在性后调微信 wxa/commit 上传代码,
|
||||
* 成功后回写 wms_wechat_app.template_id。
|
||||
*/
|
||||
export type WeChatCommitParams = {
|
||||
/** 代码库中的代码模板 ID(由 wechat.getTemplateList 获取) */
|
||||
template_id: number
|
||||
/** ext.json 配置内容(JSON 字符串,控制 extAppid / 自定义字段等) */
|
||||
ext_json: string
|
||||
/** 代码版本号(≤64 字符) */
|
||||
user_version: string
|
||||
/** 代码描述 */
|
||||
user_desc: string
|
||||
}
|
||||
|
||||
export type WeChatCommitData = {
|
||||
/** 小程序 AppID */
|
||||
appid: string
|
||||
/** 已上传的模板 ID(同时回写 wms_wechat_app.template_id) */
|
||||
template_id: number
|
||||
}
|
||||
|
||||
export function wechatCommit(
|
||||
data: WeChatCommitParams
|
||||
): Promise<{ code?: number; message?: string; data?: WeChatCommitData } & Record<string, unknown>> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.commit',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true,
|
||||
// 上传代码到微信耗时较长,超时放宽到 3 分钟
|
||||
timeout: 180000
|
||||
} as any)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取体验版二维码(wechat.getTrialQRCode)——
|
||||
* 后端取当前仓库启用小程序,校验权限集 18 / 86 后调微信 wxa/get_qrcode 取二维码(jpeg),
|
||||
* 转存 COS 后返回可访问的图片 URL。
|
||||
*/
|
||||
export type WeChatTrialQRCodeParams = {
|
||||
/** 扫码后进入的页面路径(可选,如 page/index?action=1,后端自动 urlencode) */
|
||||
path?: string
|
||||
}
|
||||
|
||||
export type WeChatTrialQRCodeData = {
|
||||
/** 小程序 AppID */
|
||||
appid: string
|
||||
/** 二维码图片 URL(COS) */
|
||||
url: string
|
||||
}
|
||||
|
||||
export function wechatGetTrialQRCode(
|
||||
data: WeChatTrialQRCodeParams = {}
|
||||
): Promise<
|
||||
{ code?: number; message?: string; data?: WeChatTrialQRCodeData } & Record<string, unknown>
|
||||
> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.getTrialQRCode',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
data,
|
||||
isSystemApi: true
|
||||
} as any)
|
||||
}
|
||||
|
||||
/** 审核项(item_list 元素):微信审核类目信息,后端原样透传 */
|
||||
export type WeChatAuditItem = {
|
||||
/** 类目路径(如 教育/在线教育) */
|
||||
address?: string
|
||||
/** 类目标签 */
|
||||
tag?: string
|
||||
/** 一级类目 */
|
||||
first_class?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代码审核(wechat.submitAudit)——
|
||||
* 后端取当前仓库启用小程序,校验权限集 18;**仅 audit_status != 1(无审核中的版本)时允许提交**,
|
||||
* 成功后记录 audit_status=1 与 audit_id(回写 wms_wechat_app.audit_id)。
|
||||
*
|
||||
* 审核结果由微信事件(weapp_audit_success / weapp_audit_fail)回写后端:2 通过、3 驳回(含原因);
|
||||
* ⚠️ 目前没有查询审核状态的接口,前端只能得到「已提交」与 auditid。
|
||||
*/
|
||||
export type WeChatSubmitAuditParams = {
|
||||
/** 审核项列表(可选,含 address/tag/first_class 等类目信息) */
|
||||
item_list?: WeChatAuditItem[]
|
||||
/** 版本描述(可选) */
|
||||
version_desc?: string
|
||||
/** 不使用地理位置接口声明(可选) */
|
||||
privacy_api_not_use?: boolean
|
||||
}
|
||||
|
||||
export type WeChatSubmitAuditData = {
|
||||
/** 小程序 AppID */
|
||||
appid: string
|
||||
/** 微信审核单 ID(同时回写 wms_wechat_app.audit_id) */
|
||||
auditid: number
|
||||
}
|
||||
|
||||
export function wechatSubmitAudit(
|
||||
data: WeChatSubmitAuditParams = {}
|
||||
): Promise<
|
||||
{ code?: number; message?: string; data?: WeChatSubmitAuditData } & Record<string, unknown>
|
||||
> {
|
||||
return request({
|
||||
url: '/system',
|
||||
method: 'post',
|
||||
params: {
|
||||
method: 'wechat.submitAudit',
|
||||
v,
|
||||
timestamp: new Date().getTime()
|
||||
},
|
||||
@ -61,7 +284,12 @@ export function wechatGetRegisterUrl(
|
||||
|
||||
export const wechat = {
|
||||
getAuthUrl: wechatGetAuthUrl,
|
||||
getRegisterUrl: wechatGetRegisterUrl
|
||||
queryAuth: wechatQueryAuth,
|
||||
registerMiniprogram: wechatRegisterMiniprogram,
|
||||
getTemplateList: wechatGetTemplateList,
|
||||
commit: wechatCommit,
|
||||
getTrialQRCode: wechatGetTrialQRCode,
|
||||
submitAudit: wechatSubmitAudit
|
||||
}
|
||||
|
||||
export default wechat
|
||||
|
||||
@ -97,3 +97,34 @@ export function formatBarcodeText(
|
||||
const items = normalizeBarcodeList(value, options)
|
||||
return items.length ? items.join(separator) : fallback
|
||||
}
|
||||
|
||||
/** 行数据中可能承载条码的嵌套对象字段(按优先级) */
|
||||
const BARCODE_NESTED_KEYS = ['stock', 'store_stock', 'goods'] as const
|
||||
|
||||
/** 收集单行(含 stock/store_stock/goods 嵌套)内的条码:先取 barcodes 数组,再取 barcode 单值 */
|
||||
function collectRowBarcodesInto(row: unknown, result: string[]): void {
|
||||
if (!row || typeof row !== 'object' || Array.isArray(row)) return
|
||||
const record = row as Record<string, unknown>
|
||||
result.push(...normalizeBarcodeList(record.barcodes, { splitText: false }))
|
||||
const single = pickBarcodeText(record.barcode)
|
||||
if (single) result.push(single)
|
||||
for (const key of BARCODE_NESTED_KEYS) {
|
||||
collectRowBarcodesInto(record[key], result)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从一行或多行数据(如订单明细行 + item_snapshot、库存行 + stock/goods 关联)中
|
||||
* 归一化收集商品条码,去重并保持顺序。
|
||||
* 支持 `barcode` 单值、`barcodes` 数组(字符串数组 / 对象数组 / JSON 字符串)与嵌套对象。
|
||||
*/
|
||||
export function collectRowBarcodes(...rows: unknown[]): string[] {
|
||||
const collected: string[] = []
|
||||
for (const row of rows) collectRowBarcodesInto(row, collected)
|
||||
return Array.from(new Set(collected.filter(Boolean)))
|
||||
}
|
||||
|
||||
/** 取一行(或多行)数据中的首个商品条码;取不到时返回空串(不会输出 `[object Object]`) */
|
||||
export function resolveRowBarcode(...rows: unknown[]): string {
|
||||
return collectRowBarcodes(...rows)[0] ?? ''
|
||||
}
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
<!--
|
||||
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/packingflow-config'
|
||||
import { TAG_RESOLVERS, translate, formatTime } from '../config/packingflow-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>
|
||||
|
||||
@ -1,175 +0,0 @@
|
||||
<!--
|
||||
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/packingflow-config'
|
||||
import type { OperationButtonConfig } from '../config/packingflow-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>
|
||||
@ -1,132 +0,0 @@
|
||||
<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>
|
||||
@ -1,35 +0,0 @@
|
||||
<template>
|
||||
<el-button
|
||||
v-if="videoCount > 0"
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
@click.stop="$emit('click')"
|
||||
>
|
||||
<el-icon style="margin-right:2px"><VideoCameraFilled /></el-icon>
|
||||
有视频 ({{ videoCount }})
|
||||
</el-button>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { VideoCameraFilled } from '@element-plus/icons-vue'
|
||||
|
||||
export interface VideoItem {
|
||||
id: number
|
||||
video_url: string
|
||||
status?: string
|
||||
camera_id?: number
|
||||
camera_name?: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
videos: VideoItem[]
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
click: []
|
||||
}>()
|
||||
|
||||
const videoCount = computed(() => props.videos?.length ?? 0)
|
||||
</script>
|
||||
@ -1,134 +0,0 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="visible"
|
||||
title="打包录像列表"
|
||||
width="700px"
|
||||
align-center
|
||||
:close-on-click-modal="false"
|
||||
@update:model-value="$emit('update:visible', $event)"
|
||||
>
|
||||
<div v-if="videos.length === 0" class="empty-hint">
|
||||
<el-empty description="暂无录像" :image-size="80" />
|
||||
</div>
|
||||
<div v-else class="video-list">
|
||||
<div
|
||||
v-for="(video, index) in videos"
|
||||
:key="video.id ?? index"
|
||||
class="video-item"
|
||||
@click="$emit('play', video)"
|
||||
>
|
||||
<div class="video-item__thumb">
|
||||
<el-icon size="28"><VideoPlay /></el-icon>
|
||||
</div>
|
||||
<div class="video-item__info">
|
||||
<div class="video-item__name">
|
||||
{{ video.camera_name || '录像 ' + (index + 1) }}
|
||||
</div>
|
||||
<div class="video-item__meta">
|
||||
<span>摄像头ID: {{ video.camera_id ?? '—' }}</span>
|
||||
<span class="meta-divider">|</span>
|
||||
<span>录像ID: {{ video.id }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="video-item__action">
|
||||
<el-button type="primary" size="small" round>播放</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button size="small" @click="$emit('update:visible', false)">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { VideoPlay } from '@element-plus/icons-vue'
|
||||
import type { VideoItem } from './VideoButton.vue'
|
||||
|
||||
defineProps<{
|
||||
visible: boolean
|
||||
videos: VideoItem[]
|
||||
}>()
|
||||
|
||||
defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
play: [video: VideoItem]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.video-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.video-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 16px 20px;
|
||||
border: 1px solid #ebeef5;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.video-item:hover {
|
||||
border-color: #409eff;
|
||||
background: #ecf5ff;
|
||||
box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.video-item__thumb {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #ecf5ff 0%, #d9ecff 100%);
|
||||
border-radius: 12px;
|
||||
color: #409eff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.video-item:hover .video-item__thumb {
|
||||
background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.video-item__info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.video-item__name {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.video-item__meta {
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.meta-divider {
|
||||
color: #dcdfe6;
|
||||
}
|
||||
|
||||
.video-item__action {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.empty-hint {
|
||||
padding: 40px 0;
|
||||
}
|
||||
</style>
|
||||
@ -1,173 +0,0 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="visible"
|
||||
:title="video?.camera_name || '录像回放'"
|
||||
width="800px"
|
||||
align-center
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="$emit('update:visible', $event)"
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<div class="player-wrapper">
|
||||
<!-- 加载中 -->
|
||||
<div v-if="loading" class="player-overlay">
|
||||
<el-icon class="is-loading" size="32"><Loading /></el-icon>
|
||||
<span>加载中…</span>
|
||||
</div>
|
||||
|
||||
<!-- 播放错误 -->
|
||||
<div v-else-if="errorMsg" class="player-overlay">
|
||||
<el-icon size="32"><WarningFilled /></el-icon>
|
||||
<span class="error-text">{{ errorMsg }}</span>
|
||||
<el-button size="small" type="primary" @click="retry">重试</el-button>
|
||||
</div>
|
||||
|
||||
<!-- 视频播放器 -->
|
||||
<video
|
||||
v-show="!loading && !errorMsg"
|
||||
ref="videoRef"
|
||||
class="video-element"
|
||||
:src="video?.video_url"
|
||||
controls
|
||||
autoplay
|
||||
@loadeddata="loading = false"
|
||||
@error="handleVideoError"
|
||||
@ended="handleEnded"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 视频信息 -->
|
||||
<div v-if="video" class="video-info-bar">
|
||||
<span v-if="video.camera_id">摄像头ID: {{ video.camera_id }}</span>
|
||||
<span v-if="video.camera_name && video.camera_id" class="info-divider">|</span>
|
||||
<span v-if="video.camera_name">{{ video.camera_name }}</span>
|
||||
<span class="info-divider">|</span>
|
||||
<span>录像ID: {{ video.id }}</span>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button size="small" @click="$emit('update:visible', false)">关闭</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, nextTick } from 'vue'
|
||||
import { Loading, WarningFilled } from '@element-plus/icons-vue'
|
||||
import type { VideoItem } from './VideoButton.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
video: VideoItem | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
}>()
|
||||
|
||||
const videoRef = ref<HTMLVideoElement | null>(null)
|
||||
const loading = ref(true)
|
||||
const errorMsg = ref('')
|
||||
|
||||
// 打开时重置状态
|
||||
watch(() => props.visible, (val) => {
|
||||
if (val) {
|
||||
loading.value = true
|
||||
errorMsg.value = ''
|
||||
nextTick(() => {
|
||||
if (videoRef.value) {
|
||||
videoRef.value.load()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
function handleVideoError(e: Event) {
|
||||
loading.value = false
|
||||
const el = e.target as HTMLVideoElement
|
||||
const code = el?.error?.code
|
||||
const msgMap: Record<number, string> = {
|
||||
1: '视频加载被中止',
|
||||
2: '网络错误,无法加载视频',
|
||||
3: '视频解码失败',
|
||||
4: '视频格式不支持或文件不存在'
|
||||
}
|
||||
errorMsg.value = msgMap[code ?? 4] || '视频播放失败'
|
||||
}
|
||||
|
||||
function handleEnded() {
|
||||
// 播放结束
|
||||
}
|
||||
|
||||
function retry() {
|
||||
loading.value = true
|
||||
errorMsg.value = ''
|
||||
nextTick(() => {
|
||||
if (videoRef.value) {
|
||||
videoRef.value.load()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function handleClosed() {
|
||||
if (videoRef.value) {
|
||||
videoRef.value.pause()
|
||||
videoRef.value.removeAttribute('src')
|
||||
videoRef.value.load()
|
||||
}
|
||||
loading.value = true
|
||||
errorMsg.value = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.player-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 360px;
|
||||
background: #000;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.video-element {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
min-height: 360px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.player-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: #909399;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: #f56c6c;
|
||||
max-width: 300px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.video-info-bar {
|
||||
margin-top: 10px;
|
||||
padding: 6px 0;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.info-divider {
|
||||
color: #dcdfe6;
|
||||
}
|
||||
</style>
|
||||
@ -1,160 +0,0 @@
|
||||
<!--
|
||||
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 '../packingflow-config'
|
||||
import type { DetailSectionConfig, DetailFieldConfig } from '../packingflow-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(newRow.id)
|
||||
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 {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.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>
|
||||
@ -1,227 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,776 +0,0 @@
|
||||
/**
|
||||
* 【打包流水】页面配置 — 基于 template v2 架构
|
||||
*
|
||||
* 原 packingflow 页面迁移至 newpackingflow 新结构。
|
||||
* 仓库选择、运单号搜索等筛选条件统一整合到左侧 ScanBox 面板。
|
||||
*/
|
||||
|
||||
import type { Component } from 'vue'
|
||||
import DetailPanel from './components/DetailPanel.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import { packingList, packingGet } from '@/api/order/packing/index'
|
||||
|
||||
// ============================================================
|
||||
// 〇、全局页面配置
|
||||
// ============================================================
|
||||
export const PAGE_CONFIG = {
|
||||
/** 是否显示顶部多标签栏 */
|
||||
showTabArea: false,
|
||||
/** 单页模式:不显示标签栏,仅一个标签页内容 */
|
||||
singlePage: true,
|
||||
/** 是否启用详情面板(底部分栏),false 时表格占满全高 */
|
||||
enableDetailPanel: true
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 〇-A、组件注册表
|
||||
// ============================================================
|
||||
export const COMPONENT_REGISTRY: Record<string, Component> = {
|
||||
DetailPanel,
|
||||
LogPanel
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 〇-B、SCANBOX_GROUPS — ScanBox 分组名称
|
||||
// ============================================================
|
||||
export const SCANBOX_GROUPS = {
|
||||
basic: '基础信息',
|
||||
process: '流程状态',
|
||||
time: '时间范围'
|
||||
} 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 — 值翻译映射(select options 和 tag 翻译共用)
|
||||
// ============================================================
|
||||
export const VALUE_MAPS: Record<string, Record<string, string>> = {
|
||||
status: {
|
||||
'0': '未打包', '1': '打包中', '2': '已打包',
|
||||
'未打包': '未打包', '打包中': '打包中', '已打包': '已打包'
|
||||
},
|
||||
pack_mode: {
|
||||
'1': '散单', '2': '团购',
|
||||
'散单': '散单', '团购': '团购'
|
||||
}
|
||||
}
|
||||
|
||||
/** 从 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)
|
||||
}
|
||||
}
|
||||
|
||||
/** 计算打包时长(结束时间 - 开始时间),返回格式化字符串 */
|
||||
export function calcPackDuration(startTime: any, endTime: any): string {
|
||||
if (!startTime || !endTime) return '—'
|
||||
try {
|
||||
const start = new Date(startTime)
|
||||
const end = new Date(endTime)
|
||||
if (isNaN(start.getTime()) || isNaN(end.getTime())) return '—'
|
||||
const diff = end.getTime() - start.getTime()
|
||||
if (diff < 0) return '—'
|
||||
const hours = Math.floor(diff / 3600000)
|
||||
const minutes = Math.floor((diff % 3600000) / 60000)
|
||||
const seconds = Math.floor((diff % 60000) / 1000)
|
||||
if (hours > 0) return `${hours}小时${minutes}分${seconds}秒`
|
||||
if (minutes > 0) return `${minutes}分${seconds}秒`
|
||||
return `${seconds}秒`
|
||||
} catch {
|
||||
return '—'
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// TAG_RESOLVERS — 标签颜色解析器
|
||||
// ============================================================
|
||||
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
|
||||
resolveStatusTag(v) {
|
||||
const s = Number(v)
|
||||
if (s === 0) return 'info' // 未打包
|
||||
if (s === 1) return 'warning' // 打包中
|
||||
if (s === 2) return 'success' // 已打包
|
||||
return 'info'
|
||||
},
|
||||
resolvePackModeTag(v) {
|
||||
const s = Number(v)
|
||||
if (s === 2) return 'warning' // 团购
|
||||
return 'info' // 散单
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 二、FIELD_DICT 实例 — 打包流水字段定义
|
||||
// ============================================================
|
||||
export const FIELD_DICT: Record<string, FieldDefinition> = {
|
||||
id: {
|
||||
key: 'id',
|
||||
label: '任务ID',
|
||||
scanBox: null,
|
||||
table: { width: 90 },
|
||||
slot: null,
|
||||
detailLabel: '任务ID'
|
||||
},
|
||||
order_id: {
|
||||
key: 'order_id',
|
||||
label: '订单ID',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { width: 100 },
|
||||
slot: null,
|
||||
detailLabel: '订单ID'
|
||||
},
|
||||
waybill_code: {
|
||||
key: 'waybill_code',
|
||||
label: '运单号',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 160, showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '运单号'
|
||||
},
|
||||
wave_no: {
|
||||
key: 'wave_no',
|
||||
label: '波次号',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 140, showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '波次号'
|
||||
},
|
||||
operator_text: {
|
||||
key: 'operator_text',
|
||||
label: '打包员',
|
||||
scanBox: null,
|
||||
table: { width: 100 },
|
||||
slot: null,
|
||||
detailLabel: '打包员'
|
||||
},
|
||||
workbench_name: {
|
||||
key: 'workbench_name',
|
||||
label: '工作台',
|
||||
scanBox: null,
|
||||
table: { width: 120, showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '工作台'
|
||||
},
|
||||
pack_quantity: {
|
||||
key: 'pack_quantity',
|
||||
label: '打包数量',
|
||||
scanBox: null,
|
||||
table: { width: 100, align: 'center', sortable: true },
|
||||
slot: null,
|
||||
detailLabel: '打包数量'
|
||||
},
|
||||
pack_mode: {
|
||||
key: 'pack_mode',
|
||||
label: '打包模式',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('pack_mode') },
|
||||
table: { width: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagResolver: 'resolvePackModeTag', translateField: 'pack_mode' },
|
||||
detailLabel: '打包模式',
|
||||
filterParamMap: { '散单': '1', '团购': '2' }
|
||||
},
|
||||
status: {
|
||||
key: 'status',
|
||||
label: '任务状态',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('status') },
|
||||
table: { width: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagResolver: 'resolveStatusTag', translateField: 'status' },
|
||||
detailLabel: '任务状态',
|
||||
filterParamMap: { '未打包': '0', '打包中': '1', '已打包': '2' }
|
||||
},
|
||||
start_time: {
|
||||
key: 'start_time',
|
||||
label: '开始时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { width: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '开始时间'
|
||||
},
|
||||
end_time: {
|
||||
key: 'end_time',
|
||||
label: '结束时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { width: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '结束时间'
|
||||
},
|
||||
pack_duration: {
|
||||
key: 'pack_duration',
|
||||
label: '打包时长',
|
||||
scanBox: null,
|
||||
table: { width: 120, align: 'center' },
|
||||
slot: { type: 'text' },
|
||||
detailLabel: '打包时长'
|
||||
},
|
||||
create_time: {
|
||||
key: 'create_time',
|
||||
label: '创建时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { width: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '创建时间'
|
||||
},
|
||||
/** 仓库 — 仅用于 ScanBox 筛选,options 由 index.vue 动态注入 */
|
||||
warehouse_id: {
|
||||
key: 'warehouse_id',
|
||||
label: '仓库',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.basic, options: [] },
|
||||
table: null,
|
||||
slot: null
|
||||
},
|
||||
/** 工作台ID — 仅用于 ScanBox 筛选 */
|
||||
workbench_id: {
|
||||
key: 'workbench_id',
|
||||
label: '工作台ID',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: null,
|
||||
slot: null
|
||||
},
|
||||
/** 录像列 — 由 index.vue 自定义插槽渲染 VideoButton */
|
||||
videos: {
|
||||
key: 'videos',
|
||||
label: '录像',
|
||||
scanBox: null,
|
||||
table: { width: 110, fixed: 'right', align: 'center' },
|
||||
slot: null
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 三、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]
|
||||
|
||||
// daterange 类型:拆分为 key_start / key_end
|
||||
if (def?.scanBox?.type === 'daterange' && Array.isArray(value) && value.length === 2) {
|
||||
where[`${key}_start`] = value[0]
|
||||
where[`${key}_end`] = value[1]
|
||||
continue
|
||||
}
|
||||
|
||||
// filterParamMap 值映射(如中文 → 数字)
|
||||
if (def?.filterParamMap) {
|
||||
const mapped = def.filterParamMap[String(value)]
|
||||
if (mapped !== undefined) {
|
||||
where[key] = mapped
|
||||
continue
|
||||
}
|
||||
}
|
||||
where[key] = value
|
||||
}
|
||||
return where
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十、工具栏按钮系统
|
||||
// ============================================================
|
||||
// 按钮分类对齐 storage/receiving 模式:
|
||||
// refresh — 蓝底白字(刷新)
|
||||
// setting — 白底黑字(导出、字段设置、显示详情)
|
||||
// action — 白底蓝边框(功能操作)
|
||||
// cancel — 红底白字(作废/删除)
|
||||
|
||||
export interface ToolbarButtonConfig {
|
||||
key: string
|
||||
label: string
|
||||
category: 'refresh' | 'setting' | 'action' | 'cancel'
|
||||
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: 'refresh',
|
||||
size: 'small',
|
||||
loadingKey: 'loading',
|
||||
action: 'loadData'
|
||||
},
|
||||
columnConfig: {
|
||||
key: 'columnConfig',
|
||||
label: '字段设置',
|
||||
category: 'setting',
|
||||
size: 'small',
|
||||
action: 'openColumnConfigPanel'
|
||||
},
|
||||
toggleDetail: {
|
||||
key: 'toggleDetail',
|
||||
label: '显示详情',
|
||||
category: 'setting',
|
||||
dynamicLabelKey: 'detailToggleLabel',
|
||||
size: 'small',
|
||||
action: 'toggleDetailVisible'
|
||||
}
|
||||
}
|
||||
|
||||
/** 按标签页名称获取工具栏按钮列表(自动根据 PAGE_CONFIG 过滤) */
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十一、批量操作配置(可选,接入 BatchOperationForm 时使用)
|
||||
// ============================================================
|
||||
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> = {
|
||||
// batchExample: {
|
||||
// action: 'batchExample',
|
||||
// title: '批量操作示例',
|
||||
// confirmText: '确定对选中的 {count} 项执行操作吗?',
|
||||
// confirmType: 'warning',
|
||||
// confirmButtonText: '确认操作',
|
||||
// successText: '批量操作成功',
|
||||
// failText: '批量操作失败',
|
||||
// apiMethod: yourBatchApi,
|
||||
// payloadKey: 'ids',
|
||||
// idField: 'id'
|
||||
// }
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十二、标签页注册表 — 打包流水(单页模式)
|
||||
// ============================================================
|
||||
export const tabPages: TabPageRawConfig[] = [
|
||||
{
|
||||
name: 'packing',
|
||||
label: '打包任务',
|
||||
scanBoxCacheKey: 'packingflow-list',
|
||||
scanBoxFieldKeys: [
|
||||
'warehouse_id', 'waybill_code', 'wave_no', 'order_id', 'workbench_id',
|
||||
'status', 'pack_mode',
|
||||
'start_time'
|
||||
],
|
||||
tableColumnKeys: [
|
||||
'id', 'order_id', 'waybill_code', 'wave_no', 'operator_text',
|
||||
'workbench_name', 'pack_quantity', 'pack_mode', 'status',
|
||||
'start_time', 'end_time', 'pack_duration', 'create_time', 'videos'
|
||||
],
|
||||
upperTableDefaults: {
|
||||
title: '打包任务列表',
|
||||
showIndex: true,
|
||||
showSelection: false,
|
||||
emptyText: '暂无打包任务数据'
|
||||
},
|
||||
detailTabs: [
|
||||
{ name: 'detail', label: '任务明细', componentKey: 'DetailPanel' }
|
||||
],
|
||||
detailSections: [
|
||||
{
|
||||
title: '基础信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['id', 'order_id', 'wave_no', 'waybill_code', 'operator_text', 'workbench_name', 'pack_quantity', 'pack_mode', 'status']
|
||||
},
|
||||
{
|
||||
title: '时间信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['start_time', 'end_time', 'pack_duration', 'create_time']
|
||||
}
|
||||
],
|
||||
api: {
|
||||
list: packingList as ApiMethod,
|
||||
detail: packingGet as ApiMethod,
|
||||
parseListResponse(res: any) {
|
||||
const codeOk = [200, 20000, 1, 0].includes(res.code)
|
||||
if (!codeOk) throw new Error(res.message || '查询失败')
|
||||
const list = (res.data?.list ?? []).map((item: any) => ({
|
||||
...item,
|
||||
waybill_code: extractWaybillCode(item),
|
||||
pack_duration: calcPackDuration(item.start_time, item.end_time)
|
||||
}))
|
||||
return {
|
||||
list,
|
||||
total: res.data?.pagination?.total ?? 0
|
||||
}
|
||||
},
|
||||
buildListParams({ pagination, conditions, sort }) {
|
||||
// warehouse_id 提到顶层,其余进入 where
|
||||
const { warehouse_id, ...rest } = buildWhereConditions(conditions)
|
||||
return {
|
||||
warehouse_id: warehouse_id || undefined,
|
||||
pagination: { page: pagination.page, pageSize: pagination.pageSize },
|
||||
where: rest,
|
||||
sort: sort?.prop
|
||||
? { sortField: sort.prop, sortOrder: sort.order === 'ascending' ? 'ASC' : 'DESC' }
|
||||
: { sortField: 'create_time', sortOrder: 'DESC' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
// ============================================================
|
||||
// 十三、工具函数
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* 从 API 返回数据中提取运单号
|
||||
* 优先取顶层 waybill_code,若为空则从 expresses 数组中拼接
|
||||
*/
|
||||
export function extractWaybillCode(row: any): string | null {
|
||||
if (row.waybill_code) return row.waybill_code
|
||||
if (row.expresses?.length) {
|
||||
return row.expresses
|
||||
.map((e: any) => e.waybill_code)
|
||||
.filter(Boolean)
|
||||
.join(',')
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十四、向后兼容导出
|
||||
// ============================================================
|
||||
export const templateTabs = tabPages.map((t) => ({ name: t.name, label: t.label, scanBoxCacheKey: t.scanBoxCacheKey }))
|
||||
@ -1,879 +0,0 @@
|
||||
<!--
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ 【页面模板 v2】— 基于 waveOrder2 架构设计 ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
|
||||
===== 快速复制使用 =====
|
||||
1. 复制整个 views/mode/ 文件夹 → 重命名为你的页面名(如 views/order/myPage/)
|
||||
2. 修改 defineOptions name(如 'MyPage')
|
||||
3. 编辑 config/packingflow-config.ts:
|
||||
a. 在 FIELD_DICT 中添加页面字段
|
||||
b. 在 tabPages 中配置标签页(引用 FIELD_DICT 的 key)
|
||||
c. 在 TabPageApiConfig 中接入真实接口
|
||||
4. 在 router/map.ts 中添加路由
|
||||
|
||||
===== 页面结构 =====
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ TabArea(多标签页切换,可关闭) │
|
||||
├──────────┬──────────────────────────────────────────────┤
|
||||
│ ScanBox │ OrderToolbarButtonGroup(工具栏按钮组) │
|
||||
│ 筛选面板 │ ┌──────────────────────────────────────────┐│
|
||||
│ │ │ UpperTable(表格) ││
|
||||
│ │ │ - OperationCellRenderer(操作列) ││
|
||||
│ │ ├──────────────────────────────────────────┤│
|
||||
│ │ │ 分隔条(可拖拽) ││
|
||||
│ │ ├──────────────────────────────────────────┤│
|
||||
│ │ │ DetailPanel / LogPanel(明细/日志面板) ││
|
||||
│ │ └──────────────────────────────────────────┘│
|
||||
└──────────┴──────────────────────────────────────────────┘
|
||||
-->
|
||||
<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="220px"
|
||||
: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>
|
||||
|
||||
<!-- 上下分栏区域:详情面板启用时才显示分栏 + 详情 -->
|
||||
<template v-if="PAGE_CONFIG.enableDetailPanel">
|
||||
<div class="split-stack" ref="splitStackRef">
|
||||
<!-- 上半:表格 -->
|
||||
<div class="upper-wrapper" :style="detailVisible ? upperPaneStyle : upperPaneFullStyle">
|
||||
<UpperTable
|
||||
ref="upperTableRef"
|
||||
:title="currentTabConfig?.upperTable.title ?? '列表'"
|
||||
default-align="center"
|
||||
:enable-column-config="currentTabConfig?.upperTable.enableColumnConfig ?? true"
|
||||
:column-config-schema-version="1"
|
||||
:table-id="`template-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 ?? true"
|
||||
: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"
|
||||
>
|
||||
<!-- 动态列插槽:根据 columnSlots 配置自动渲染 -->
|
||||
<template
|
||||
v-for="(slotConfig, colProp) in currentColumnSlots"
|
||||
:key="`columnSlots-${colProp}`"
|
||||
#[`column-${colProp}`]="{ row }"
|
||||
>
|
||||
<!-- 操作列:渲染操作按钮 -->
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<!-- 其他列:标签/文本渲染 -->
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- 录像列自定义渲染 -->
|
||||
<template #column-videos="{ row }">
|
||||
<VideoButton :videos="row.videos || []" @click="openVideoList(row)" />
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</UpperTable>
|
||||
</div>
|
||||
|
||||
<!-- 分隔条(可拖拽) -->
|
||||
<template v-if="detailVisible">
|
||||
<div
|
||||
class="pane-resizer"
|
||||
title="拖动调整列表与详情区域高度"
|
||||
@mousedown="beginSplitDrag"
|
||||
/>
|
||||
|
||||
<!-- 下半:明细面板 -->
|
||||
<div v-if="selectedRow" class="lower-level" :style="lowerPaneStyle">
|
||||
<div class="detail-header">
|
||||
<el-tabs v-model="activeDetailTab" class="detail-tab">
|
||||
<el-tab-pane
|
||||
v-for="tab in currentDetailTabs"
|
||||
:key="tab.name"
|
||||
:label="tab.label"
|
||||
:name="tab.name"
|
||||
/>
|
||||
</el-tabs>
|
||||
</div>
|
||||
<div class="detail-container">
|
||||
<component
|
||||
:is="activeDetailTabComponent"
|
||||
:row="selectedDetail"
|
||||
:detail-config="currentDetailConfig"
|
||||
:api-method="currentDetailTabApiMethod"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 未选中行时的占位 -->
|
||||
<div v-else class="no-selection" :style="lowerPaneStyle">
|
||||
<div class="empty-tip">
|
||||
<p>请从上方列表中选择一项查看详情</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 详情面板禁用:表格占满全高 -->
|
||||
<template v-else>
|
||||
<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="`template-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 }"
|
||||
>
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- 录像列自定义渲染 -->
|
||||
<template #column-videos="{ row }">
|
||||
<VideoButton :videos="row.videos || []" @click="openVideoList(row)" />
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</UpperTable>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 录像弹窗 ===== -->
|
||||
<VideoListDialog
|
||||
v-model:visible="videoListVisible"
|
||||
:videos="currentVideos"
|
||||
@play="handlePlayVideo"
|
||||
/>
|
||||
<VideoPlayerDialog
|
||||
v-model:visible="playerVisible"
|
||||
:video="playingVideo"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// ============================================================
|
||||
// ★★★ 第一步:修改组件名 ★★★
|
||||
// ============================================================
|
||||
defineOptions({ name: 'PackingFlow' })
|
||||
|
||||
import { ref, computed, onMounted, reactive } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
|
||||
import { loadWarehouses } from '@/api/index/index'
|
||||
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 OperationCellRenderer from './components/OperationCellRenderer.vue'
|
||||
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
|
||||
import type { ToolbarButtonConfig as OrderToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
|
||||
import {
|
||||
PAGE_CONFIG,
|
||||
tabPages,
|
||||
resolveTabConfig,
|
||||
getTabToolbarButtons,
|
||||
type TabPageConfig,
|
||||
type DetailTabConfig,
|
||||
type ToolbarButtonConfig,
|
||||
} from './config/packingflow-config'
|
||||
import { extractWaybillCode } from './config/packingflow-config'
|
||||
import VideoButton, { type VideoItem } from './components/VideoButton.vue'
|
||||
import VideoListDialog from './components/VideoListDialog.vue'
|
||||
import VideoPlayerDialog from './components/VideoPlayerDialog.vue'
|
||||
|
||||
// ============================================================
|
||||
// 容器高度
|
||||
// ============================================================
|
||||
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 ?? 'tab1')
|
||||
|
||||
/** 当前激活标签页的完整配置 */
|
||||
const currentTabConfig = computed<TabPageConfig | undefined>(() => {
|
||||
const raw = tabPages.find((t) => t.name === activeTabName.value)
|
||||
if (!raw) return undefined
|
||||
return resolveTabConfig(raw)
|
||||
})
|
||||
|
||||
/** 当前 ScanBox 缓存 key */
|
||||
const currentScanBoxCacheKey = computed(
|
||||
() => currentTabConfig.value?.scanBoxCacheKey ?? 'template-default'
|
||||
)
|
||||
|
||||
/** 当前 ScanBox 筛选字段(动态注入仓库选项) */
|
||||
const warehouseOptions = ref<{ label: string; value: any }[]>([])
|
||||
|
||||
const currentScanBoxFields = computed(() => {
|
||||
const fields = currentTabConfig.value?.scanBoxFields ?? []
|
||||
if (warehouseOptions.value.length === 0) return fields
|
||||
return fields.map((f: any) => {
|
||||
if (f.value === 'warehouse_id') {
|
||||
return { ...f, options: warehouseOptions.value }
|
||||
}
|
||||
return f
|
||||
})
|
||||
})
|
||||
|
||||
/** 当前表格列 */
|
||||
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
|
||||
})
|
||||
|
||||
/** 当前激活明细标签页对应的 API 方法 */
|
||||
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
|
||||
|
||||
// DetailPanel 的数据由 handleRowClick 获取并预处理(如 extractWaybillCode),
|
||||
// 此处不传 apiMethod,避免 DetailPanel 内部重复请求覆盖已处理的数据
|
||||
let componentCfg: unknown
|
||||
switch (tab.componentKey) {
|
||||
case 'DetailPanel':
|
||||
return undefined
|
||||
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,
|
||||
exportLoading: false
|
||||
}))
|
||||
|
||||
const buttonLabelMap = computed<Record<string, string>>(() => ({
|
||||
detailToggleLabel: detailVisible.value ? '隐藏详情' : '显示详情'
|
||||
}))
|
||||
|
||||
const toolbarLayoutKey = computed(() =>
|
||||
JSON.stringify({
|
||||
loading: buttonLoadingMap.value,
|
||||
disabled: buttonDisabledMap.value,
|
||||
labels: buttonLabelMap.value
|
||||
})
|
||||
)
|
||||
|
||||
function resolveButtonLoading(loadingKey?: string) {
|
||||
if (!loadingKey) return false
|
||||
return Boolean(buttonLoadingMap.value[loadingKey])
|
||||
}
|
||||
|
||||
function resolveButtonDisabled(disabledKey?: string) {
|
||||
if (!disabledKey) return false
|
||||
return Boolean(buttonDisabledMap.value[disabledKey])
|
||||
}
|
||||
|
||||
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
|
||||
if (!dynamicLabelKey) return defaultLabel
|
||||
return buttonLabelMap.value[dynamicLabelKey] || defaultLabel
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 工具栏动作分发
|
||||
// ============================================================
|
||||
const toolbarActionMap: Record<string, () => void> = {
|
||||
loadData: () => { void loadData() },
|
||||
openColumnConfigPanel: () => { upperTableRef.value?.openColumnConfig?.() },
|
||||
toggleDetailVisible: () => { detailVisible.value = !detailVisible.value }
|
||||
}
|
||||
|
||||
function handleToolbarButtonClick(action: string) {
|
||||
const handler = toolbarActionMap[action]
|
||||
if (handler) {
|
||||
handler()
|
||||
return
|
||||
}
|
||||
// ★ 在此添加功能按钮分发
|
||||
console.warn('[PageTemplate] 未处理的工具栏动作:', action)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 操作列按钮事件处理
|
||||
// ============================================================
|
||||
async function handleOperationAction(key: string, row: Record<string, any>) {
|
||||
// ★ 在此添加操作列按钮回调
|
||||
console.log('[PageTemplate] 操作列按钮:', key, row)
|
||||
switch (key) {
|
||||
case 'viewDetail':
|
||||
// 已经通过行点击处理
|
||||
break
|
||||
case 'edit':
|
||||
ElMessage.info(`编辑「${row.name ?? row.code ?? row.id}」`)
|
||||
break
|
||||
default:
|
||||
console.warn('[PageTemplate] 未处理的操作按钮:', key)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// ★★★ 第二步:接入真实接口 ★★★
|
||||
// ============================================================
|
||||
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 && (res.code === 1 || res.code === 200)) {
|
||||
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 {
|
||||
// ★ 未配置 API 时使用模拟数据(替换为真实接口后删除)
|
||||
console.log('[PageTemplate] 未配置 API,使用空数据。请在 tabPages 中配置 api 字段。')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error('[PageTemplate] 加载列表失败:', e)
|
||||
ElMessage.error(e?.message || '获取列表数据失败')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
queryTime.value = Math.round(performance.now() - startTime)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// ScanBox 筛选事件
|
||||
// ============================================================
|
||||
const scanBoxRef = ref<any>(null)
|
||||
const presetTree = ref<any[]>([])
|
||||
|
||||
const handleConditionChange = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
const handleConditionReset = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
const handleConditionClear = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// UpperTable 事件
|
||||
// ============================================================
|
||||
const upperTableRef = ref<any>(null)
|
||||
const selectedRows = ref<Record<string, any>[]>([])
|
||||
|
||||
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 detailVisible = ref(PAGE_CONFIG.enableDetailPanel)
|
||||
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
|
||||
|
||||
// 根据 DetailPanel 的 api 配置决定数据来源
|
||||
const detailCfg = cfg.api?.detail
|
||||
if (typeof detailCfg === 'function') {
|
||||
try {
|
||||
const detailRes = await detailCfg(row.id)
|
||||
if (detailRes && (detailRes.code === 1 || detailRes.code === 200 || detailRes.code === 20000)) {
|
||||
const rawData = detailRes.data ?? detailRes
|
||||
rawData.waybill_code = extractWaybillCode(rawData)
|
||||
selectedDetail.value = rawData
|
||||
} else {
|
||||
selectedDetail.value = { ...row }
|
||||
}
|
||||
} catch {
|
||||
selectedDetail.value = { ...row }
|
||||
}
|
||||
} else {
|
||||
// source='list' 或未配置:直接用行数据
|
||||
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()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 分栏拖拽
|
||||
// ============================================================
|
||||
const { splitStackRef, beginSplitDrag, lowerPaneStyle, upperPaneStyle } =
|
||||
useVerticalSplitPane({ defaultLowerPercent: 38 })
|
||||
|
||||
const upperPaneFullStyle = computed(() => ({
|
||||
flex: '1 1 auto',
|
||||
minHeight: '0',
|
||||
overflow: 'hidden' as const
|
||||
}))
|
||||
|
||||
// ============================================================
|
||||
// 录像相关
|
||||
// ============================================================
|
||||
const videoListVisible = ref(false)
|
||||
const playerVisible = ref(false)
|
||||
const currentVideos = ref<VideoItem[]>([])
|
||||
const playingVideo = ref<VideoItem | null>(null)
|
||||
|
||||
function openVideoList(row: Record<string, any>) {
|
||||
currentVideos.value = (row.videos as VideoItem[]) || []
|
||||
if (currentVideos.value.length === 0) return
|
||||
videoListVisible.value = true
|
||||
}
|
||||
|
||||
function handlePlayVideo(video: VideoItem) {
|
||||
videoListVisible.value = false
|
||||
playingVideo.value = video
|
||||
playerVisible.value = true
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 初始化
|
||||
// ============================================================
|
||||
|
||||
/** 加载仓库列表,注入到 ScanBox 的 warehouse_id 选项中 */
|
||||
async function loadWarehouseOptions() {
|
||||
try {
|
||||
const res: any = await loadWarehouses()
|
||||
const raw = res?.warehouses || res?.data?.list || res?.data || []
|
||||
warehouseOptions.value = raw.map((item: any) => ({
|
||||
label: item.label || item.warehouse_name || item.company_name || String(item.value ?? ''),
|
||||
value: item.value ?? item.warehouse_id ?? item.id
|
||||
}))
|
||||
} catch {
|
||||
// 仓库列表加载失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadWarehouseOptions()
|
||||
loadData()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
/* ===== 引入共享样式(scan-box / toolbar / split-stack / pane-resizer / lower-level 等) ===== */
|
||||
@use "../../order/orderManagement/styles/order-sub.scss";
|
||||
|
||||
/* ================================================================
|
||||
整体布局容器
|
||||
================================================================ */
|
||||
.page-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
1. 顶部多标签页区域
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
2. 主内容区容器
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
3. ScanBox "筛选/过滤" 标签样式(对齐页面顶部 TabArea 风格)
|
||||
================================================================ */
|
||||
.main-container {
|
||||
: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;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
补充:过渡动画
|
||||
================================================================ */
|
||||
.main-content {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tab-content-inner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* fade + slide 混合过渡 */
|
||||
.tab-fade-enter-active,
|
||||
.tab-fade-leave-active {
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.tab-fade-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
.tab-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
.tab-fade-leave-active {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
无选中行时的占位(与 waveOrder2 保持一致)
|
||||
================================================================ */
|
||||
.no-selection {
|
||||
flex: 0 0 38%;
|
||||
height: 38%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-top: 1px solid #ebeef5;
|
||||
overflow: hidden;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
明细面板
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
空提示样式
|
||||
================================================================ */
|
||||
.empty-tip {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.empty-tip p {
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
@ -1,107 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -2,7 +2,7 @@ import type {
|
||||
InboxV2SubTypeGroupItem,
|
||||
InboxV2SubTypeItem,
|
||||
InboxV2TypeItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
|
||||
// ============================================================
|
||||
// 自动回复设置 - 常量与选项
|
||||
|
||||
@ -111,7 +111,7 @@ import {
|
||||
inboxV2RelationFunctionSet,
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2FunctionItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import { functionColumns } from '../autoReply-config'
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@ -109,7 +109,7 @@ import {
|
||||
inboxV2RelationGroupSet,
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2SubTypeGroupItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import {
|
||||
getGroupTypeOptions,
|
||||
getSubGroupOptions,
|
||||
|
||||
@ -129,7 +129,7 @@ import {
|
||||
inboxV2KeywordUpdate,
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2KeywordItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import {
|
||||
isSystemRecord,
|
||||
keywordColumns,
|
||||
|
||||
@ -93,7 +93,7 @@ import {
|
||||
inboxV2RelationRuleSet,
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2NumberRuleItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import { numberRuleColumns, numberRuleTargetLabel } from '../autoReply-config'
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@ -74,7 +74,7 @@ import {
|
||||
inboxV2ReplySave,
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2MergedReplyItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import { replyPlaceholders, toFlag } from '../autoReply-config'
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@ -52,7 +52,7 @@ import {
|
||||
inboxV2SubTypeCreate,
|
||||
inboxV2SubTypeUpdate,
|
||||
type InboxV2SubTypeItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import { toFlag } from '../autoReply-config'
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@ -43,7 +43,7 @@ import {
|
||||
inboxV2TypeCreate,
|
||||
inboxV2TypeUpdate,
|
||||
type InboxV2TypeItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import { toFlag } from '../autoReply-config'
|
||||
|
||||
const props = defineProps<{
|
||||
|
||||
@ -332,7 +332,7 @@ import {
|
||||
unwrapInboxV2Data,
|
||||
type InboxV2SubTypeItem,
|
||||
type InboxV2TypeItem,
|
||||
} from '@/api/inbox/autoReply'
|
||||
} from '@/api/inbox-2/autoReply'
|
||||
import {
|
||||
isSystemRecord,
|
||||
subTypeColumns,
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
|
||||
@ -1,175 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,132 +0,0 @@
|
||||
<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>
|
||||
@ -1,159 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,227 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,727 +0,0 @@
|
||||
/**
|
||||
* 【页面模板】配置文件 v2 — 基于 waveOrder2 架构设计
|
||||
*
|
||||
* ===== 核心设计 =====
|
||||
*
|
||||
* 1. FIELD_DICT — 全局字段预设表,每个字段拥有唯一翻译(label)和完整元数据
|
||||
* 2. VALUE_MAPS — 值翻译映射表(select options 和 tag 翻译共用)
|
||||
* 3. TAG_RESOLVERS — 标签颜色解析器(集中管理 tag 颜色逻辑)
|
||||
* 4. 各标签页通过 key 引用所需字段(scanBoxFieldKeys / tableColumnKeys)
|
||||
* 5. resolveTabConfig() — 加载时将 key 列表展开为完整配置
|
||||
*
|
||||
* ===== 快速上手 =====
|
||||
* 1. 复制整个 views/mode/ 文件夹,重命名为你的页面名
|
||||
* 2. 在 FIELD_DICT 中添加你需要的字段定义
|
||||
* 3. 在 tabPages 中配置标签页(引用 FIELD_DICT 的 key)
|
||||
* 4. 在 TabPageApiConfig 中接入真实接口
|
||||
* 5. 在 router/map.ts 中添加路由
|
||||
*/
|
||||
|
||||
import type { Component } from 'vue'
|
||||
import DetailPanel from './components/DetailPanel.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
|
||||
// ============================================================
|
||||
// 〇、全局页面配置
|
||||
// ============================================================
|
||||
export const PAGE_CONFIG = {
|
||||
/** 是否显示顶部多标签栏 */
|
||||
showTabArea: true,
|
||||
/** 单页模式:不显示标签栏,仅一个标签页内容 */
|
||||
singlePage: false,
|
||||
/** 是否启用详情面板(底部分栏 + 显示/隐藏详情按钮),false 时表格占满全高 */
|
||||
enableDetailPanel: true
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 〇-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 — 值翻译映射(select options 和 tag 翻译共用)
|
||||
// ============================================================
|
||||
export const VALUE_MAPS: Record<string, Record<string, string>> = {
|
||||
status: { 'pending': '待处理', 'processing': '处理中', 'done': '已完成', '待处理': '待处理', '处理中': '处理中', '已完成': '已完成' },
|
||||
type: { 'A': '类型A', 'B': '类型B', 'C': '类型C', '类型A': '类型A', '类型B': '类型B', '类型C': '类型C' },
|
||||
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 — 标签颜色解析器
|
||||
// ============================================================
|
||||
// 颜色规则:未xx=info(灰) 已xx=success(绿) xx中/部分xx=warning(黄) 错误=danger(红)
|
||||
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
|
||||
resolveStatusTag(v) {
|
||||
if (!v) return 'info'
|
||||
if (v === '已完成' || v === 'done') return 'success'
|
||||
if (v === '处理中' || v === 'processing') return 'warning'
|
||||
return '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> = {
|
||||
code: {
|
||||
key: 'code',
|
||||
label: '编号',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 160, fixed: 'left', copyAction: 'copy', showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '编号'
|
||||
},
|
||||
name: {
|
||||
key: 'name',
|
||||
label: '名称',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 150, showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '名称'
|
||||
},
|
||||
type: {
|
||||
key: 'type',
|
||||
label: '类型',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.basic, options: getOptions('type') },
|
||||
table: { minWidth: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagType: 'info', translateField: 'type' },
|
||||
detailLabel: '类型',
|
||||
filterParamMap: { '类型A': 'A', '类型B': 'B', '类型C': 'C' }
|
||||
},
|
||||
status: {
|
||||
key: 'status',
|
||||
label: '状态',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('status') },
|
||||
table: { minWidth: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagResolver: 'resolveStatusTag', translateField: 'status' },
|
||||
detailLabel: '状态',
|
||||
filterParamMap: { '待处理': 'pending', '处理中': 'processing', '已完成': 'done' }
|
||||
},
|
||||
count: {
|
||||
key: 'count',
|
||||
label: '数量',
|
||||
scanBox: null,
|
||||
table: { minWidth: 80, align: 'center', sortable: true },
|
||||
slot: null
|
||||
},
|
||||
amount: {
|
||||
key: 'amount',
|
||||
label: '金额(元)',
|
||||
scanBox: null,
|
||||
table: { minWidth: 110, align: 'center', sortable: true },
|
||||
slot: null
|
||||
},
|
||||
creator: {
|
||||
key: 'creator',
|
||||
label: '创建人',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 100 },
|
||||
slot: null,
|
||||
detailLabel: '创建人'
|
||||
},
|
||||
create_time: {
|
||||
key: 'create_time',
|
||||
label: '创建时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { minWidth: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '创建时间'
|
||||
},
|
||||
update_time: {
|
||||
key: 'update_time',
|
||||
label: '更新时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { minWidth: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '更新时间'
|
||||
},
|
||||
/** 操作列(虚拟字段,仅用于表格列渲染) */
|
||||
operation: {
|
||||
key: 'operation',
|
||||
label: '操作',
|
||||
scanBox: null,
|
||||
table: { minWidth: 180, 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
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十、工具栏按钮系统
|
||||
// ============================================================
|
||||
// 按钮分为三类:
|
||||
// common — 公共按钮(刷新、导出)
|
||||
// function — 功能按钮(打开表单/确认窗口)
|
||||
// basic — 基础操作(字段设置、隐藏详情)
|
||||
|
||||
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'
|
||||
},
|
||||
export: {
|
||||
key: 'export',
|
||||
label: '导出',
|
||||
category: 'common',
|
||||
size: 'small',
|
||||
loadingKey: 'exportLoading',
|
||||
action: 'handleExport',
|
||||
buttonType: 'dropdown',
|
||||
dropdownOptions: [
|
||||
{ label: '不含明细', action: 'handleExport' },
|
||||
{ label: '含明细', action: 'handleExportItem', divided: true }
|
||||
]
|
||||
},
|
||||
// ===== 基础操作 =====
|
||||
columnConfig: {
|
||||
key: 'columnConfig',
|
||||
label: '字段设置',
|
||||
category: 'basic',
|
||||
size: 'small',
|
||||
action: 'openColumnConfigPanel'
|
||||
},
|
||||
toggleDetail: {
|
||||
key: 'toggleDetail',
|
||||
label: '显示详情',
|
||||
category: 'basic',
|
||||
dynamicLabelKey: 'detailToggleLabel',
|
||||
size: 'small',
|
||||
action: 'toggleDetailVisible'
|
||||
}
|
||||
// ★ 在此添加功能按钮(如批量操作)★
|
||||
}
|
||||
|
||||
/** 按标签页名称获取工具栏按钮列表(自动根据 PAGE_CONFIG 过滤) */
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十一、批量操作配置(可选,接入 BatchOperationForm 时使用)
|
||||
// ============================================================
|
||||
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> = {
|
||||
// batchExample: {
|
||||
// action: 'batchExample',
|
||||
// title: '批量操作示例',
|
||||
// confirmText: '确定对选中的 {count} 项执行操作吗?',
|
||||
// confirmType: 'warning',
|
||||
// confirmButtonText: '确认操作',
|
||||
// successText: '批量操作成功',
|
||||
// failText: '批量操作失败',
|
||||
// apiMethod: yourBatchApi,
|
||||
// payloadKey: 'ids',
|
||||
// idField: 'id'
|
||||
// }
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十二、标签页注册表 — 在此定义你的页面标签页
|
||||
// ============================================================
|
||||
export const tabPages: TabPageRawConfig[] = [
|
||||
// ===== 示例标签页一 =====
|
||||
{
|
||||
name: 'tab1',
|
||||
label: '标签页一',
|
||||
scanBoxCacheKey: 'template-tab1',
|
||||
scanBoxFieldKeys: ['code', 'type', 'status', 'creator', 'create_time'],
|
||||
tableColumnKeys: ['code', 'name', 'type', 'status', 'count', 'amount', 'creator', 'create_time', 'operation'],
|
||||
upperTableDefaults: {
|
||||
title: '示例列表一',
|
||||
showSelection: true
|
||||
},
|
||||
detailTabs: [
|
||||
{ name: 'detail', label: '明细', componentKey: 'DetailPanel' },
|
||||
{ name: 'log', label: '操作日志', componentKey: 'LogPanel' }
|
||||
],
|
||||
detailSections: [
|
||||
{
|
||||
title: '基础信息',
|
||||
columnCount: 3,
|
||||
fieldKeys: ['code', 'name', 'type', 'status', 'count', 'amount', 'creator']
|
||||
},
|
||||
{
|
||||
title: '时间信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['create_time', 'update_time']
|
||||
}
|
||||
],
|
||||
/** ★ 接入真实接口时取消注释 */
|
||||
// api: {
|
||||
// list: yourListApi,
|
||||
// detail: { source: 'list' },
|
||||
// parseListResponse(res) {
|
||||
// return { list: res.data?.list ?? [], total: res.data?.pagination?.total ?? 0 }
|
||||
// },
|
||||
// buildListParams({ pagination, conditions, sort }) {
|
||||
// return {
|
||||
// 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: 'warning'
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// ===== 示例标签页二 =====
|
||||
{
|
||||
name: 'tab2',
|
||||
label: '标签页二',
|
||||
scanBoxCacheKey: 'template-tab2',
|
||||
scanBoxFieldKeys: ['code', 'status', 'create_time'],
|
||||
tableColumnKeys: ['code', 'name', 'status', 'count', 'creator', 'create_time', 'operation'],
|
||||
upperTableDefaults: {
|
||||
title: '示例列表二',
|
||||
showSelection: true
|
||||
},
|
||||
detailSections: [
|
||||
{
|
||||
title: '基础信息',
|
||||
columnCount: 3,
|
||||
fieldKeys: ['code', 'name', 'status', 'count', 'creator']
|
||||
},
|
||||
{
|
||||
title: '时间信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['create_time', 'update_time']
|
||||
}
|
||||
],
|
||||
operationButtons: [
|
||||
{
|
||||
key: 'viewDetail',
|
||||
label: '查看详情',
|
||||
actionType: 'action',
|
||||
type: 'primary'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
// ============================================================
|
||||
// 十三、向后兼容导出
|
||||
// ============================================================
|
||||
export const templateTabs = tabPages.map((t) => ({ name: t.name, label: t.label, scanBoxCacheKey: t.scanBoxCacheKey }))
|
||||
|
||||
@ -1,854 +0,0 @@
|
||||
<!--
|
||||
╔══════════════════════════════════════════════════════════════╗
|
||||
║ 【页面模板 v2】— 基于 waveOrder2 架构设计 ║
|
||||
╚══════════════════════════════════════════════════════════════╝
|
||||
|
||||
===== 快速复制使用 =====
|
||||
1. 复制整个 views/mode/ 文件夹 → 重命名为你的页面名(如 views/order/myPage/)
|
||||
2. 修改 defineOptions name(如 'MyPage')
|
||||
3. 编辑 config/template-config.ts:
|
||||
a. 在 FIELD_DICT 中添加页面字段
|
||||
b. 在 tabPages 中配置标签页(引用 FIELD_DICT 的 key)
|
||||
c. 在 TabPageApiConfig 中接入真实接口
|
||||
4. 在 router/map.ts 中添加路由
|
||||
|
||||
===== 页面结构 =====
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ TabArea(多标签页切换,可关闭) │
|
||||
├──────────┬──────────────────────────────────────────────┤
|
||||
│ ScanBox │ OrderToolbarButtonGroup(工具栏按钮组) │
|
||||
│ 筛选面板 │ ┌──────────────────────────────────────────┐│
|
||||
│ │ │ UpperTable(表格) ││
|
||||
│ │ │ - OperationCellRenderer(操作列) ││
|
||||
│ │ ├──────────────────────────────────────────┤│
|
||||
│ │ │ 分隔条(可拖拽) ││
|
||||
│ │ ├──────────────────────────────────────────┤│
|
||||
│ │ │ DetailPanel / LogPanel(明细/日志面板) ││
|
||||
│ │ └──────────────────────────────────────────┘│
|
||||
└──────────┴──────────────────────────────────────────────┘
|
||||
-->
|
||||
<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="220px"
|
||||
: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>
|
||||
|
||||
<!-- 上下分栏区域:详情面板启用时才显示分栏 + 详情 -->
|
||||
<template v-if="PAGE_CONFIG.enableDetailPanel">
|
||||
<div class="split-stack" ref="splitStackRef">
|
||||
<!-- 上半:表格 -->
|
||||
<div class="upper-wrapper" :style="detailVisible ? upperPaneStyle : upperPaneFullStyle">
|
||||
<UpperTable
|
||||
ref="upperTableRef"
|
||||
:title="currentTabConfig?.upperTable.title ?? '列表'"
|
||||
default-align="center"
|
||||
:enable-column-config="currentTabConfig?.upperTable.enableColumnConfig ?? true"
|
||||
:column-config-schema-version="1"
|
||||
:table-id="`template-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 ?? true"
|
||||
: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"
|
||||
>
|
||||
<!-- 动态列插槽:根据 columnSlots 配置自动渲染 -->
|
||||
<template
|
||||
v-for="(slotConfig, colProp) in currentColumnSlots"
|
||||
:key="`columnSlots-${colProp}`"
|
||||
#[`column-${colProp}`]="{ row }"
|
||||
>
|
||||
<!-- 操作列:渲染操作按钮 -->
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<!-- 其他列:标签/文本渲染 -->
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</UpperTable>
|
||||
</div>
|
||||
|
||||
<!-- 分隔条(可拖拽) -->
|
||||
<template v-if="detailVisible">
|
||||
<div
|
||||
class="pane-resizer"
|
||||
title="拖动调整列表与详情区域高度"
|
||||
@mousedown="beginSplitDrag"
|
||||
/>
|
||||
|
||||
<!-- 下半:明细面板 -->
|
||||
<div v-if="selectedRow" class="lower-level" :style="lowerPaneStyle">
|
||||
<div class="detail-header">
|
||||
<el-tabs v-model="activeDetailTab" class="detail-tab">
|
||||
<el-tab-pane
|
||||
v-for="tab in currentDetailTabs"
|
||||
:key="tab.name"
|
||||
:label="tab.label"
|
||||
:name="tab.name"
|
||||
/>
|
||||
</el-tabs>
|
||||
</div>
|
||||
<div class="detail-container">
|
||||
<component
|
||||
:is="activeDetailTabComponent"
|
||||
:row="selectedDetail"
|
||||
:detail-config="currentDetailConfig"
|
||||
:api-method="currentDetailTabApiMethod"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 未选中行时的占位 -->
|
||||
<div v-else class="no-selection" :style="lowerPaneStyle">
|
||||
<div class="empty-tip">
|
||||
<p>请从上方列表中选择一项查看详情</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 详情面板禁用:表格占满全高 -->
|
||||
<template v-else>
|
||||
<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="`template-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 }"
|
||||
>
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</UpperTable>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 功能按钮表单(pages/ 目录下的组件) ===== -->
|
||||
<!-- ★ 在此添加表单弹窗组件,如:
|
||||
<YourFormDialog
|
||||
v-model:visible="yourFormVisible"
|
||||
@success="handleFormSuccess"
|
||||
/>
|
||||
-->
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// ============================================================
|
||||
// ★★★ 第一步:修改组件名 ★★★
|
||||
// ============================================================
|
||||
defineOptions({ name: 'PageTemplate' })
|
||||
|
||||
import { ref, computed, onMounted, reactive } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
|
||||
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 OperationCellRenderer from './components/OperationCellRenderer.vue'
|
||||
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
|
||||
import type { ToolbarButtonConfig as OrderToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
|
||||
import {
|
||||
PAGE_CONFIG,
|
||||
tabPages,
|
||||
resolveTabConfig,
|
||||
getTabToolbarButtons,
|
||||
type TabPageConfig,
|
||||
type DetailTabConfig,
|
||||
type ToolbarButtonConfig,
|
||||
} from './config/template-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 ?? 'tab1')
|
||||
|
||||
/** 当前激活标签页的完整配置 */
|
||||
const currentTabConfig = computed<TabPageConfig | undefined>(() => {
|
||||
const raw = tabPages.find((t) => t.name === activeTabName.value)
|
||||
if (!raw) return undefined
|
||||
return resolveTabConfig(raw)
|
||||
})
|
||||
|
||||
/** 当前 ScanBox 缓存 key */
|
||||
const currentScanBoxCacheKey = computed(
|
||||
() => currentTabConfig.value?.scanBoxCacheKey ?? 'template-default'
|
||||
)
|
||||
|
||||
/** 当前 ScanBox 筛选字段 */
|
||||
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
|
||||
})
|
||||
|
||||
/** 当前激活明细标签页对应的 API 方法 */
|
||||
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,
|
||||
exportLoading: false
|
||||
}))
|
||||
|
||||
const buttonLabelMap = computed<Record<string, string>>(() => ({
|
||||
detailToggleLabel: detailVisible.value ? '隐藏详情' : '显示详情'
|
||||
}))
|
||||
|
||||
const toolbarLayoutKey = computed(() =>
|
||||
JSON.stringify({
|
||||
loading: buttonLoadingMap.value,
|
||||
disabled: buttonDisabledMap.value,
|
||||
labels: buttonLabelMap.value
|
||||
})
|
||||
)
|
||||
|
||||
function resolveButtonLoading(loadingKey?: string) {
|
||||
if (!loadingKey) return false
|
||||
return Boolean(buttonLoadingMap.value[loadingKey])
|
||||
}
|
||||
|
||||
function resolveButtonDisabled(disabledKey?: string) {
|
||||
if (!disabledKey) return false
|
||||
return Boolean(buttonDisabledMap.value[disabledKey])
|
||||
}
|
||||
|
||||
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
|
||||
if (!dynamicLabelKey) return defaultLabel
|
||||
return buttonLabelMap.value[dynamicLabelKey] || defaultLabel
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 工具栏动作分发
|
||||
// ============================================================
|
||||
const toolbarActionMap: Record<string, () => void> = {
|
||||
loadData: () => { void loadData() },
|
||||
openColumnConfigPanel: () => { upperTableRef.value?.openColumnConfig?.() },
|
||||
toggleDetailVisible: () => { detailVisible.value = !detailVisible.value },
|
||||
handleExport: () => { console.log('[PageTemplate] 导出(不含明细)', activeTabName.value) },
|
||||
handleExportItem: () => { console.log('[PageTemplate] 导出(含明细)', activeTabName.value) }
|
||||
}
|
||||
|
||||
function handleToolbarButtonClick(action: string) {
|
||||
const handler = toolbarActionMap[action]
|
||||
if (handler) {
|
||||
handler()
|
||||
return
|
||||
}
|
||||
// ★ 在此添加功能按钮分发
|
||||
console.warn('[PageTemplate] 未处理的工具栏动作:', action)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 操作列按钮事件处理
|
||||
// ============================================================
|
||||
async function handleOperationAction(key: string, row: Record<string, any>) {
|
||||
// ★ 在此添加操作列按钮回调
|
||||
console.log('[PageTemplate] 操作列按钮:', key, row)
|
||||
switch (key) {
|
||||
case 'viewDetail':
|
||||
// 已经通过行点击处理
|
||||
break
|
||||
case 'edit':
|
||||
ElMessage.info(`编辑「${row.name ?? row.code ?? row.id}」`)
|
||||
break
|
||||
default:
|
||||
console.warn('[PageTemplate] 未处理的操作按钮:', key)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// ★★★ 第二步:接入真实接口 ★★★
|
||||
// ============================================================
|
||||
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 && (res.code === 1 || res.code === 200)) {
|
||||
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 {
|
||||
// ★ 未配置 API 时使用模拟数据(替换为真实接口后删除)
|
||||
console.log('[PageTemplate] 未配置 API,使用空数据。请在 tabPages 中配置 api 字段。')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error('[PageTemplate] 加载列表失败:', e)
|
||||
ElMessage.error(e?.message || '获取列表数据失败')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
queryTime.value = Math.round(performance.now() - startTime)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// ScanBox 筛选事件
|
||||
// ============================================================
|
||||
const scanBoxRef = ref<any>(null)
|
||||
const presetTree = ref<any[]>([])
|
||||
|
||||
const handleConditionChange = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
const handleConditionReset = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
const handleConditionClear = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// UpperTable 事件
|
||||
// ============================================================
|
||||
const upperTableRef = ref<any>(null)
|
||||
const selectedRows = ref<Record<string, any>[]>([])
|
||||
|
||||
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 detailVisible = ref(PAGE_CONFIG.enableDetailPanel)
|
||||
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
|
||||
|
||||
// 根据 DetailPanel 的 api 配置决定数据来源
|
||||
const detailCfg = cfg.api?.detail
|
||||
if (typeof detailCfg === 'function') {
|
||||
try {
|
||||
const detailRes = await detailCfg({ id: row.id, code: row.code })
|
||||
if (detailRes && (detailRes.code === 1 || detailRes.code === 200)) {
|
||||
selectedDetail.value = detailRes.data ?? detailRes
|
||||
} else {
|
||||
selectedDetail.value = { ...row }
|
||||
}
|
||||
} catch {
|
||||
selectedDetail.value = { ...row }
|
||||
}
|
||||
} else {
|
||||
// source='list' 或未配置:直接用行数据
|
||||
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()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 分栏拖拽
|
||||
// ============================================================
|
||||
const { splitStackRef, beginSplitDrag, lowerPaneStyle, upperPaneStyle } =
|
||||
useVerticalSplitPane({ defaultLowerPercent: 38 })
|
||||
|
||||
const upperPaneFullStyle = computed(() => ({
|
||||
flex: '1 1 auto',
|
||||
minHeight: '0',
|
||||
overflow: 'hidden' as const
|
||||
}))
|
||||
|
||||
// ============================================================
|
||||
// 初始化
|
||||
// ============================================================
|
||||
onMounted(() => {
|
||||
loadData()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
/* ================================================================
|
||||
整体布局
|
||||
================================================================ */
|
||||
.page-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
1. 顶部多标签页
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
2. 主内容区
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
.order-sub-container {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
background-color: #f0f2f5;
|
||||
|
||||
:deep(.scan-box-container) {
|
||||
flex: 0 0 220px;
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 10px;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tab-content-inner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
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;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tab-fade-enter-from,
|
||||
.tab-fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
7. 空状态
|
||||
================================================================ */
|
||||
.empty-tip {
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
@ -1,107 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -23,6 +23,7 @@ import {
|
||||
parseOrderDetailPayload,
|
||||
parseOrderListResponse
|
||||
} from '@/views/order/orderManagement/utils/order-index-helpers'
|
||||
import { resolveRowBarcode } from '@/utils/barcode'
|
||||
|
||||
/** ScanBox 筛选字段分组(波次模块专用,策略/散单候选等页仍可使用) */
|
||||
export const WAVE_SCAN_FIELD_GROUPS = {
|
||||
@ -1608,6 +1609,8 @@ function mapPendingOrderItemsToPrintDetails(items: Record<string, unknown>[]) {
|
||||
const itemCode = resolvePrintLineField(item, snap, 'item_code')
|
||||
const itemName = resolvePrintLineField(item, snap, 'item_name')
|
||||
const unitPrice = resolvePrintLineField(item, snap, 'actual_price', 'retail_price', 'price', 'unit_price')
|
||||
// 商品条码:模板「商品明细」条码列(field_code=barcode)取值,兼容 barcode 单值与 barcodes 数组
|
||||
const barcode = resolveRowBarcode(item, snap)
|
||||
|
||||
return {
|
||||
item_snapshot: {
|
||||
@ -1619,7 +1622,7 @@ function mapPendingOrderItemsToPrintDetails(items: Record<string, unknown>[]) {
|
||||
},
|
||||
item_code: itemCode,
|
||||
item_name: itemName,
|
||||
barcode: resolvePrintLineField(item, snap, 'barcode'),
|
||||
barcode: barcode || SNAPSHOT_EMPTY_LABEL,
|
||||
sku_property: resolvePrintLineField(item, snap, 'sku_property', 'ext_code'),
|
||||
goods_code: resolvePrintLineField(item, snap, 'goods_code'),
|
||||
brand_name: resolvePrintLineField(item, snap, 'brand_name'),
|
||||
|
||||
@ -98,7 +98,7 @@ import FallbackOrderListPanel from './FallbackOrderListPanel.vue'
|
||||
import WaveStrategyListPanel from './WaveStrategyListPanel.vue'
|
||||
import WavePickTaskListPanel from './WavePickTaskListPanel.vue'
|
||||
import { safeInvoke } from '@/utils/safe-invoke'
|
||||
import { orderWaveConfirmPrintScan, orderWaveConfirmPrintUnclaimedWaveCount } from '@/api/order.wave/orderwave'
|
||||
import { orderWaveConfirmPrintScan, orderWaveConfirmPrintUnclaimedWaveCount } from '@/api/order/order'
|
||||
import { useBarcodeScan } from '@/composables/useBarcodeScan'
|
||||
import { WAVE_PAGE_CONFIG } from './config/wave-config'
|
||||
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
<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/waveorder-config'
|
||||
import { TAG_RESOLVERS, translate, formatTime } from '../config/waveorder-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>
|
||||
@ -1,141 +0,0 @@
|
||||
<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: () => [
|
||||
{ name: 'tab1', label: '标签页一' },
|
||||
{ name: 'tab2', label: '标签页二' },
|
||||
{ name: 'tab3', label: '标签页三' },
|
||||
{ name: 'tab4', label: '标签页四' },
|
||||
{ name: 'tab5', label: '标签页五' }
|
||||
],
|
||||
defaultActive: 'tab1'
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'tab-change', tabName: string): void
|
||||
}>()
|
||||
|
||||
const activeTab = ref(props.defaultActive)
|
||||
|
||||
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>
|
||||
@ -1,168 +0,0 @@
|
||||
<template>
|
||||
<div class="wave-order2-detail">
|
||||
<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, formatTime } from '../../config/waveorder-config'
|
||||
import type { DetailSectionConfig, DetailFieldConfig } from '../../config/waveorder-config'
|
||||
|
||||
defineOptions({ name: 'WaveOrder2DetailPanel' })
|
||||
|
||||
const props = defineProps<{
|
||||
row: Record<string, any> | null
|
||||
/** 明细区域配置(由各页面在 waveorder-config.ts 中配置) */
|
||||
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({
|
||||
wave_id: newRow.wave_id ?? newRow.id,
|
||||
wave_no: newRow.wave_no
|
||||
})
|
||||
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 翻译,然后 format 格式化,否则显示原始值 */
|
||||
function resolveDisplayValue(field: DetailFieldConfig, value: any): string {
|
||||
if (field.translateField) {
|
||||
return translate(field.translateField, value)
|
||||
}
|
||||
if (field.format === 'datetime') {
|
||||
return formatTime(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>
|
||||
.wave-order2-detail {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
font-size: 14px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 16px;
|
||||
|
||||
&: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>
|
||||
@ -1,204 +0,0 @@
|
||||
<template>
|
||||
<div class="log-panel">
|
||||
<div class="section-title">操作日志</div>
|
||||
<div 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' })
|
||||
|
||||
const props = defineProps<{
|
||||
/** 当前选中行数据(用于生成关联日志) */
|
||||
row: Record<string, any> | null
|
||||
/** 可选的日志 API 方法,传入后自动调用获取真实日志 */
|
||||
apiMethod?: (...args: any[]) => Promise<any>
|
||||
}>()
|
||||
|
||||
/** 通过 API 获取的真实日志列表 */
|
||||
const apiLogs = ref<any[] | null>(null)
|
||||
const apiLoading = ref(false)
|
||||
|
||||
watch(() => props.row, async (newRow) => {
|
||||
if (newRow && props.apiMethod) {
|
||||
apiLoading.value = true
|
||||
try {
|
||||
const res = await props.apiMethod({
|
||||
wave_id: newRow.wave_id ?? newRow.id,
|
||||
wave_no: newRow.wave_no,
|
||||
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 : []
|
||||
} else {
|
||||
apiLogs.value = []
|
||||
}
|
||||
} catch {
|
||||
apiLogs.value = []
|
||||
} finally {
|
||||
apiLoading.value = false
|
||||
}
|
||||
} else {
|
||||
apiLogs.value = null
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
/** 基于 row 生成模拟日志(无 apiMethod 时使用) */
|
||||
const mockLogs = computed(() => {
|
||||
if (!props.row) return []
|
||||
const id = props.row.id ?? 0
|
||||
const waveNo = props.row.wave_no ?? props.row.order_no ?? `#${id}`
|
||||
const operators = ['张三', '李四', '系统']
|
||||
const logTemplates = [
|
||||
{ action: '创建波次', result: '成功', detail: `波次 ${waveNo} 创建成功,包含 ${props.row.total_orders ?? props.row.sku_count ?? 0} 个订单` },
|
||||
{ action: '分配库位', result: id % 3 === 0 ? '成功' : '部分成功', detail: id % 3 === 0 ? '所有订单库位分配完成' : '部分订单库位不足,等待人工处理' },
|
||||
{ action: '分配快递', result: '成功', detail: `已为波次分配快递资源` },
|
||||
{ action: '打印面单', result: id % 2 === 0 ? '成功' : '进行中', detail: id % 2 === 0 ? '面单打印完成' : '面单打印中,已完成 60%' },
|
||||
{ action: '开始拣货', result: '成功', detail: `拣货任务已下发` },
|
||||
{ action: '完成拣货', result: id % 4 === 0 ? '成功' : '等待中', detail: id % 4 === 0 ? '拣货完成,等待复核' : '' },
|
||||
{ action: '复核通过', result: id % 5 === 0 ? '成功' : '等待中', detail: id % 5 === 0 ? '复核已通过' : '' },
|
||||
{ action: '发货出库', result: id % 7 === 0 ? '成功' : '等待中', detail: id % 7 === 0 ? '已出库' : '' }
|
||||
]
|
||||
|
||||
const startTime = new Date(props.row.create_time ?? Date.now())
|
||||
return logTemplates.map((tpl, i) => {
|
||||
const logTime = new Date(startTime.getTime() + i * 1800000 + (id % 60) * 60000)
|
||||
return {
|
||||
...tpl,
|
||||
operator: operators[i % operators.length],
|
||||
time: logTime.toISOString().replace('T', ' ').slice(0, 19),
|
||||
level: tpl.result === '成功' ? 'success' : tpl.result === '失败' ? 'error' : 'warning'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
/** 最终展示的日志:优先使用 API 日志,否则使用 mock 日志 */
|
||||
const logs = computed(() => {
|
||||
if (apiLogs.value !== null) {
|
||||
return apiLogs.value.map((log: any) => ({
|
||||
operator: log.operator_name ?? log.operator ?? log.creator_name ?? '—',
|
||||
action: log.operation_name ?? log.action ?? log.operation ?? '—',
|
||||
result: log.status === 'success' || log.result === '成功' ? '成功' : log.result ?? '—',
|
||||
detail: log.message ?? log.detail ?? '',
|
||||
time: log.created_at ?? log.create_time ?? log.time ?? '—',
|
||||
level: log.level ?? 'info'
|
||||
}))
|
||||
}
|
||||
return mockLogs.value
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.log-panel {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
margin-bottom: 12px;
|
||||
padding-left: 8px;
|
||||
border-left: 3px solid #409eff;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.log-timeline {
|
||||
position: relative;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.log-item {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px dashed #ebeef5;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.log-dot {
|
||||
flex-shrink: 0;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
margin-top: 6px;
|
||||
|
||||
&.success {
|
||||
background: #67c23a;
|
||||
box-shadow: 0 0 4px rgba(103, 194, 58, 0.4);
|
||||
}
|
||||
&.warning {
|
||||
background: #e6a23c;
|
||||
box-shadow: 0 0 4px rgba(230, 162, 60, 0.4);
|
||||
}
|
||||
&.error {
|
||||
background: #f56c6c;
|
||||
box-shadow: 0 0 4px rgba(245, 108, 108, 0.4);
|
||||
}
|
||||
&.info {
|
||||
background: #909399;
|
||||
}
|
||||
}
|
||||
|
||||
.log-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.log-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.log-operator {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.log-action {
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.log-detail {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
margin-top: 4px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.log-time {
|
||||
font-size: 12px;
|
||||
color: #c0c4cc;
|
||||
margin-top: 2px;
|
||||
}
|
||||
</style>
|
||||
@ -1,171 +0,0 @@
|
||||
<!--
|
||||
OperationCellRenderer — 表格操作列渲染组件
|
||||
|
||||
根据 operationButtons 配置渲染按钮列表。
|
||||
|
||||
支持的行为类型:
|
||||
- actionType='action' → 触发 @operation-action 事件(可选配置 confirmMessage 弹确认框)
|
||||
- actionType='form' → 打开 COMPONENT_REGISTRY 中注册的表单组件
|
||||
|
||||
paramMap 配置说明(actionType='form' 时):
|
||||
{ "wave_id": "wave_id", "wave_no": "wave_no" }
|
||||
→ 从行数据中取 row.wave_id → 注入表单 prop wave_id
|
||||
-->
|
||||
<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/waveorder-config'
|
||||
import type { OperationButtonConfig } from '../../config/waveorder-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>>({})
|
||||
/** 已解析的表单组件缓存(key: 按钮 key) */
|
||||
const resolvedFormComponents = ref<Record<string, Component>>({})
|
||||
/** action 按钮 loading 状态(key: 按钮 key) */
|
||||
const actionLoadingMap = reactive<Record<string, boolean>>({})
|
||||
|
||||
// ============================================================
|
||||
// action 按钮:支持确认弹窗
|
||||
// ============================================================
|
||||
|
||||
/** 处理 action 类型按钮点击(如有 confirmMessage 则先弹确认框) */
|
||||
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 // 用户取消
|
||||
}
|
||||
}
|
||||
|
||||
// 设置 loading 并触发事件
|
||||
actionLoadingMap[btn.key] = true
|
||||
emit('operation-action', btn.key, props.row)
|
||||
// 立即清除 loading(实际异步操作由父组件管理)
|
||||
actionLoadingMap[btn.key] = false
|
||||
}
|
||||
|
||||
/** 解析按钮对应的表单组件 */
|
||||
function resolveFormComponent(btn: OperationButtonConfig) {
|
||||
if (!btn.formKey) return undefined
|
||||
// 先在 COMPONENT_REGISTRY 中查找
|
||||
const comp = COMPONENT_REGISTRY[btn.formKey]
|
||||
if (comp) return comp
|
||||
// 未找到时输出警告
|
||||
console.warn(`[OperationCellRenderer] 组件 "${btn.formKey}" 未在 COMPONENT_REGISTRY 中注册`)
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 构建表单 props(根据 paramMap 从行数据提取) */
|
||||
function buildFormProps(btn: OperationButtonConfig): Record<string, any> {
|
||||
const formProps: Record<string, any> = {}
|
||||
if (btn.paramMap) {
|
||||
for (const [propName, rowField] of Object.entries(btn.paramMap)) {
|
||||
formProps[propName] = props.row[rowField]
|
||||
}
|
||||
}
|
||||
if (btn.extraParams) {
|
||||
Object.assign(formProps, btn.extraParams)
|
||||
}
|
||||
return formProps
|
||||
}
|
||||
|
||||
/** 打开表单弹窗 */
|
||||
function openForm(btn: OperationButtonConfig) {
|
||||
const resolved = resolveFormComponent(btn)
|
||||
if (!resolved) return
|
||||
|
||||
resolvedFormComponents.value[btn.key] = resolved
|
||||
activeFormKey.value = btn.key
|
||||
formVisibleMap[btn.key] = true
|
||||
}
|
||||
|
||||
/** 表单操作成功后回调 */
|
||||
function handleFormSuccess(key: string) {
|
||||
formVisibleMap[key] = false
|
||||
activeFormKey.value = ''
|
||||
// 通知父组件刷新等
|
||||
emit('operation-action', key, props.row)
|
||||
}
|
||||
|
||||
/** 按钮禁用判断 */
|
||||
function isDisabled(btn: OperationButtonConfig): boolean {
|
||||
if (!btn.disabledOnField) return false
|
||||
return !props.row[btn.disabledOnField]
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.operation-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,971 +0,0 @@
|
||||
<template>
|
||||
<div class="order-management-wrapper" :style="{ height: containerHeight }">
|
||||
<!-- ===== 多标签模式:显示顶部多标签页 ===== -->
|
||||
<template v-if="WAVEORDER2_PAGE_CONFIG.showTabArea && !WAVEORDER2_PAGE_CONFIG.singlePage">
|
||||
<div class="tab-section">
|
||||
<TabArea
|
||||
:tabs="tabList"
|
||||
:default-active="activeTabName"
|
||||
@tab-change="handleTabChange"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ===== 标签页隐藏时的提示条 ===== -->
|
||||
<!-- <div
|
||||
v-if="!WAVEORDER2_PAGE_CONFIG.showTabArea && !WAVEORDER2_PAGE_CONFIG.singlePage"
|
||||
class="tab-hidden-bar"
|
||||
>
|
||||
<span class="tab-hidden-hint">多标签页区域已隐藏</span>
|
||||
</div> -->
|
||||
|
||||
<!-- ===== 主内容区(结构与 waveOrder 子面板完全一致) ===== -->
|
||||
<div class="tab-container main-container">
|
||||
<div class="order-sub-container">
|
||||
<scan-box
|
||||
ref="scanBoxRef"
|
||||
:cache-key="currentScanBoxCacheKey"
|
||||
width="220px"
|
||||
: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">
|
||||
<order-toolbar-button-group
|
||||
:buttons="currentToolbarButtons"
|
||||
:resolve-disabled="resolveButtonDisabled"
|
||||
:resolve-loading="resolveButtonLoading"
|
||||
:resolve-label="resolveButtonLabel"
|
||||
:layout-key="toolbarLayoutKey"
|
||||
@action="handleToolbarButtonClick"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 上下分栏区域:详情面板启用时才显示分栏 + 详情 -->
|
||||
<template v-if="WAVEORDER2_PAGE_CONFIG.enableDetailPanel">
|
||||
<div class="split-stack" ref="splitStackRef">
|
||||
<div class="upper-wrapper" :style="detailVisible ? upperPaneStyle : upperPaneFullStyle">
|
||||
<upper-table
|
||||
ref="upperTableRef"
|
||||
:title="currentTabConfig?.upperTable.title ?? '列表'"
|
||||
default-align="center"
|
||||
:enable-column-config="currentTabConfig?.upperTable.enableColumnConfig ?? true"
|
||||
:column-config-schema-version="1"
|
||||
:table-id="`wave-order2-table-${activeTabName}`"
|
||||
:data="listData"
|
||||
:row-key="'wave_no'"
|
||||
:columns="currentColumns"
|
||||
table-size="small"
|
||||
:pagination="pagination"
|
||||
:show-index="currentTabConfig?.upperTable.showIndex ?? true"
|
||||
:show-selection="currentTabConfig?.upperTable.showSelection ?? true"
|
||||
: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"
|
||||
>
|
||||
<!-- 动态列插槽:根据列配置的 columnSlots 自动渲染 -->
|
||||
<template
|
||||
v-for="(slotConfig, colProp) in currentColumnSlots"
|
||||
:key="`${columnSlotsKey}-${colProp}`"
|
||||
#[`column-${colProp}`]="{ row }"
|
||||
>
|
||||
<!-- 操作列:渲染操作按钮 -->
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<!-- 其他列:标签/文本渲染 -->
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</upper-table>
|
||||
</div>
|
||||
|
||||
<template v-if="detailVisible">
|
||||
<div
|
||||
class="pane-resizer"
|
||||
title="拖动调整列表与详情区域高度"
|
||||
@mousedown="beginSplitDrag"
|
||||
/>
|
||||
<div v-if="selectedRow" class="lower-level" :style="lowerPaneStyle">
|
||||
<div class="detail-header">
|
||||
<el-tabs v-model="activeDetailTab" class="detail-tab">
|
||||
<el-tab-pane
|
||||
v-for="tab in currentDetailTabs"
|
||||
:key="tab.name"
|
||||
:label="tab.label"
|
||||
:name="tab.name"
|
||||
/>
|
||||
</el-tabs>
|
||||
</div>
|
||||
<div class="detail-container">
|
||||
<component
|
||||
:is="activeDetailTabComponent"
|
||||
:row="selectedDetail"
|
||||
:detail-config="currentDetailConfig"
|
||||
:api-method="currentDetailTabApiMethod"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="no-selection" :style="lowerPaneStyle">
|
||||
<div class="empty-tip">
|
||||
<p>请从上方列表中选择一项查看详情</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 详情面板禁用:表格占满全高 -->
|
||||
<template v-else>
|
||||
<div class="upper-wrapper upper-wrapper--full">
|
||||
<upper-table
|
||||
ref="upperTableRef"
|
||||
:title="currentTabConfig?.upperTable.title ?? '列表'"
|
||||
default-align="center"
|
||||
:enable-column-config="currentTabConfig?.upperTable.enableColumnConfig ?? true"
|
||||
:column-config-schema-version="1"
|
||||
:table-id="`wave-order2-table-${activeTabName}`"
|
||||
:data="listData"
|
||||
:row-key="'wave_no'"
|
||||
: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="`${columnSlotsKey}-${colProp}`"
|
||||
#[`column-${colProp}`]="{ row }"
|
||||
>
|
||||
<OperationCellRenderer
|
||||
v-if="slotConfig.type === 'operation'"
|
||||
:buttons="currentTabConfig?.operationButtons"
|
||||
:row="row"
|
||||
@operation-action="handleOperationAction"
|
||||
/>
|
||||
<ColumnCellRenderer
|
||||
v-else
|
||||
:config="slotConfig"
|
||||
:value="row[colProp]"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">{{ currentTabConfig?.upperTable.emptyText ?? '暂无数据' }}</div>
|
||||
</template>
|
||||
</upper-table>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 功能按钮表单(pages/ 目录下的组件) ===== -->
|
||||
<FetchGroupOrderForm
|
||||
v-model:visible="fetchGroupOrderFormVisible"
|
||||
@success="handleFormSuccess"
|
||||
/>
|
||||
|
||||
<BatchOperationForm
|
||||
v-model:visible="batchOperationFormVisible"
|
||||
:config="batchOperationConfig"
|
||||
:selected-ids="batchOperationSelectedIds"
|
||||
:selected-rows="selectedRows"
|
||||
:extracted-payload="batchOperationExtractedPayload"
|
||||
@success="handleFormSuccess"
|
||||
/>
|
||||
|
||||
<!-- ===== 待处理订单弹窗 ===== -->
|
||||
<el-dialog
|
||||
v-model="pendingOrderDialogVisible"
|
||||
:title="pendingOrderDialogTitle"
|
||||
width="92vw"
|
||||
destroy-on-close
|
||||
append-to-body
|
||||
align-center
|
||||
@closed="handlePendingOrderDialogClosed"
|
||||
>
|
||||
<PendingOrderListPanel
|
||||
v-if="pendingOrderDialogVisible && pendingOrderDialogWaveNo"
|
||||
:wave-no="pendingOrderDialogWaveNo"
|
||||
/>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, reactive } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import { useVerticalSplitPane } from '@/composables/useVerticalSplitPane'
|
||||
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 OperationCellRenderer from './components/public/OperationCellRenderer.vue'
|
||||
import PendingOrderListPanel from '@/views/order/waveOrder/component/PendingOrderListPanel.vue'
|
||||
import { resolveWavePickCompleteWaveId } from '@/views/order/waveOrder/composables/useWavePickComplete'
|
||||
import { pickWavePickComplete } from '@/api/pick/pick'
|
||||
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
|
||||
import type { ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
|
||||
import FetchGroupOrderForm from './pages/FetchGroupOrderForm.vue'
|
||||
import BatchOperationForm from './pages/BatchOperationForm.vue'
|
||||
import {
|
||||
WAVEORDER2_PAGE_CONFIG,
|
||||
waveOrder2Tabs,
|
||||
waveOrder2TabPages,
|
||||
resolveTabConfig,
|
||||
getTabToolbarButtons,
|
||||
BATCH_OPERATION_CONFIGS
|
||||
} from './config/waveorder-config'
|
||||
import type {
|
||||
TabPageConfig,
|
||||
DetailTabConfig,
|
||||
WaveOrder2ToolbarButtonConfig,
|
||||
BatchOperationConfig
|
||||
} from './config/waveorder-config'
|
||||
|
||||
defineOptions({ name: 'WaveOrder2' })
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
// ===== 容器高度(与 waveOrder 一致) =====
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
const containerHeight = computed(() => {
|
||||
return shortcutExpanded.value
|
||||
? 'calc(100vh - 150px)'
|
||||
: 'calc(100vh - 100px)'
|
||||
})
|
||||
|
||||
// ===== 标签页 =====
|
||||
const tabList = ref(waveOrder2Tabs.map((t) => ({ name: t.name, label: t.label })))
|
||||
const activeTabName = ref(waveOrder2Tabs[0]?.name ?? 'tab1')
|
||||
|
||||
/** 当前激活标签页的完整配置(运行时由 resolveTabConfig 展开 key 引用) */
|
||||
const currentTabConfig = computed<TabPageConfig | undefined>(() => {
|
||||
const raw = waveOrder2TabPages.find((t) => t.name === activeTabName.value)
|
||||
if (!raw) return undefined
|
||||
return resolveTabConfig(raw)
|
||||
})
|
||||
|
||||
/** 当前标签页的 ScanBox 缓存 key */
|
||||
const currentScanBoxCacheKey = computed(() => {
|
||||
return currentTabConfig.value?.scanBoxCacheKey ?? 'wave-order2-default'
|
||||
})
|
||||
|
||||
/** 当前标签页的 ScanBox 筛选字段 */
|
||||
const currentScanBoxFields = computed(() => {
|
||||
return currentTabConfig.value?.scanBoxFields ?? []
|
||||
})
|
||||
|
||||
/** 当前标签页的表格列 */
|
||||
const currentColumns = computed(() => {
|
||||
return currentTabConfig.value?.upperTable.columns ?? []
|
||||
})
|
||||
|
||||
/** 当前标签页的列插槽配置 */
|
||||
const currentColumnSlots = computed(() => {
|
||||
return currentTabConfig.value?.columnSlots ?? {}
|
||||
})
|
||||
|
||||
/** 当前标签页的明细面板配置 */
|
||||
const currentDetailConfig = computed(() => {
|
||||
return currentTabConfig.value?.detailConfig ?? []
|
||||
})
|
||||
|
||||
/** 当前标签页的明细标签页列表 */
|
||||
const currentDetailTabs = computed<DetailTabConfig[]>(() => {
|
||||
return currentTabConfig.value?.detailTabs ?? []
|
||||
})
|
||||
|
||||
/** 当前激活的明细标签页对应的组件 */
|
||||
const activeDetailTabComponent = computed(() => {
|
||||
const tab = currentDetailTabs.value.find((t) => t.name === activeDetailTab.value)
|
||||
return tab?.component ?? null
|
||||
})
|
||||
|
||||
/** 当前激活明细标签页对应的 API 方法(函数=source='api',对象=source='list'返回 undefined) */
|
||||
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
|
||||
|
||||
// 根据 componentKey 匹配对应的 API 配置
|
||||
let componentCfg: unknown
|
||||
switch (tab.componentKey) {
|
||||
case 'DetailPanel':
|
||||
componentCfg = cfg.api.detail
|
||||
break
|
||||
case 'LogPanel':
|
||||
componentCfg = cfg.api.log
|
||||
break
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
|
||||
// 函数 → 直接返回作为 apiMethod;对象 { source:'list' } → 组件用行数据
|
||||
if (typeof componentCfg === 'function') {
|
||||
return componentCfg
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
|
||||
|
||||
// ============================================================
|
||||
// 工具栏按钮系统(参照 orderManagement 设计)
|
||||
// ============================================================
|
||||
|
||||
/** 当前标签页的工具栏按钮列表(从 WAVEORDER2_TOOLBAR_BUTTONS 获取) */
|
||||
const currentToolbarButtons = computed<ToolbarButtonConfig[]>(() => {
|
||||
const btns = getTabToolbarButtons(activeTabName.value)
|
||||
return btns.map((btn: WaveOrder2ToolbarButtonConfig) => ({
|
||||
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,
|
||||
exportLoading: false,
|
||||
batchAutoGroupingLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAutoGrouping',
|
||||
batchFinishAutoGroupingLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchFinishAutoGrouping',
|
||||
batchCancelLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchCancel',
|
||||
batchAllocateExpressLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAllocateExpress',
|
||||
batchAllocateStorageLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchAllocateStorage',
|
||||
batchRemoveExceptionOrdersLoading: batchOpLoading.value && currentBatchOpAction.value === 'batchRemoveExceptionOrders'
|
||||
}))
|
||||
|
||||
/** 按钮动态标签映射 */
|
||||
const buttonLabelMap = computed<Record<string, string>>(() => ({
|
||||
detailToggleLabel: detailVisible.value ? '隐藏详情' : '显示详情'
|
||||
}))
|
||||
|
||||
/** 工具栏布局 key(变化时触发 OrderToolbarButtonGroup 重排) */
|
||||
const toolbarLayoutKey = computed(() =>
|
||||
JSON.stringify({
|
||||
loading: buttonLoadingMap.value,
|
||||
disabled: buttonDisabledMap.value,
|
||||
labels: buttonLabelMap.value
|
||||
})
|
||||
)
|
||||
|
||||
function resolveButtonLoading(loadingKey?: string) {
|
||||
if (!loadingKey) return false
|
||||
return Boolean(buttonLoadingMap.value[loadingKey])
|
||||
}
|
||||
|
||||
function resolveButtonDisabled(disabledKey?: string) {
|
||||
if (!disabledKey) return false
|
||||
return Boolean(buttonDisabledMap.value[disabledKey])
|
||||
}
|
||||
|
||||
function resolveButtonLabel(defaultLabel: string, dynamicLabelKey?: string) {
|
||||
if (!dynamicLabelKey) return defaultLabel
|
||||
return buttonLabelMap.value[dynamicLabelKey] || defaultLabel
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 工具栏动作分发
|
||||
// ============================================================
|
||||
|
||||
/** 基础工具栏动作映射 */
|
||||
const toolbarActionMap: Record<string, () => void> = {
|
||||
loadData: () => { void loadData() },
|
||||
openColumnConfigPanel: () => { upperTableRef.value?.openColumnConfig?.() },
|
||||
toggleDetailVisible: () => { detailVisible.value = !detailVisible.value },
|
||||
handleExportWaybill: () => { console.log('[WaveOrder2] 导出(不含明细)', activeTabName.value) },
|
||||
handleExportItem: () => { console.log('[WaveOrder2] 导出(含明细)', activeTabName.value) }
|
||||
}
|
||||
|
||||
/** 统一工具栏按钮点击处理 */
|
||||
function handleToolbarButtonClick(action: ToolbarButtonConfig['action']) {
|
||||
const handler = toolbarActionMap[action]
|
||||
if (handler) {
|
||||
handler()
|
||||
return
|
||||
}
|
||||
// 功能按钮:打开对应表单
|
||||
handleFunctionButtonAction(action)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 操作列按钮事件处理
|
||||
// ============================================================
|
||||
|
||||
/** 操作列 action 按钮回调 */
|
||||
async function handleOperationAction(key: string, row: Record<string, any>) {
|
||||
switch (key) {
|
||||
case 'handleOrders':
|
||||
openPendingOrdersByWave(row)
|
||||
break
|
||||
case 'batchPick':
|
||||
// confirm 已在 OperationCellRenderer 中处理
|
||||
await handleWavePickComplete(row)
|
||||
break
|
||||
default:
|
||||
console.warn('[WaveOrder2] 未处理的操作按钮:', key)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 处理订单 — 打开待处理订单弹窗
|
||||
// ============================================================
|
||||
|
||||
const pendingOrderDialogVisible = ref(false)
|
||||
const pendingOrderDialogWaveNo = ref('')
|
||||
const pendingOrderDialogTitle = computed(() =>
|
||||
pendingOrderDialogWaveNo.value
|
||||
? `待处理订单 - ${pendingOrderDialogWaveNo.value}`
|
||||
: '待处理订单'
|
||||
)
|
||||
|
||||
function openPendingOrdersByWave(row: Record<string, any>) {
|
||||
const waveNo = String(row?.wave_no || '').trim()
|
||||
if (!waveNo) {
|
||||
ElMessage.warning('当前波次缺少波次号')
|
||||
return
|
||||
}
|
||||
pendingOrderDialogWaveNo.value = waveNo
|
||||
pendingOrderDialogVisible.value = true
|
||||
}
|
||||
|
||||
function handlePendingOrderDialogClosed() {
|
||||
pendingOrderDialogWaveNo.value = ''
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 批量拣货 — 调用拣货接口
|
||||
// ============================================================
|
||||
|
||||
async function handleWavePickComplete(row: Record<string, any>) {
|
||||
const waveId = resolveWavePickCompleteWaveId(row)
|
||||
if (!waveId) {
|
||||
ElMessage.warning('当前波次缺少可用的波次 ID')
|
||||
return
|
||||
}
|
||||
|
||||
const waveNo = String(row?.wave_no ?? row?.wave_code ?? waveId).trim()
|
||||
|
||||
try {
|
||||
const res = (await pickWavePickComplete({ wave_id: waveId })) as Record<string, any>
|
||||
if (res?.code !== undefined && res?.code !== null && res?.code !== 1 && res?.code !== 200 && res?.code !== 0) {
|
||||
throw new Error(res?.message || res?.tip || '批量拣货失败')
|
||||
}
|
||||
ElMessage.success(`波次「${waveNo}」批量拣货已完成`)
|
||||
loadData()
|
||||
} catch (e: any) {
|
||||
if (e?.message && e?.message !== 'cancel') {
|
||||
ElMessage.error(e?.message || '批量拣货失败')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 功能按钮表单状态
|
||||
// ============================================================
|
||||
|
||||
/** 团购单抓取表单 */
|
||||
const fetchGroupOrderFormVisible = ref(false)
|
||||
|
||||
/** 批量操作表单 */
|
||||
const batchOperationFormVisible = ref(false)
|
||||
const batchOperationConfig = ref<BatchOperationConfig | null>(null)
|
||||
const batchOperationSelectedIds = ref<string[] | number[]>([])
|
||||
/** 多字段提取结果(idField 为数组时使用),直接作为请求体 */
|
||||
const batchOperationExtractedPayload = ref<Record<string, any[]> | null>(null)
|
||||
const batchOpLoading = ref(false)
|
||||
const currentBatchOpAction = ref('')
|
||||
|
||||
/** 功能按钮 action → 表单打开逻辑 */
|
||||
function handleFunctionButtonAction(action: string) {
|
||||
switch (action) {
|
||||
case 'openFetchGroupOrderForm':
|
||||
openFetchGroupOrderForm()
|
||||
break
|
||||
case 'openBatchAutoGroupingForm':
|
||||
case 'openBatchFinishAutoGroupingForm':
|
||||
case 'openBatchCancelForm':
|
||||
case 'openBatchAllocateExpressForm':
|
||||
case 'openBatchAllocateStorageForm':
|
||||
case 'openBatchRemoveExceptionOrdersForm':
|
||||
openBatchOperationForm(action)
|
||||
break
|
||||
default:
|
||||
console.warn('[WaveOrder2] 未处理的工具栏动作:', action)
|
||||
}
|
||||
}
|
||||
|
||||
function openFetchGroupOrderForm() {
|
||||
fetchGroupOrderFormVisible.value = true
|
||||
}
|
||||
|
||||
function openBatchOperationForm(action: string) {
|
||||
if (!selectedRows.value.length) {
|
||||
ElMessage.warning('请先选择波次')
|
||||
return
|
||||
}
|
||||
|
||||
// 根据 action 推导对应的批量操作 key
|
||||
const opKey = action.replace('open', '').replace('Form', '')
|
||||
// openBatchAutoGroupingForm → BatchAutoGrouping → batchAutoGrouping
|
||||
const configKey = opKey.charAt(0).toLowerCase() + opKey.slice(1)
|
||||
|
||||
const cfg = BATCH_OPERATION_CONFIGS[configKey]
|
||||
if (!cfg) {
|
||||
console.warn('[WaveOrder2] 未找到批量操作配置:', configKey)
|
||||
return
|
||||
}
|
||||
|
||||
currentBatchOpAction.value = cfg.action
|
||||
batchOperationConfig.value = { ...cfg }
|
||||
|
||||
const idField = cfg.idField ?? 'wave_id'
|
||||
|
||||
if (Array.isArray(idField)) {
|
||||
// 多字段模式:提取所有字段,组装为 { field1: [...], field2: [...] }
|
||||
const payload: Record<string, any[]> = {}
|
||||
for (const field of idField) {
|
||||
payload[field] = []
|
||||
}
|
||||
for (const row of selectedRows.value) {
|
||||
for (const field of idField) {
|
||||
const val = (row as any)[field]
|
||||
payload[field]!.push(val !== undefined && val !== null ? val : null)
|
||||
}
|
||||
}
|
||||
batchOperationExtractedPayload.value = payload
|
||||
// selectedIds 用第一个字段的值供 UI 展示
|
||||
const firstField = idField[0]
|
||||
batchOperationSelectedIds.value = firstField ? (payload[firstField]?.filter((v: any) => v !== null) ?? []) : []
|
||||
} else {
|
||||
// 单字段模式(支持逗号分隔 fallback)
|
||||
batchOperationExtractedPayload.value = null
|
||||
const idFields = (idField as string).split(',').map((f: string) => f.trim())
|
||||
batchOperationSelectedIds.value = selectedRows.value
|
||||
.map((r: any) => {
|
||||
for (const field of idFields) {
|
||||
const val = r[field]
|
||||
if (val !== undefined && val !== null && val !== '') return val
|
||||
}
|
||||
return null
|
||||
})
|
||||
.filter((v: any) => v !== null)
|
||||
}
|
||||
batchOperationFormVisible.value = true
|
||||
}
|
||||
|
||||
/** 表单操作成功后刷新列表 */
|
||||
function handleFormSuccess() {
|
||||
selectedRows.value = []
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
/** 切换标签页时重置状态并加载新数据 */
|
||||
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()
|
||||
}
|
||||
|
||||
// ===== ScanBox =====
|
||||
const scanBoxRef = ref<any>(null)
|
||||
const presetTree = ref<any[]>([])
|
||||
|
||||
const handleConditionChange = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handleConditionReset = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handleConditionClear = () => {
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
function handleSortChange({ prop, order }: any) {
|
||||
currentSort.prop = prop
|
||||
currentSort.order = order
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ===== 列表数据 =====
|
||||
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 && (res.code === 1 || res.code === 200)) {
|
||||
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('[WaveOrder2] 加载列表失败:', e)
|
||||
ElMessage.error(e?.message || '获取列表数据失败')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
queryTime.value = Math.round(performance.now() - startTime)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
pagination.currentPage = page
|
||||
loadData()
|
||||
}
|
||||
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
pagination.pageSize = size
|
||||
pagination.currentPage = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ===== UpperTable =====
|
||||
const upperTableRef = ref<any>(null)
|
||||
const selectedRows = ref<Record<string, any>[]>([])
|
||||
|
||||
const handleSelectionChange = (rows: Record<string, any>[]) => {
|
||||
selectedRows.value = rows
|
||||
}
|
||||
|
||||
// ===== 明细面板 =====
|
||||
const detailVisible = ref(WAVEORDER2_PAGE_CONFIG.enableDetailPanel)
|
||||
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 (!WAVEORDER2_PAGE_CONFIG.enableDetailPanel) return
|
||||
|
||||
const cfg = currentTabConfig.value
|
||||
if (!cfg) return
|
||||
selectedRow.value = row
|
||||
|
||||
// 根据 DetailPanel 的 api 配置决定数据来源
|
||||
const detailCfg = cfg.api?.detail
|
||||
// 直接传函数 = source='api'(与 list 字段写法一致)
|
||||
if (typeof detailCfg === 'function') {
|
||||
try {
|
||||
const detailRes = await detailCfg({ wave_id: row.wave_id ?? row.id, wave_no: row.wave_no })
|
||||
if (detailRes && (detailRes.code === 1 || detailRes.code === 200)) {
|
||||
selectedDetail.value = detailRes.data ?? detailRes
|
||||
return
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[WaveOrder2] 获取明细失败,使用列表行数据:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// source='list' 或 API 失败:直接使用列表行数据
|
||||
selectedDetail.value = { ...row }
|
||||
}
|
||||
|
||||
// ===== 分栏拖拽(使用 useVerticalSplitPane,与 waveOrder 一致) =====
|
||||
const { splitStackRef, beginSplitDrag, lowerPaneStyle, upperPaneStyle } = useVerticalSplitPane({
|
||||
defaultLowerPercent: 38
|
||||
})
|
||||
|
||||
const upperPaneFullStyle = computed(() => ({
|
||||
flex: '1 1 auto',
|
||||
minHeight: '0',
|
||||
overflow: 'hidden' as const
|
||||
}))
|
||||
|
||||
// ===== 初始化 & 标签页切换时重新加载 =====
|
||||
onMounted(() => {
|
||||
loadData()
|
||||
})
|
||||
|
||||
// 当 currentTabConfig 变化(如列配置变更)时,列插槽的 key 也会变,触发重新渲染
|
||||
const columnSlotsKey = computed(() => {
|
||||
return `${activeTabName.value}-${Object.keys(currentColumnSlots.value).join(',')}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
/* ===== 引入 waveOrder 共享样式(scan-box / toolbar / split-stack / pane-resizer / lower-level 等) ===== */
|
||||
@use "../orderManagement/styles/order-sub.scss";
|
||||
|
||||
/* ================================================================
|
||||
整体布局容器
|
||||
================================================================ */
|
||||
.order-management-wrapper {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
1. 顶部多标签页区域(抽离组件)
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
.tab-hidden-bar {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 4px 16px;
|
||||
background: #fff;
|
||||
border: 1px dashed #dcdfe6;
|
||||
border-bottom: none;
|
||||
border-radius: 6px 6px 0 0;
|
||||
|
||||
.tab-hidden-hint {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
2. 主内容区容器
|
||||
================================================================ */
|
||||
.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;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
3. ScanBox"筛选/过滤"标签样式(对齐页面顶部 TabArea 风格)
|
||||
================================================================ */
|
||||
.main-container {
|
||||
: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;
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
补充:工具栏信息文字
|
||||
================================================================ */
|
||||
.toolbar-info {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
补充:空提示样式
|
||||
================================================================ */
|
||||
.empty-tip {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
无选中行时的占位(与 waveOrder 保持一致)
|
||||
================================================================ */
|
||||
.no-selection {
|
||||
flex: 0 0 38%;
|
||||
height: 38%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-top: 1px solid #ebeef5;
|
||||
overflow: hidden;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
标签页切换过渡动画
|
||||
================================================================ */
|
||||
.main-content {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tab-content-inner {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* fade + slide 混合过渡 */
|
||||
.tab-fade-enter-active,
|
||||
.tab-fade-leave-active {
|
||||
transition: opacity 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.tab-fade-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
|
||||
.tab-fade-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
.tab-fade-leave-active {
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
}
|
||||
</style>
|
||||
@ -1,246 +0,0 @@
|
||||
<!--
|
||||
BatchOperationForm — 批量操作表单(确认弹窗)
|
||||
|
||||
支持的批量操作:
|
||||
- batchAutoGrouping 批量改为自动加团
|
||||
- batchFinishAutoGrouping 批量结束自动加团
|
||||
- batchCancel 批量取消波次
|
||||
- batchAllocateExpress 快速分配快递号
|
||||
- batchAllocateStorage 批量分配储位
|
||||
- batchRemoveExceptionOrders 批量移除异常订单
|
||||
|
||||
使用方式:index.vue 中通过 v-model:visible 控制显示,
|
||||
:config 传入对应的 BatchOperationConfig。
|
||||
-->
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="visible"
|
||||
:title="config?.title ?? '确认操作'"
|
||||
width="480px"
|
||||
align-center
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<div class="batch-op-body">
|
||||
<el-alert
|
||||
:type="config?.confirmType ?? 'warning'"
|
||||
:closable="false"
|
||||
show-icon
|
||||
:title="confirmMessage"
|
||||
/>
|
||||
<div class="batch-op-info">
|
||||
<span>已选波次数:<strong>{{ selectedIds.length }}</strong></span>
|
||||
<div v-if="selectedIds.length <= 10" class="batch-op-ids">
|
||||
{{ selectedIds.join('、') }}
|
||||
</div>
|
||||
</div>
|
||||
<!-- 进度显示 -->
|
||||
<template v-if="showProgress">
|
||||
<el-divider />
|
||||
<div class="batch-op-progress">
|
||||
<el-progress
|
||||
:percentage="progressPercent"
|
||||
:status="progressStatus"
|
||||
:stroke-width="16"
|
||||
/>
|
||||
<p class="batch-op-progress-text">
|
||||
{{ progressLabel }}
|
||||
<template v-if="resultCount > 0">
|
||||
(已完成 {{ resultCount }} 个波次)
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button size="small" @click="handleClosed">取消</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
:type="config?.confirmType === 'error' ? 'danger' : 'primary'"
|
||||
:loading="submitting"
|
||||
:disabled="showProgress && progressStatus === 'success'"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
{{ config?.confirmButtonText ?? '确认' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { BatchOperationConfig } from '../config/waveorder-config'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
config: BatchOperationConfig | null
|
||||
selectedIds: string[] | number[]
|
||||
/** 完整的选中行数据,供 payloadBuilder 使用 */
|
||||
selectedRows?: Record<string, any>[]
|
||||
/** 多字段提取结果(idField 配置为数组时),直接作为请求体 */
|
||||
extractedPayload?: Record<string, any[]> | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', v: boolean): void
|
||||
(e: 'success'): void
|
||||
}>()
|
||||
|
||||
const submitting = ref(false)
|
||||
const showProgress = ref(false)
|
||||
const progressPercent = ref(0)
|
||||
const progressStatus = ref<'success' | 'exception' | 'warning' | ''>('')
|
||||
const progressLabel = ref('')
|
||||
const resultCount = ref(0)
|
||||
|
||||
let pollingTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const confirmMessage = computed(() => {
|
||||
if (!props.config) return ''
|
||||
return props.config.confirmText.replace('{count}', String(props.selectedIds.length))
|
||||
})
|
||||
|
||||
function handleClosed() {
|
||||
stopPolling()
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollingTimer) {
|
||||
clearInterval(pollingTimer)
|
||||
pollingTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 重置内部状态 */
|
||||
function reset() {
|
||||
submitting.value = false
|
||||
showProgress.value = false
|
||||
progressPercent.value = 0
|
||||
progressStatus.value = ''
|
||||
progressLabel.value = ''
|
||||
resultCount.value = 0
|
||||
stopPolling()
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(v) => {
|
||||
if (!v) reset()
|
||||
}
|
||||
)
|
||||
|
||||
/** 开始轮询任务进度 */
|
||||
function startProgressPolling(taskId: string | number) {
|
||||
if (!props.config?.progressApiMethod) return
|
||||
showProgress.value = true
|
||||
progressStatus.value = ''
|
||||
progressLabel.value = '任务处理中…'
|
||||
|
||||
pollingTimer = setInterval(async () => {
|
||||
try {
|
||||
const res = await props.config!.progressApiMethod!({ task_id: taskId })
|
||||
const data = res?.data ?? res
|
||||
const status = data?.status ?? data?.task_status ?? ''
|
||||
const percent = Number(data?.progress ?? data?.progress_percent ?? 0)
|
||||
|
||||
progressPercent.value = Math.min(100, Math.round(percent))
|
||||
|
||||
if (status === 'success' || status === 'completed' || status === 'fin' || percent >= 100) {
|
||||
progressStatus.value = 'success'
|
||||
progressLabel.value = '任务已完成'
|
||||
resultCount.value = Number(data?.success_count ?? data?.total ?? 0)
|
||||
stopPolling()
|
||||
} else if (status === 'failed' || status === 'error') {
|
||||
progressStatus.value = 'exception'
|
||||
progressLabel.value = data?.message ?? '任务执行失败'
|
||||
stopPolling()
|
||||
} else {
|
||||
progressLabel.value = data?.message ?? `处理中… ${percent}%`
|
||||
}
|
||||
} catch {
|
||||
// 忽略轮询错误
|
||||
}
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (submitting.value) return
|
||||
if (!props.config) return
|
||||
if (!props.selectedIds.length) {
|
||||
ElMessage.warning('没有可操作的波次')
|
||||
return
|
||||
}
|
||||
|
||||
const cfg = props.config
|
||||
submitting.value = true
|
||||
try {
|
||||
// 1. payloadBuilder 最高优先:完全自定义
|
||||
// 2. extractedPayload 次之:多字段自动提取结果
|
||||
// 3. 兜底:payloadKey + selectedIds 单字段拼接
|
||||
const payload = cfg.payloadBuilder
|
||||
? cfg.payloadBuilder(props.selectedRows ?? [])
|
||||
: props.extractedPayload
|
||||
? { ...props.extractedPayload }
|
||||
: { [cfg.payloadKey ?? 'ids']: props.selectedIds }
|
||||
const res = await cfg.apiMethod(payload)
|
||||
|
||||
const ok = res && (res.code === 1 || res.code === 200 || res.flag === 'success')
|
||||
if (!ok) {
|
||||
ElMessage.error(res?.message || cfg.failText)
|
||||
return
|
||||
}
|
||||
|
||||
// 如果配置了进度轮询
|
||||
const taskId = res?.data?.task_id
|
||||
if (cfg.useProgress && taskId) {
|
||||
ElMessage.success(cfg.successText)
|
||||
startProgressPolling(taskId)
|
||||
} else {
|
||||
const count = Number(res?.data?.updated_count ?? props.selectedIds.length) || 0
|
||||
ElMessage.success(`${cfg.successText}(${count} 个波次)`)
|
||||
emit('success')
|
||||
handleClosed()
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error(cfg.failText)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
if (!showProgress.value) {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.batch-op-body {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.batch-op-info {
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.batch-op-ids {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.batch-op-progress {
|
||||
.batch-op-progress-text {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -1,556 +0,0 @@
|
||||
<!--
|
||||
FetchGroupOrderForm — 抓取团购单表单
|
||||
|
||||
对应 waveOrder 中 GroupWaveBatchListPanel 的团购单抓取对话框。
|
||||
提供货主筛选、最小同组订单数、店铺名称、包含SKU、区分快递等条件,
|
||||
查询可抓取的团购单结构并提交抓取。
|
||||
-->
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="visible"
|
||||
title="抓取团购单"
|
||||
width="1280px"
|
||||
align-center
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<div class="fetch-group-order-body">
|
||||
<!-- 筛选区域 -->
|
||||
<el-form :inline="true" size="small" class="fetch-filters">
|
||||
<el-form-item label="货主">
|
||||
<el-select
|
||||
v-model="filters.storeId"
|
||||
placeholder="全部"
|
||||
clearable
|
||||
filterable
|
||||
style="width: 180px"
|
||||
@change="handleFilterChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="store in storeOptions"
|
||||
:key="String(store.value)"
|
||||
:label="store.label"
|
||||
:value="store.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="最小同组订单数">
|
||||
<el-input-number
|
||||
v-model="filters.sameOrderQuantity"
|
||||
:min="1"
|
||||
:controls="false"
|
||||
style="width: 150px"
|
||||
@change="handleFilterChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="店铺名称">
|
||||
<el-input
|
||||
v-model="filters.shopName"
|
||||
clearable
|
||||
placeholder="模糊匹配店铺名称"
|
||||
style="width: 180px"
|
||||
@keyup.enter="fetchList"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="包含 SKU">
|
||||
<el-input
|
||||
v-model="filters.includeSku"
|
||||
clearable
|
||||
placeholder="仅保留包含该 SKU 的分组"
|
||||
style="width: 180px"
|
||||
@keyup.enter="fetchList"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-switch
|
||||
v-model="filters.distinguishExpress"
|
||||
active-text="区分快递"
|
||||
inactive-text="不区分快递"
|
||||
@change="handleFilterChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="listLoading" @click="fetchList">查询</el-button>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<!-- 工具栏 -->
|
||||
<div class="fetch-toolbar">
|
||||
<div class="fetch-toolbar__left">
|
||||
<span>已选 {{ selectionRows.length }} 个结构</span>
|
||||
</div>
|
||||
<el-checkbox v-model="filters.returnOrderIds">返回订单 ID 列表</el-checkbox>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<el-table
|
||||
ref="tableRef"
|
||||
:data="list"
|
||||
v-loading="listLoading"
|
||||
border
|
||||
size="small"
|
||||
row-key="item_detail_machine"
|
||||
max-height="400"
|
||||
@selection-change="handleSelectionChange"
|
||||
>
|
||||
<el-table-column type="selection" width="48" reserve-selection />
|
||||
<el-table-column prop="item_detail" label="商品结构" min-width="260" show-overflow-tooltip />
|
||||
<el-table-column prop="logistics_name" label="快递" min-width="130" show-overflow-tooltip />
|
||||
<el-table-column prop="group_count" label="同组订单数" min-width="100" align="right" />
|
||||
<el-table-column prop="items_total" label="商品总数" min-width="100" align="right" />
|
||||
<el-table-column label="货主" min-width="110">
|
||||
<template #default="{ row }">
|
||||
{{ getGroupOrderStoreText(row) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态汇总" min-width="240">
|
||||
<template #default="{ row }">
|
||||
<span class="status-summary-text">{{ getGroupOrderStatusSummary(row) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="商品快照" min-width="280">
|
||||
<template #default="{ row }">
|
||||
<span class="order-info-text">{{ getGroupOrderItemSnapshotText(row) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="首单时间" min-width="168">
|
||||
<template #default="{ row }">
|
||||
{{ formatTime(row.first_order_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="末单时间" min-width="168">
|
||||
<template #default="{ row }">
|
||||
{{ formatTime(row.last_order_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template #empty>
|
||||
<div class="empty-tip">暂无可抓取的团购单结构</div>
|
||||
</template>
|
||||
</el-table>
|
||||
|
||||
<!-- 分页 -->
|
||||
<div class="fetch-pagination">
|
||||
<el-pagination
|
||||
v-model:current-page="pagination.currentPage"
|
||||
v-model:page-size="pagination.pageSize"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:total="pagination.total"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
background
|
||||
size="small"
|
||||
@size-change="handlePageSizeChange"
|
||||
@current-change="handlePageChange"
|
||||
/>
|
||||
</div>
|
||||
</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'
|
||||
import {
|
||||
orderWaveGroupOrderFetchList,
|
||||
orderWaveGroupFetch
|
||||
} from '@/api/order.wave/orderwave'
|
||||
import type {
|
||||
WaveGroupOrderFetchListResponse,
|
||||
WaveFetchResponse
|
||||
} from '@/api/order.wave/orderwave'
|
||||
import { loadStores } from '@/api/index/index'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
/** 查询接口(可选覆盖,默认 orderWaveGroupOrderFetchList) */
|
||||
fetchListApi?: (...args: any[]) => Promise<any>
|
||||
/** 提交抓取接口(可选覆盖,默认 orderWaveGroupFetch) */
|
||||
submitApi?: (...args: any[]) => Promise<any>
|
||||
/** 货主选项(可选覆盖,默认自动加载) */
|
||||
storeOptions?: Array<{ label: string; value: any }>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:visible', v: boolean): void
|
||||
(e: 'success'): void
|
||||
}>()
|
||||
|
||||
const filters = reactive({
|
||||
distinguishExpress: true,
|
||||
storeId: undefined as number | string | undefined,
|
||||
sameOrderQuantity: undefined as number | undefined,
|
||||
shopName: '',
|
||||
includeSku: '',
|
||||
returnOrderIds: false
|
||||
})
|
||||
|
||||
const storeOptions = ref<Array<{ label: string; value: any }>>([])
|
||||
|
||||
const list = ref<any[]>([])
|
||||
const listLoading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const selectionRows = ref<any[]>([])
|
||||
|
||||
const pagination = reactive({
|
||||
currentPage: 1,
|
||||
pageSize: 20,
|
||||
total: 0
|
||||
})
|
||||
|
||||
/** 判断响应码是否成功 */
|
||||
const okCode = (code: unknown) => code === 1 || code === 200 || code === 0
|
||||
|
||||
// ============================================================
|
||||
// 辅助函数(对齐 waveOrder GroupWaveBatchListPanel)
|
||||
// ============================================================
|
||||
|
||||
/** 获取团购单货主文本 */
|
||||
function getGroupOrderStoreText(row: any) {
|
||||
if (Array.isArray(row?.store_ids) && row.store_ids.length > 1) {
|
||||
return row.store_ids.join(',')
|
||||
}
|
||||
return (row?.store_name || row?.store_short_name || row?.store_id) ?? row?.store_ids?.[0] ?? '—'
|
||||
}
|
||||
|
||||
/** 获取团购单状态汇总 */
|
||||
function getGroupOrderStatusSummary(row: any) {
|
||||
const summary = row?.status_summary || {}
|
||||
const parts = [
|
||||
`配货未开始 ${summary.pick_none ?? 0}`,
|
||||
`配货完成 ${summary.pick_fin ?? 0}`,
|
||||
`出库未开始 ${summary.outbound_none ?? 0}`,
|
||||
`出库完成 ${summary.outbound_fin ?? 0}`
|
||||
]
|
||||
return parts.join(' / ')
|
||||
}
|
||||
|
||||
/** 获取团购单商品快照文本 */
|
||||
function getGroupOrderItemSnapshotText(row: any) {
|
||||
if (typeof row?.item_detail === 'string' && row.item_detail) {
|
||||
return row.item_detail
|
||||
}
|
||||
if (Array.isArray(row?.item_snapshot) && row.item_snapshot.length) {
|
||||
return row.item_snapshot
|
||||
.map((item: any) => `${item.item_name || item.item_code || item.barcode || '未知商品'} x ${item.quantity ?? 0}`)
|
||||
.join(' | ')
|
||||
}
|
||||
return row?.item_detail_machine_snapshot || '—'
|
||||
}
|
||||
|
||||
/** 格式化时间戳 */
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 货主选项加载(参照 GroupWaveBatchListPanel.loadGroupOrderStoreOptions)
|
||||
// ============================================================
|
||||
|
||||
async function loadStoreOptions() {
|
||||
if (props.storeOptions?.length) {
|
||||
storeOptions.value = props.storeOptions
|
||||
return
|
||||
}
|
||||
if (storeOptions.value.length > 0) return
|
||||
try {
|
||||
const res: any = await loadStores()
|
||||
const stores = Array.isArray(res?.stores) ? res.stores : []
|
||||
storeOptions.value = stores.map((item: any) => ({
|
||||
label: item.label || item.name || String(item.value || item.id),
|
||||
value: item.value ?? item.id
|
||||
}))
|
||||
} catch (error) {
|
||||
console.error('[FetchGroupOrderForm] 加载货主列表失败:', error)
|
||||
storeOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// 监听外部传入的 storeOptions
|
||||
watch(
|
||||
() => props.storeOptions,
|
||||
(val) => {
|
||||
if (val && val.length) storeOptions.value = val
|
||||
}
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// 构建查询参数(对齐 waveOrder buildStructureFetchListPayload)
|
||||
// ============================================================
|
||||
|
||||
function buildListPayload(): Record<string, any> {
|
||||
const payload: Record<string, any> = {
|
||||
pagination: {
|
||||
page: pagination.currentPage,
|
||||
pageSize: pagination.pageSize
|
||||
},
|
||||
distinguish_express: filters.distinguishExpress,
|
||||
return_order_ids: filters.returnOrderIds
|
||||
}
|
||||
if (filters.storeId !== undefined && filters.storeId !== null && filters.storeId !== '') {
|
||||
payload.store_id = Number(filters.storeId)
|
||||
}
|
||||
if (filters.sameOrderQuantity !== undefined && filters.sameOrderQuantity !== null) {
|
||||
payload.same_order_quantity = Number(filters.sameOrderQuantity)
|
||||
}
|
||||
if (filters.shopName.trim()) {
|
||||
payload.shop_name = filters.shopName.trim()
|
||||
}
|
||||
if (filters.includeSku.trim()) {
|
||||
payload.include_sku = filters.includeSku.trim()
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 查询列表(对齐 waveOrder fetchGroupOrderList)
|
||||
// ============================================================
|
||||
|
||||
async function fetchList() {
|
||||
listLoading.value = true
|
||||
try {
|
||||
const fetchApi = props.fetchListApi ?? orderWaveGroupOrderFetchList
|
||||
const res = await fetchApi(buildListPayload()) as
|
||||
WaveGroupOrderFetchListResponse & { code?: number; message?: string; data?: Partial<WaveGroupOrderFetchListResponse> }
|
||||
|
||||
if (!res || !okCode(res.code)) {
|
||||
throw new Error(res?.message || '获取可抓取团购单列表失败')
|
||||
}
|
||||
|
||||
const responseList = Array.isArray(res.list)
|
||||
? res.list
|
||||
: Array.isArray(res.data?.list)
|
||||
? res.data.list
|
||||
: []
|
||||
const responsePagination = res.pagination || res.data?.pagination || {}
|
||||
|
||||
list.value = responseList
|
||||
pagination.currentPage = responsePagination.page || pagination.currentPage
|
||||
pagination.pageSize = responsePagination.pageSize || pagination.pageSize
|
||||
pagination.total = responsePagination.total || 0
|
||||
} catch (error: any) {
|
||||
console.error('[FetchGroupOrderForm] 获取列表失败:', error)
|
||||
list.value = []
|
||||
pagination.total = 0
|
||||
ElMessage.error(error?.message || '获取可抓取团购单列表失败')
|
||||
} finally {
|
||||
listLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 筛选 & 分页
|
||||
// ============================================================
|
||||
|
||||
function handleClosed() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function handleFilterChange() {
|
||||
pagination.currentPage = 1
|
||||
fetchList()
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.distinguishExpress = true
|
||||
filters.storeId = undefined
|
||||
filters.sameOrderQuantity = undefined
|
||||
filters.shopName = ''
|
||||
filters.includeSku = ''
|
||||
filters.returnOrderIds = false
|
||||
pagination.currentPage = 1
|
||||
selectionRows.value = []
|
||||
fetchList()
|
||||
}
|
||||
|
||||
function handleSelectionChange(rows: any[]) {
|
||||
selectionRows.value = rows
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
fetchList()
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
pagination.currentPage = 1
|
||||
fetchList()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 提交抓取(对齐 waveOrder submitGroupOrderDialog)
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* 解析抓取接口返回的 fetch_state,给出对应提示
|
||||
* (对齐 GroupWaveBatchListPanel.applyWaveStrategyFetchUiResult)
|
||||
*/
|
||||
function applyFetchResult(
|
||||
payload: WaveFetchResponse & { code?: number; message?: string; tip?: string },
|
||||
successHint?: string
|
||||
) {
|
||||
const fs = (payload as any).fetch_state
|
||||
|
||||
// 验证错误
|
||||
const validationErrors = (payload as any).validation_errors
|
||||
if (Array.isArray(validationErrors) && validationErrors.length) {
|
||||
const detail = validationErrors
|
||||
.map((e: any) => [e?.field, e?.message].filter(Boolean).join(': ') || '')
|
||||
.filter(Boolean)
|
||||
.join(';')
|
||||
ElMessage.warning(detail || payload?.message || '入参校验未通过')
|
||||
return false
|
||||
}
|
||||
|
||||
// fetch_state === 2 → 失败
|
||||
if (fs === 2) {
|
||||
ElMessage.warning((payload as any).tip || payload?.message || '抓取任务创建失败')
|
||||
return false
|
||||
}
|
||||
|
||||
// fetch_state === 3 → 已有进行中任务
|
||||
if (fs === 3) {
|
||||
const taskNo = String((payload as any).task_no ?? (payload as any).existing_task_no ?? '')
|
||||
const taskId = String(payload.task_id ?? (payload as any).existing_task_id ?? '')
|
||||
const tip = (payload as any).tip || payload?.message || '存在未完成的抓取任务'
|
||||
const suffix = [taskNo ? `任务编号:${taskNo}` : '', taskId ? `任务ID:${taskId}` : ''].filter(Boolean).join(',')
|
||||
ElMessage.success(suffix ? `${tip}(${suffix})` : tip)
|
||||
emit('success')
|
||||
handleClosed()
|
||||
return true
|
||||
}
|
||||
|
||||
// fetch_state === 1 或 undefined → 成功创建
|
||||
if (fs === 1 || fs === undefined || fs === null) {
|
||||
const taskId = String(payload?.task_id ?? '')
|
||||
const taskNo = String((payload as any).task_no ?? '')
|
||||
const planSummary = String((payload as any).plan_summary ?? '')
|
||||
const hint = planSummary || payload?.message || successHint || '抓取任务已创建'
|
||||
const suffix = [taskNo ? `任务编号:${taskNo}` : '', taskId ? `任务ID:${taskId}` : ''].filter(Boolean).join(',')
|
||||
ElMessage.success(suffix ? `${hint}(${suffix})` : hint)
|
||||
emit('success')
|
||||
handleClosed()
|
||||
return true
|
||||
}
|
||||
|
||||
ElMessage.warning(payload?.message || `未知抓取状态(fetch_state=${String(fs)})`)
|
||||
return false
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!selectionRows.value.length) {
|
||||
ElMessage.warning('请先勾选要抓取的结构')
|
||||
return
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const submitApi = props.submitApi ?? orderWaveGroupFetch
|
||||
const structureList = selectionRows.value.map((row: any) => ({
|
||||
item_detail_machine: String(row?.item_detail_machine || '')
|
||||
}))
|
||||
|
||||
const res = await submitApi({ structure_list: structureList }) as
|
||||
WaveFetchResponse & { code?: number; message?: string; tip?: string }
|
||||
|
||||
if (!res || !okCode(res.code)) {
|
||||
throw new Error(res?.message || '抓取团购单失败')
|
||||
}
|
||||
|
||||
// 处理 fetch_state 逻辑
|
||||
applyFetchResult(res, '抓取任务已创建')
|
||||
} catch (error: any) {
|
||||
console.error('[FetchGroupOrderForm] 提交抓取失败:', error)
|
||||
ElMessage.error(error?.message || '抓取团购单失败')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 打开时自动加载
|
||||
// ============================================================
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(v) => {
|
||||
if (v) {
|
||||
filters.distinguishExpress = true
|
||||
filters.returnOrderIds = false
|
||||
pagination.currentPage = 1
|
||||
selectionRows.value = []
|
||||
loadStoreOptions()
|
||||
fetchList()
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.fetch-group-order-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.fetch-filters {
|
||||
flex-shrink: 0;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
}
|
||||
|
||||
.fetch-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 0;
|
||||
|
||||
&__left {
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
}
|
||||
}
|
||||
|
||||
.fetch-pagination {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
padding: 24px 0;
|
||||
}
|
||||
|
||||
.status-summary-text {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: normal;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.order-info-text {
|
||||
font-size: 12px;
|
||||
color: #606266;
|
||||
white-space: normal;
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@ -1,4 +1,5 @@
|
||||
import type { ToolbarButtonConfig } from '@/views/order/orderManagement/config/order-common-config'
|
||||
import { resolveRowBarcode } from '@/utils/barcode'
|
||||
|
||||
/** 出库单列表主工具栏按钮(action 与 stockout/index.vue 内 toolbarActionMap 键一致)
|
||||
* 排序与样式分类对齐 storage/receiving:
|
||||
@ -340,15 +341,32 @@ export const productColumns = [
|
||||
{ prop: 'remark', label: '备注', minWidth: '120' }
|
||||
]
|
||||
|
||||
/** item_snapshot 兼容对象与 JSON 字符串两种返回形态 */
|
||||
function resolvePrintItemSnapshot(raw: unknown): Record<string, any> {
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw as Record<string, any>
|
||||
if (typeof raw === 'string' && raw.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, any>
|
||||
}
|
||||
} catch {
|
||||
// 忽略非法 JSON,按无快照处理
|
||||
}
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
||||
export function formatStockoutListItems(list: any[] = []) {
|
||||
return (list || []).map(item => {
|
||||
const snap = item.item_snapshot || {}
|
||||
const snap = resolvePrintItemSnapshot(item.item_snapshot)
|
||||
return {
|
||||
...item,
|
||||
item_code: item.item_code || snap.item_code || '',
|
||||
item_name: item.item_name || snap.item_name || '',
|
||||
sku_property: item.sku_property ?? snap.sku_property ?? '',
|
||||
barcode: item.barcode ?? snap.barcode ?? '',
|
||||
// 商品条码:模板「商品明细」条码列(field_code=barcode)取值,兼容 barcode 单值与 barcodes 数组
|
||||
barcode: resolveRowBarcode(item, snap),
|
||||
stock_unit: item.stock_unit ?? snap.stock_unit ?? '',
|
||||
actual_qty: item.actual_qty ?? item.actual_quantity ?? '',
|
||||
batch_no: item.batch_no ?? '',
|
||||
|
||||
@ -1,756 +0,0 @@
|
||||
<!--
|
||||
ApiOpenInterface — API 开放接口管理
|
||||
管理 API 应用的创建、编辑、停用、密钥管理等。
|
||||
-->
|
||||
<template>
|
||||
<div class="api-open-interface">
|
||||
<!-- ===== 工具栏 ===== -->
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-input
|
||||
v-model="searchForm.app_name"
|
||||
placeholder="搜索应用名称"
|
||||
clearable
|
||||
style="width: 220px"
|
||||
size="default"
|
||||
@keyup.enter="handleSearch"
|
||||
@clear="handleSearch"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Search /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select
|
||||
v-model="searchForm.is_enabled"
|
||||
placeholder="启用状态"
|
||||
clearable
|
||||
style="width: 140px"
|
||||
size="default"
|
||||
@change="handleSearch"
|
||||
>
|
||||
<el-option label="全部" :value="undefined" />
|
||||
<el-option label="已启用" :value="1" />
|
||||
<el-option label="已停用" :value="0" />
|
||||
</el-select>
|
||||
<el-button type="primary" size="default" @click="handleSearch">
|
||||
<el-icon><Search /></el-icon>
|
||||
查询
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="toolbar-right">
|
||||
<el-button size="default" @click="loadData">
|
||||
<el-icon><Refresh /></el-icon>
|
||||
刷新
|
||||
</el-button>
|
||||
<el-button type="primary" size="default" @click="openCreateDialog">
|
||||
<el-icon><Plus /></el-icon>
|
||||
创建应用
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 数据表格 ===== -->
|
||||
<el-table
|
||||
v-loading="loading"
|
||||
:data="listData"
|
||||
border
|
||||
stripe
|
||||
size="default"
|
||||
style="width: 100%"
|
||||
empty-text="暂无 API 应用数据"
|
||||
>
|
||||
<el-table-column prop="id" label="ID" width="70" align="center" />
|
||||
<el-table-column prop="app_name" label="应用名称" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column label="AppKey" min-width="200" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono-text">{{ row.self_app_key }}</span>
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
style="margin-left: 4px"
|
||||
@click="handleCopy(row.self_app_key, 'AppKey')"
|
||||
>
|
||||
复制
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="AppSecret" min-width="160" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<span class="mono-text">{{ row.self_app_secret || '****' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="sign_method" label="签名方法" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" type="info">{{ row.sign_method?.toUpperCase() || 'MD5' }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="rate_limit" label="速率限制" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
{{ row.rate_limit ?? 1000 }} 次/秒
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="is_enabled" label="状态" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" :type="row.is_enabled === 1 ? 'success' : 'danger'">
|
||||
{{ row.is_enabled === 1 ? '启用' : '停用' }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间" width="170" align="center">
|
||||
<template #default="{ row }">
|
||||
{{ formatTime(row.created_at) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="260" align="center" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" size="small" @click="openDetailDialog(row)">
|
||||
详情
|
||||
</el-button>
|
||||
<el-button link type="primary" size="small" @click="openEditDialog(row)">
|
||||
编辑
|
||||
</el-button>
|
||||
<el-button link type="warning" size="small" @click="handleRegenerateSecret(row)">
|
||||
重置密钥
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.is_enabled === 1"
|
||||
link
|
||||
type="danger"
|
||||
size="small"
|
||||
@click="handleDelete(row)"
|
||||
>
|
||||
停用
|
||||
</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<!-- ===== 分页 ===== -->
|
||||
<div class="pagination-wrap">
|
||||
<el-pagination
|
||||
v-model:current-page="pagination.page"
|
||||
v-model:page-size="pagination.pageSize"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:total="pagination.total"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
@size-change="handleSizeChange"
|
||||
@current-change="handlePageChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- ===== 创建/编辑对话框 ===== -->
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
:title="dialogMode === 'create' ? '创建 API 应用' : '编辑 API 应用'"
|
||||
width="600px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
align-center
|
||||
>
|
||||
<el-form
|
||||
ref="formRef"
|
||||
:model="formData"
|
||||
:rules="formRules"
|
||||
label-width="120px"
|
||||
label-position="right"
|
||||
>
|
||||
<el-form-item label="应用名称" prop="app_name">
|
||||
<el-input
|
||||
v-model="formData.app_name"
|
||||
placeholder="请输入应用名称"
|
||||
:maxlength="200"
|
||||
show-word-limit
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="速率限制">
|
||||
<el-input-number
|
||||
v-model="formData.rate_limit"
|
||||
:min="1"
|
||||
:max="100000"
|
||||
:precision="0"
|
||||
controls-position="right"
|
||||
style="width: 100%"
|
||||
/>
|
||||
<span class="unit-text">次/秒</span>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="回调 URL">
|
||||
<el-input
|
||||
v-model="formData.callback_url"
|
||||
placeholder="接收推送通知的 URL,如 https://example.com/webhook"
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="IP 白名单">
|
||||
<div class="ip-whitelist">
|
||||
<el-tag
|
||||
v-for="(ip, idx) in formData.self_ip_whitelist"
|
||||
:key="idx"
|
||||
closable
|
||||
class="ip-tag"
|
||||
@close="handleRemoveFormIp(idx)"
|
||||
>
|
||||
{{ ip }}
|
||||
</el-tag>
|
||||
<el-input
|
||||
v-if="formIpInputVisible"
|
||||
ref="formIpInputRef"
|
||||
v-model="formIpInputValue"
|
||||
size="small"
|
||||
style="width: 160px"
|
||||
placeholder="IP 或 CIDR"
|
||||
@blur="handleAddFormIp"
|
||||
@keyup.enter="handleAddFormIp"
|
||||
/>
|
||||
<el-button v-else size="small" @click="showFormIpInput">+ 添加 IP</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-if="dialogMode === 'edit'" label="启用状态">
|
||||
<el-switch
|
||||
v-model="formData.is_enabled"
|
||||
:active-value="1"
|
||||
:inactive-value="0"
|
||||
active-text="启用"
|
||||
inactive-text="停用"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<!-- 创建成功后显示密钥信息 -->
|
||||
<template v-if="createdSecret">
|
||||
<el-divider />
|
||||
<el-alert
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
title="请立即保存以下密钥信息,关闭后 AppSecret 将不再完整显示!"
|
||||
/>
|
||||
<div class="secret-display">
|
||||
<div class="secret-row">
|
||||
<span class="secret-label">AppKey:</span>
|
||||
<code class="secret-value">{{ createdSecret.self_app_key }}</code>
|
||||
<el-button link type="primary" size="small" @click="handleCopy(createdSecret.self_app_key, 'AppKey')">
|
||||
复制
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="secret-row">
|
||||
<span class="secret-label">AppSecret:</span>
|
||||
<code class="secret-value secret-highlight">{{ createdSecret.self_app_secret }}</code>
|
||||
<el-button link type="primary" size="small" @click="handleCopy(createdSecret.self_app_secret, 'AppSecret')">
|
||||
复制
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="handleSubmit">
|
||||
{{ dialogMode === 'create' ? '创建' : '保存' }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- ===== 详情对话框 ===== -->
|
||||
<el-dialog
|
||||
v-model="detailVisible"
|
||||
title="API 应用详情"
|
||||
width="600px"
|
||||
:close-on-click-modal="false"
|
||||
align-center
|
||||
>
|
||||
<el-descriptions v-if="detailData" :column="2" border size="default">
|
||||
<el-descriptions-item label="应用 ID">{{ detailData.id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="应用名称">{{ detailData.app_name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="AppKey" :span="2">
|
||||
<code>{{ detailData.self_app_key }}</code>
|
||||
<el-button link type="primary" size="small" style="margin-left: 8px" @click="handleCopy(detailData.self_app_key, 'AppKey')">
|
||||
复制
|
||||
</el-button>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="AppSecret" :span="2">
|
||||
<code>{{ detailData.self_app_secret || '****' }}</code>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="签名方法">
|
||||
<el-tag size="small" type="info">{{ detailData.sign_method?.toUpperCase() || 'MD5' }}</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="速率限制">{{ detailData.rate_limit ?? 1000 }} 次/秒</el-descriptions-item>
|
||||
<el-descriptions-item label="启用状态">
|
||||
<el-tag size="small" :type="detailData.is_enabled === 1 ? 'success' : 'danger'">
|
||||
{{ detailData.is_enabled === 1 ? '已启用' : '已停用' }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="接口类型">{{ detailData.interface_type_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="仓库 ID">{{ detailData.warehouse_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="回调 URL" :span="2">
|
||||
{{ detailData.callback_url || '—' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="IP 白名单" :span="2">
|
||||
<template v-if="detailData.self_ip_whitelist?.length">
|
||||
<el-tag v-for="(ip, i) in detailData.self_ip_whitelist" :key="i" size="small" style="margin: 2px 4px 2px 0">
|
||||
{{ ip }}
|
||||
</el-tag>
|
||||
</template>
|
||||
<span v-else>—</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ formatTime(detailData.created_at) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="更新时间">{{ formatTime(detailData.updated_at) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, nextTick, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
|
||||
import {
|
||||
apiAppList,
|
||||
apiAppCreate,
|
||||
apiAppUpdate,
|
||||
apiAppDelete,
|
||||
apiAppDetail,
|
||||
apiAppRegenerateSecret,
|
||||
type ApiAppItem,
|
||||
type ApiAppFlatResponse
|
||||
} from '@/api/apiapp/apiapp'
|
||||
|
||||
defineOptions({ name: 'ApiOpenInterface' })
|
||||
|
||||
// ============================================================
|
||||
// 表格数据
|
||||
// ============================================================
|
||||
const loading = ref(false)
|
||||
const listData = ref<ApiAppItem[]>([])
|
||||
const pagination = reactive({
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
total: 0
|
||||
})
|
||||
|
||||
const searchForm = reactive({
|
||||
app_name: '',
|
||||
is_enabled: undefined as number | undefined
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// 数据加载
|
||||
// ============================================================
|
||||
const SUCCESS_CODES = [200, 20000, 1, 0]
|
||||
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const res = await apiAppList({
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
app_name: searchForm.app_name || undefined,
|
||||
is_enabled: searchForm.is_enabled
|
||||
})
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
ElMessage.error(res.message || '查询失败')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
return
|
||||
}
|
||||
listData.value = res.list ?? []
|
||||
pagination.total = res.pagination?.total ?? 0
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '查询异常')
|
||||
listData.value = []
|
||||
pagination.total = 0
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSearch() {
|
||||
pagination.page = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.page = page
|
||||
loadData()
|
||||
}
|
||||
|
||||
function handleSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
pagination.page = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 创建 / 编辑对话框
|
||||
// ============================================================
|
||||
const dialogVisible = ref(false)
|
||||
const dialogMode = ref<'create' | 'edit'>('create')
|
||||
const submitting = ref(false)
|
||||
const editingId = ref<number | null>(null)
|
||||
const formRef = ref()
|
||||
const createdSecret = ref<ApiAppFlatResponse | null>(null)
|
||||
|
||||
interface FormData {
|
||||
app_name: string
|
||||
rate_limit: number
|
||||
callback_url: string
|
||||
self_ip_whitelist: string[]
|
||||
is_enabled: number
|
||||
}
|
||||
|
||||
const formData = reactive<FormData>({
|
||||
app_name: '',
|
||||
rate_limit: 1000,
|
||||
callback_url: '',
|
||||
self_ip_whitelist: [] as string[],
|
||||
is_enabled: 1
|
||||
})
|
||||
|
||||
const formRules = {
|
||||
app_name: [
|
||||
{ required: true, message: '请输入应用名称', trigger: 'blur' },
|
||||
{ max: 200, message: '应用名称不能超过 200 个字符', trigger: 'blur' }
|
||||
]
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
formData.app_name = ''
|
||||
formData.rate_limit = 1000
|
||||
formData.callback_url = ''
|
||||
formData.self_ip_whitelist = []
|
||||
formData.is_enabled = 1
|
||||
createdSecret.value = null
|
||||
editingId.value = null
|
||||
}
|
||||
|
||||
function openCreateDialog() {
|
||||
dialogMode.value = 'create'
|
||||
resetForm()
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
function openEditDialog(row: ApiAppItem) {
|
||||
dialogMode.value = 'edit'
|
||||
resetForm()
|
||||
editingId.value = row.id
|
||||
formData.app_name = row.app_name
|
||||
formData.rate_limit = row.rate_limit ?? 1000
|
||||
formData.callback_url = row.callback_url || ''
|
||||
formData.self_ip_whitelist = row.self_ip_whitelist ? [...row.self_ip_whitelist] : []
|
||||
formData.is_enabled = row.is_enabled
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
if (dialogMode.value === 'create') {
|
||||
const res = await apiAppCreate({
|
||||
app_name: formData.app_name,
|
||||
rate_limit: formData.rate_limit,
|
||||
callback_url: formData.callback_url || undefined,
|
||||
self_ip_whitelist: formData.self_ip_whitelist.length > 0 ? formData.self_ip_whitelist : undefined
|
||||
})
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
ElMessage.error(res.message || '创建失败')
|
||||
return
|
||||
}
|
||||
createdSecret.value = res
|
||||
ElMessage.success('创建成功!请保存 AppKey 和 AppSecret')
|
||||
// 不关闭对话框,等用户确认密钥后再关闭;关闭时通过 watch 自动刷新列表
|
||||
} else {
|
||||
const res = await apiAppUpdate({
|
||||
id: editingId.value!,
|
||||
app_name: formData.app_name,
|
||||
rate_limit: formData.rate_limit,
|
||||
callback_url: formData.callback_url || undefined,
|
||||
self_ip_whitelist: formData.self_ip_whitelist.length > 0 ? formData.self_ip_whitelist : undefined,
|
||||
is_enabled: formData.is_enabled
|
||||
})
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
ElMessage.error(res.message || '更新失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('更新成功')
|
||||
dialogVisible.value = false
|
||||
loadData()
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '操作失败')
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 创建成功后用户关闭对话框时,自动刷新列表
|
||||
watch(dialogVisible, (visible, prevVisible) => {
|
||||
if (!visible && prevVisible && dialogMode.value === 'create' && createdSecret.value) {
|
||||
loadData()
|
||||
}
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// 删除(停用)
|
||||
// ============================================================
|
||||
async function handleDelete(row: ApiAppItem) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确定要停用应用「${row.app_name}」吗?停用后该应用的 API 密钥将立即失效。`,
|
||||
'停用确认',
|
||||
{
|
||||
confirmButtonText: '确定停用',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
)
|
||||
const res = await apiAppDelete(row.id)
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
ElMessage.error(res.message || '停用失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('已停用')
|
||||
loadData()
|
||||
} catch {
|
||||
// 用户取消
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 重新生成密钥
|
||||
// ============================================================
|
||||
async function handleRegenerateSecret(row: ApiAppItem) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确定要重新生成「${row.app_name}」的 AppSecret 吗?旧密钥将立即失效,请确保已更新所有使用该密钥的系统。`,
|
||||
'重置密钥确认',
|
||||
{
|
||||
confirmButtonText: '确定重置',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}
|
||||
)
|
||||
const res = await apiAppRegenerateSecret(row.id)
|
||||
if (!SUCCESS_CODES.includes(res.code)) {
|
||||
ElMessage.error(res.message || '重置失败')
|
||||
return
|
||||
}
|
||||
const newSecret = res.self_app_secret || ''
|
||||
ElMessageBox.alert(
|
||||
`新 AppSecret:${newSecret}`,
|
||||
'密钥已重置 — 请妥善保存',
|
||||
{
|
||||
confirmButtonText: '我已保存',
|
||||
type: 'warning',
|
||||
dangerouslyUseHTMLString: false
|
||||
}
|
||||
)
|
||||
loadData()
|
||||
} catch {
|
||||
// 用户取消
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 详情对话框
|
||||
// ============================================================
|
||||
const detailVisible = ref(false)
|
||||
const detailData = ref<ApiAppFlatResponse | null>(null)
|
||||
|
||||
async function openDetailDialog(row: ApiAppItem) {
|
||||
detailVisible.value = true
|
||||
detailData.value = null
|
||||
try {
|
||||
const res = await apiAppDetail(row.id)
|
||||
if (SUCCESS_CODES.includes(res.code)) {
|
||||
detailData.value = res
|
||||
} else {
|
||||
// 兜底用列表行数据
|
||||
detailData.value = { ...res, ...row } as any
|
||||
}
|
||||
} catch {
|
||||
detailData.value = row as any
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// IP 白名单(表单内)
|
||||
// ============================================================
|
||||
const formIpInputVisible = ref(false)
|
||||
const formIpInputValue = ref('')
|
||||
const formIpInputRef = ref()
|
||||
|
||||
function showFormIpInput() {
|
||||
formIpInputVisible.value = true
|
||||
nextTick(() => {
|
||||
formIpInputRef.value?.focus?.()
|
||||
})
|
||||
}
|
||||
|
||||
function handleAddFormIp() {
|
||||
const val = formIpInputValue.value.trim()
|
||||
if (!val) {
|
||||
formIpInputVisible.value = false
|
||||
return
|
||||
}
|
||||
if (formData.self_ip_whitelist.includes(val)) {
|
||||
ElMessage.warning('该 IP 已存在')
|
||||
formIpInputValue.value = ''
|
||||
formIpInputVisible.value = false
|
||||
return
|
||||
}
|
||||
formData.self_ip_whitelist.push(val)
|
||||
formIpInputValue.value = ''
|
||||
formIpInputVisible.value = false
|
||||
}
|
||||
|
||||
function handleRemoveFormIp(idx: number) {
|
||||
formData.self_ip_whitelist.splice(idx, 1)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 工具函数
|
||||
// ============================================================
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopy(text: string, label: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
ElMessage.success(`${label} 已复制到剪贴板`)
|
||||
} catch {
|
||||
// 降级方案
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = text
|
||||
textarea.style.position = 'fixed'
|
||||
textarea.style.opacity = '0'
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
document.execCommand('copy')
|
||||
document.body.removeChild(textarea)
|
||||
ElMessage.success(`${label} 已复制到剪贴板`)
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 初始化
|
||||
// ============================================================
|
||||
loadData()
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.api-open-interface {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
// 工具栏
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
// 表格等宽字体
|
||||
.mono-text {
|
||||
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
// 分页
|
||||
.pagination-wrap {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
// IP 白名单
|
||||
.ip-whitelist {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ip-tag {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
// 单位文本
|
||||
.unit-text {
|
||||
margin-left: 8px;
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// 密钥展示
|
||||
.secret-display {
|
||||
background: #f5f7fa;
|
||||
border: 1px solid #e4e7ed;
|
||||
border-radius: 6px;
|
||||
padding: 16px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.secret-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.secret-label {
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.secret-value {
|
||||
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
|
||||
font-size: 13px;
|
||||
color: #409eff;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.secret-highlight {
|
||||
color: #e6a23c;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -3,14 +3,26 @@
|
||||
对接接口:
|
||||
- setting.warehouse.getweChatApp(settingWarehouseGetWeChatApp):拉取当前仓库已授权的微信小程序配置
|
||||
- wechat.getAuthUrl(wechatGetAuthUrl):未配置时点击「去授权」获取授权链接,并在新小窗口中打开
|
||||
- wechat.getRegisterUrl(wechatGetRegisterUrl):点击「代注册小程序」获取代注册链接,并在新小窗口中打开
|
||||
- wechat.queryauth(wechatQueryAuth):查询当前仓库小程序的微信认证进度(左菜单「认证状态」)
|
||||
- wechat.registerMiniprogram(wechatRegisterMiniprogram):提交企业信息创建企业小程序注册任务
|
||||
(「代注册小程序」弹窗;后端调微信 fastregisterweapp,法人微信收模板消息做人脸核身,
|
||||
接口返回 errcode/errmsg、**不返回链接**,故不再开小窗)
|
||||
- wechat.getTemplateList(wechatGetTemplateList):拉普通代码模板库列表(左菜单「发布」,后端缓存 24h)
|
||||
- wechat.commit(wechatCommit):选定模板上传代码、生成体验版(需授权权限集 18)
|
||||
- wechat.getTrialQRCode(wechatGetTrialQRCode):获取体验版二维码(后端转存 COS 后返回 URL)
|
||||
- wechat.submitAudit(wechatSubmitAudit):提交代码审核(后端仅在 audit_status!=1 时允许;回写 audit_id)
|
||||
⚠️ 无审核状态查询接口,页面只能回显「已提交 + 审核单 ID」
|
||||
|
||||
交互约定:
|
||||
1) 页面挂载即拉取配置;无配置(未授权)时提示「需要授权」并高亮「去授权」入口
|
||||
2) 授权/代注册链接**不自动打开**:必须用户点击按钮后才请求接口并弹小窗
|
||||
2) 授权链接**不自动打开**:必须用户点击按钮后才请求接口并弹小窗
|
||||
3) 小窗口打开后:轮询配置,流程完成自动刷新;小窗关闭后做最后一次刷新
|
||||
4) 域名限制:微信小程序授权/代注册页只能从**主域名**进入(主域名 = 品牌豁免域名
|
||||
VITE_FRONT_CONFIG_EXEMPT_HOSTS,与 frontBrand 同源);非主域名下禁用按钮并提示
|
||||
4) 域名限制:微信小程序**授权页**只能从主域名进入(主域名 = 品牌豁免域名
|
||||
VITE_FRONT_CONFIG_EXEMPT_HOSTS,与 frontBrand 同源);非主域名下禁用授权按钮并提示。
|
||||
代注册 / 发布走纯后端接口、无微信页面跳转,故不做域名限制。
|
||||
5) 认证状态:切到「认证状态」菜单时按需查询一次,可手动刷新
|
||||
6) 发布:切到「发布」菜单时按需拉模板列表;上传代码成功后自动刷新配置并重取体验版二维码;
|
||||
提交审核后可回显审核单 ID
|
||||
|
||||
使用方:
|
||||
1) basicManagement/newview 的 viewType='form' 标签页「微信小程序」
|
||||
@ -29,15 +41,8 @@
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<el-button :disabled="pageLoading" @click="loadConfig">刷新</el-button>
|
||||
<el-tooltip :disabled="isMainDomain" :content="mainDomainTip" placement="bottom-end">
|
||||
<span class="mp-auth-trigger">
|
||||
<el-button
|
||||
:disabled="!isMainDomain"
|
||||
:loading="registerUrlLoading"
|
||||
@click="handleRegister"
|
||||
>代注册小程序</el-button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<!-- 代注册走纯后端接口(无微信页面跳转),不受主域名限制 -->
|
||||
<el-button @click="handleRegister">代注册小程序</el-button>
|
||||
<el-tooltip :disabled="isMainDomain" :content="mainDomainTip" placement="bottom-end">
|
||||
<span class="mp-auth-trigger">
|
||||
<el-button
|
||||
@ -222,7 +227,260 @@
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<!-- ② 其余菜单:页面结构已预留,接口待定 -->
|
||||
<!-- ② 认证状态(接口:wechat.queryauth) -->
|
||||
<template v-else-if="activeMenu === 'cert'">
|
||||
<section class="mp-panel">
|
||||
<header class="mp-panel__head">
|
||||
<h3 class="mp-panel__title">认证状态</h3>
|
||||
<p class="mp-panel__desc">
|
||||
来源:wechat.queryauth(按当前仓库已启用的小程序查询微信认证进度)
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div v-loading="certLoading" class="mp-cert">
|
||||
<el-empty
|
||||
v-if="!certLoading && !certInfo"
|
||||
description="暂无认证状态数据"
|
||||
:image-size="72"
|
||||
>
|
||||
<el-button @click="loadAuthStatus">重新查询</el-button>
|
||||
</el-empty>
|
||||
|
||||
<template v-else-if="certInfo">
|
||||
<el-descriptions :column="1" border size="small" class="mp-cert__desc">
|
||||
<el-descriptions-item label="小程序 AppID">
|
||||
{{ certInfo.appid || '-' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="认证状态">
|
||||
<el-tag :type="certStateMeta.type" size="small" effect="light">
|
||||
{{ certStateMeta.text }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
|
||||
<div class="mp-cert__actions">
|
||||
<el-button size="small" :loading="certLoading" @click="loadAuthStatus">
|
||||
刷新认证状态
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<el-alert
|
||||
type="info"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="mp-config-alert"
|
||||
title="认证主体 / 证件信息 / 有效期等待后端补充"
|
||||
description="wechat.queryauth 目前仅返回小程序 AppID 与认证进度(auth_state、auth_state_text);下方为规划中的内容分区。"
|
||||
/>
|
||||
|
||||
<div class="mp-placeholder">
|
||||
<div
|
||||
v-for="block in currentMenu?.blocks ?? []"
|
||||
:key="block.title"
|
||||
class="mp-placeholder__block"
|
||||
>
|
||||
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
|
||||
<p class="mp-placeholder__desc">{{ block.desc }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<!-- ③ 发布(接口:wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode / wechat.submitAudit) -->
|
||||
<template v-else-if="activeMenu === 'publish'">
|
||||
<section class="mp-panel">
|
||||
<header class="mp-panel__head">
|
||||
<h3 class="mp-panel__title">代码包上传</h3>
|
||||
<p class="mp-panel__desc">
|
||||
来源:wechat.getTemplateList / wechat.commit(取当前仓库启用小程序,需授权权限集 18
|
||||
代码管理;上传成功后后端回写 wms_wechat_app.template_id)
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<el-form label-width="110px" label-position="right" class="mp-publish-form">
|
||||
<el-form-item label="代码模板">
|
||||
<div class="mp-publish-row">
|
||||
<el-select
|
||||
v-model="commitForm.template_id"
|
||||
:loading="templateLoading"
|
||||
placeholder="请选择代码模板"
|
||||
class="mp-publish-select"
|
||||
>
|
||||
<el-option
|
||||
v-for="tpl in templateList"
|
||||
:key="String(tpl.template_id)"
|
||||
:value="tpl.template_id"
|
||||
:label="templateOptionLabel(tpl)"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button :loading="templateLoading" @click="loadTemplateList(true)">
|
||||
刷新模板
|
||||
</el-button>
|
||||
<el-tag v-if="templateFromCache" size="small" type="info" effect="plain">
|
||||
后端缓存
|
||||
</el-tag>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="版本号">
|
||||
<el-input
|
||||
v-model="commitForm.user_version"
|
||||
maxlength="64"
|
||||
placeholder="如 1.0.0(≤64 字符)"
|
||||
class="mp-publish-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="代码描述">
|
||||
<el-input
|
||||
v-model="commitForm.user_desc"
|
||||
maxlength="64"
|
||||
placeholder="如 修复分球打印错位"
|
||||
class="mp-publish-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="ext_json">
|
||||
<el-input
|
||||
v-model="commitForm.ext_json"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
placeholder='{"extAppid":"wx...","ext":{}}'
|
||||
/>
|
||||
<p class="mp-publish-hint">
|
||||
JSON 字符串,用于控制 extAppid / 自定义字段;无特殊需求保留默认值即可
|
||||
</p>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="commitSubmitting" @click="submitCommit">
|
||||
上传代码并生成体验版
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</section>
|
||||
|
||||
<section class="mp-panel">
|
||||
<header class="mp-panel__head">
|
||||
<h3 class="mp-panel__title">体验版二维码</h3>
|
||||
<p class="mp-panel__desc">
|
||||
来源:wechat.getTrialQRCode(微信生成 jpeg,后端转存 COS 后返回 URL;需权限集 18 / 86)
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<el-form label-width="110px" label-position="right" class="mp-publish-form">
|
||||
<el-form-item label="页面路径">
|
||||
<div class="mp-publish-row">
|
||||
<el-input
|
||||
v-model="trialQRCodePath"
|
||||
placeholder="选填,如 page/index?action=1"
|
||||
class="mp-publish-input"
|
||||
/>
|
||||
<el-button :loading="trialQRCodeLoading" @click="loadTrialQRCode()">
|
||||
获取二维码
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<div class="mp-qrcode">
|
||||
<el-image
|
||||
v-if="trialQRCodeUrl"
|
||||
:src="trialQRCodeUrl"
|
||||
:preview-src-list="[trialQRCodeUrl]"
|
||||
preview-teleported
|
||||
fit="contain"
|
||||
class="mp-qrcode__img"
|
||||
>
|
||||
<template #error><span class="mp-thumb__tip">二维码无法加载</span></template>
|
||||
</el-image>
|
||||
<p v-else class="mp-publish-hint">
|
||||
上传代码生成体验版后,点「获取二维码」即可扫码体验
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mp-panel">
|
||||
<header class="mp-panel__head">
|
||||
<h3 class="mp-panel__title">提交审核</h3>
|
||||
<p class="mp-panel__desc">
|
||||
来源:wechat.submitAudit(需权限集 18;后端仅在没有审核中的版本,即 audit_status != 1 时
|
||||
允许提交,成功后记录 audit_status=1 与 audit_id)
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<el-form label-width="130px" label-position="right" class="mp-publish-form">
|
||||
<el-form-item label="版本描述">
|
||||
<el-input
|
||||
v-model="auditForm.version_desc"
|
||||
maxlength="64"
|
||||
placeholder="选填,便于审核人员理解本次改动"
|
||||
class="mp-publish-input"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="地理位置接口">
|
||||
<el-switch v-model="auditForm.privacy_api_not_use" />
|
||||
<span class="mp-publish-inline-hint">
|
||||
{{ auditForm.privacy_api_not_use ? '声明不使用地理位置接口' : '未声明(默认)' }}
|
||||
</span>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="审核类目">
|
||||
<el-input
|
||||
v-model="auditForm.item_list_text"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
placeholder='选填,JSON 数组;留空则不传。例:[{"address":"教育/在线教育","tag":"","first_class":"教育"}]'
|
||||
/>
|
||||
<p class="mp-publish-hint">
|
||||
后端未提供「可选类目」查询接口,故需按微信格式手填;不需要时可留空
|
||||
</p>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit">
|
||||
提交审核
|
||||
</el-button>
|
||||
<span class="mp-publish-inline-hint">提交前请先「上传代码并生成体验版」</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-alert
|
||||
v-if="auditResult"
|
||||
type="success"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="mp-audit-result"
|
||||
:title="`已提交审核:审核单 ID ${auditResult.auditid ?? '-'}`"
|
||||
:description="`提交时间:${auditResult.submittedAt}|AppID:${auditResult.appid || '-'}|审核结果由微信事件回写后端,页面暂无查询接口`"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<el-alert
|
||||
type="info"
|
||||
show-icon
|
||||
:closable="false"
|
||||
class="mp-config-alert"
|
||||
title="「发布记录」等待后端补充"
|
||||
description="微信的正式发布 / 回滚等接口尚未收录;审核状态(审核中 / 驳回原因)也没有查询接口,提交后需等后端补充查询能力。"
|
||||
/>
|
||||
|
||||
<div class="mp-placeholder">
|
||||
<div
|
||||
v-for="block in currentMenu?.blocks ?? []"
|
||||
:key="block.title"
|
||||
class="mp-placeholder__block"
|
||||
>
|
||||
<h4 class="mp-placeholder__title">{{ block.title }}</h4>
|
||||
<p class="mp-placeholder__desc">{{ block.desc }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- ④ 其余菜单:页面结构已预留,接口待定 -->
|
||||
<template v-else>
|
||||
<section class="mp-panel">
|
||||
<header class="mp-panel__head">
|
||||
@ -253,18 +511,118 @@
|
||||
</template>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- ===== 代注册企业小程序:提交企业信息(wechat.registerMiniprogram) ===== -->
|
||||
<el-dialog
|
||||
v-model="registerDialogVisible"
|
||||
title="代注册企业小程序"
|
||||
width="580px"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-alert
|
||||
type="warning"
|
||||
show-icon
|
||||
:closable="false"
|
||||
style="margin-bottom: 16px"
|
||||
title="提交后微信会给法人微信推送模板消息,需法人本人完成人脸核身"
|
||||
description="企业信息须与工商登记一致;审核结果由微信事件回调后端,可在「认证状态」菜单查看进度。"
|
||||
/>
|
||||
|
||||
<el-form
|
||||
ref="registerFormRef"
|
||||
:model="registerForm"
|
||||
:rules="registerRules"
|
||||
label-width="110px"
|
||||
label-position="right"
|
||||
>
|
||||
<el-form-item label="企业名称" prop="name">
|
||||
<el-input
|
||||
v-model="registerForm.name"
|
||||
maxlength="64"
|
||||
placeholder="与工商登记一致(无主体名称的个体工商户填「个体户+法人姓名」)"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="企业代码" prop="code">
|
||||
<el-input
|
||||
v-model="registerForm.code"
|
||||
maxlength="32"
|
||||
placeholder="统一社会信用代码 / 组织机构代码 / 营业执照注册号"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="代码类型" prop="code_type">
|
||||
<el-select
|
||||
v-model="registerForm.code_type"
|
||||
placeholder="请选择企业代码类型"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-option :value="1" label="统一社会信用代码(18 位)" />
|
||||
<el-option :value="2" label="组织机构代码(9 位)" />
|
||||
<el-option :value="3" label="营业执照注册号(15 位)" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="法人微信号" prop="legal_persona_wechat">
|
||||
<el-input
|
||||
v-model="registerForm.legal_persona_wechat"
|
||||
maxlength="64"
|
||||
placeholder="仅支持微信号,不支持手机号 / 微信名"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="法人姓名" prop="legal_persona_name">
|
||||
<el-input
|
||||
v-model="registerForm.legal_persona_name"
|
||||
maxlength="64"
|
||||
placeholder="须与法人绑定银行卡的姓名一致"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="联系电话" prop="component_phone">
|
||||
<el-input
|
||||
v-model="registerForm.component_phone"
|
||||
maxlength="20"
|
||||
placeholder="选填,第三方联系电话"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
<el-button @click="registerDialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="registerSubmitting" @click="submitRegister">
|
||||
提交注册
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, type Component } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch, type Component } from 'vue'
|
||||
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Document, InfoFilled, Medal, Promotion, User, Wallet } from '@element-plus/icons-vue'
|
||||
import {
|
||||
settingWarehouseGetWeChatApp,
|
||||
unwrapSettingWarehousePayload
|
||||
} from '@/api/setting.warehouse/settingwarehouse'
|
||||
import { wechatGetAuthUrl, wechatGetRegisterUrl } from '@/api/wechat/wechat'
|
||||
import {
|
||||
wechatCommit,
|
||||
wechatGetAuthUrl,
|
||||
wechatGetTemplateList,
|
||||
wechatGetTrialQRCode,
|
||||
wechatQueryAuth,
|
||||
wechatRegisterMiniprogram,
|
||||
wechatSubmitAudit,
|
||||
type WeChatAuditItem,
|
||||
type WeChatQueryAuthData,
|
||||
type WeChatRegisterMiniprogramParams,
|
||||
type WeChatSubmitAuditData,
|
||||
type WeChatTemplateItem,
|
||||
type WeChatTemplateListData
|
||||
} from '@/api/wechat/wechat'
|
||||
import { isMainDomainHost, normalizeFrontHost } from '@/stores/modules/frontBrand'
|
||||
defineOptions({ name: 'MiniProgramConfigForm' })
|
||||
|
||||
@ -366,12 +724,11 @@ const MENU_LIST: MiniProgramMenuItem[] = [
|
||||
key: 'cert',
|
||||
label: '认证状态',
|
||||
icon: Medal,
|
||||
desc: '小程序微信认证状态、认证主体与有效期(接口待定)',
|
||||
pending: true,
|
||||
desc: '小程序微信认证状态(接口已接入:wechat.queryauth)',
|
||||
blocks: [
|
||||
{ title: '认证信息', desc: '认证类型 / 认证主体名称 / 认证主体证件号 / 认证有效期' },
|
||||
{ title: '认证材料与支付', desc: '认证订单与支付记录 / 认证结果通知 / 年审提醒' },
|
||||
{ title: '状态与记录', desc: '当前认证状态 / 认证历史记录 / 失败原因与重试' }
|
||||
{ title: '认证信息(待后端补充)', desc: '认证类型 / 认证主体名称 / 认证主体证件号 / 认证有效期' },
|
||||
{ title: '认证材料与支付(待后端补充)', desc: '认证订单与支付记录 / 认证结果通知 / 年审提醒' },
|
||||
{ title: '状态与记录(待后端补充)', desc: '认证历史记录 / 失败原因与重试' }
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -390,12 +747,9 @@ const MENU_LIST: MiniProgramMenuItem[] = [
|
||||
key: 'publish',
|
||||
label: '发布',
|
||||
icon: Promotion,
|
||||
desc: '代码包上传、版本审核与发布记录(接口待定)',
|
||||
pending: true,
|
||||
desc: '上传代码生成体验版、提交微信审核(接口已接入:wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode / wechat.submitAudit)',
|
||||
blocks: [
|
||||
{ title: '版本与审核', desc: '当前线上版本 / 审核中版本 / 提交审核入口' },
|
||||
{ title: '代码包管理', desc: '体验版 / 上传代码包 / 版本描述' },
|
||||
{ title: '发布记录', desc: '版本号 / 发布时间 / 发布人 / 回滚操作' }
|
||||
{ title: '发布记录(待后端补充)', desc: '版本号 / 发布时间 / 发布人 / 回滚操作' }
|
||||
]
|
||||
},
|
||||
{
|
||||
@ -453,12 +807,69 @@ type FuncInfoItem = { id: string; label: string; raw: string }
|
||||
// ============================================================
|
||||
const pageLoading = ref(false)
|
||||
const authUrlLoading = ref(false)
|
||||
const registerUrlLoading = ref(false)
|
||||
const config = ref<Record<string, unknown>>({})
|
||||
const lastLoadedAt = ref('')
|
||||
|
||||
/** 微信小窗流程类型:授权 / 代注册 */
|
||||
type WeChatFlowKind = 'auth' | 'register'
|
||||
/** 认证状态(wechat.queryauth) */
|
||||
const certLoading = ref(false)
|
||||
const certInfo = ref<WeChatQueryAuthData | null>(null)
|
||||
const certLoaded = ref(false)
|
||||
|
||||
/** 代注册弹窗(wechat.registerMiniprogram) */
|
||||
const registerDialogVisible = ref(false)
|
||||
const registerSubmitting = ref(false)
|
||||
const registerFormRef = ref<FormInstance>()
|
||||
const registerForm = reactive<WeChatRegisterMiniprogramParams>({
|
||||
name: '',
|
||||
code: '',
|
||||
code_type: 1,
|
||||
legal_persona_wechat: '',
|
||||
legal_persona_name: '',
|
||||
component_phone: ''
|
||||
})
|
||||
|
||||
const registerRules: FormRules = {
|
||||
name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
|
||||
code: [{ required: true, message: '请输入企业代码', trigger: 'blur' }],
|
||||
code_type: [{ required: true, message: '请选择企业代码类型', trigger: 'change' }],
|
||||
legal_persona_wechat: [{ required: true, message: '请输入法人微信号', trigger: 'blur' }],
|
||||
legal_persona_name: [{ required: true, message: '请输入法人姓名', trigger: 'blur' }]
|
||||
}
|
||||
|
||||
/** 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode) */
|
||||
const templateLoading = ref(false)
|
||||
const templateLoaded = ref(false)
|
||||
const templateList = ref<WeChatTemplateItem[]>([])
|
||||
const templateFromCache = ref(false)
|
||||
const commitSubmitting = ref(false)
|
||||
const commitForm = reactive<{
|
||||
template_id?: number
|
||||
user_version: string
|
||||
user_desc: string
|
||||
ext_json: string
|
||||
}>({
|
||||
template_id: undefined,
|
||||
user_version: '',
|
||||
user_desc: '',
|
||||
ext_json: '{}'
|
||||
})
|
||||
const trialQRCodeLoading = ref(false)
|
||||
const trialQRCodePath = ref('')
|
||||
const trialQRCodeUrl = ref('')
|
||||
|
||||
/** 提交审核(wechat.submitAudit) */
|
||||
const auditSubmitting = ref(false)
|
||||
const auditForm = reactive<{
|
||||
version_desc: string
|
||||
privacy_api_not_use: boolean
|
||||
item_list_text: string
|
||||
}>({
|
||||
version_desc: '',
|
||||
privacy_api_not_use: false,
|
||||
item_list_text: ''
|
||||
})
|
||||
/** 最近一次提交审核的返回(无审核状态查询接口,仅回显本次提交信息) */
|
||||
const auditResult = ref<{ appid?: string; auditid?: number; submittedAt: string } | null>(null)
|
||||
|
||||
/** 授权小窗句柄与轮询计时器 */
|
||||
let authWindow: Window | null = null
|
||||
@ -660,10 +1071,230 @@ async function loadConfig(options: { silent?: boolean } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 认证状态(wechat.queryauth)
|
||||
// ============================================================
|
||||
/** 认证状态码 → 标签文案与颜色(后端同时返回 auth_state_text,展示时优先用后端文案) */
|
||||
const CERT_STATE_META: Record<number, { text: string; type: 'info' | 'warning' | 'success' | 'danger' }> = {
|
||||
0: { text: '未认证', type: 'info' },
|
||||
1: { text: '认证中', type: 'warning' },
|
||||
2: { text: '认证通过', type: 'success' },
|
||||
3: { text: '认证失败', type: 'danger' }
|
||||
}
|
||||
|
||||
const certStateMeta = computed<{ text: string; type: 'info' | 'warning' | 'success' | 'danger' }>(() => {
|
||||
const meta = CERT_STATE_META[Number(certInfo.value?.auth_state)]
|
||||
return {
|
||||
text: certInfo.value?.auth_state_text || meta?.text || '未知状态',
|
||||
type: meta?.type ?? 'info'
|
||||
}
|
||||
})
|
||||
|
||||
/** 查询认证状态(切到「认证状态」菜单时按需拉取,也可手动刷新) */
|
||||
async function loadAuthStatus(options: { silent?: boolean } = {}) {
|
||||
if (!options.silent) certLoading.value = true
|
||||
try {
|
||||
const res: any = await wechatQueryAuth()
|
||||
if (!res || !okCode(res.code)) {
|
||||
if (!options.silent) ElMessage.error(res?.message || '查询小程序认证状态失败')
|
||||
return null
|
||||
}
|
||||
const payload = res.data
|
||||
certInfo.value =
|
||||
payload && typeof payload === 'object' && !Array.isArray(payload)
|
||||
? (payload as WeChatQueryAuthData)
|
||||
: null
|
||||
certLoaded.value = true
|
||||
return certInfo.value
|
||||
} catch (e: unknown) {
|
||||
if (!options.silent) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '查询小程序认证状态失败')
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
if (!options.silent) certLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 切菜单时按需拉取(已查过不重复请求,可手动刷新) */
|
||||
watch(activeMenu, (key) => {
|
||||
if (key === 'cert' && !certLoaded.value && !certLoading.value) void loadAuthStatus()
|
||||
if (key === 'publish' && !templateLoaded.value && !templateLoading.value) void loadTemplateList()
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode)
|
||||
// ============================================================
|
||||
/** 模板下拉选项文案:版本号 + 模板 ID + 描述 + 创建时间 */
|
||||
function templateOptionLabel(tpl: WeChatTemplateItem): string {
|
||||
const version = tpl.user_version || '未命名版本'
|
||||
const id = tpl.template_id != null ? `#${tpl.template_id}` : '#-'
|
||||
const desc = tpl.user_desc ? `|${tpl.user_desc}` : ''
|
||||
const time = tpl.create_time ? `|${toLocalDateTime(new Date(tpl.create_time * 1000))}` : ''
|
||||
return `${version} ${id}${desc}${time}`
|
||||
}
|
||||
|
||||
/** 拉取普通模板库列表(后端缓存 24h,from_cache 标识是否命中缓存;force=true 时重新请求) */
|
||||
async function loadTemplateList(force = false) {
|
||||
if (templateLoading.value) return null
|
||||
if (templateLoaded.value && !force) return templateList.value
|
||||
templateLoading.value = true
|
||||
try {
|
||||
const res: any = await wechatGetTemplateList()
|
||||
if (!res || !okCode(res.code)) {
|
||||
ElMessage.error(res?.message || '获取代码模板列表失败')
|
||||
return null
|
||||
}
|
||||
const payload = (res.data ?? {}) as Partial<WeChatTemplateListData>
|
||||
templateList.value = Array.isArray(payload.list) ? payload.list : []
|
||||
templateFromCache.value = Boolean(payload.from_cache)
|
||||
templateLoaded.value = true
|
||||
return templateList.value
|
||||
} catch (e: unknown) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '获取代码模板列表失败')
|
||||
return null
|
||||
} finally {
|
||||
templateLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传代码并生成体验版(wechat.commit) */
|
||||
async function submitCommit() {
|
||||
const templateId = commitForm.template_id
|
||||
if (templateId === undefined || templateId === null) {
|
||||
ElMessage.warning('请先选择代码模板')
|
||||
return
|
||||
}
|
||||
const version = commitForm.user_version.trim()
|
||||
if (!version) {
|
||||
ElMessage.warning('请填写版本号')
|
||||
return
|
||||
}
|
||||
if (version.length > 64) {
|
||||
ElMessage.warning('版本号不能超过 64 个字符')
|
||||
return
|
||||
}
|
||||
const desc = commitForm.user_desc.trim()
|
||||
if (!desc) {
|
||||
ElMessage.warning('请填写代码描述')
|
||||
return
|
||||
}
|
||||
const extJson = commitForm.ext_json.trim() || '{}'
|
||||
try {
|
||||
JSON.parse(extJson)
|
||||
} catch {
|
||||
ElMessage.error('ext_json 不是合法的 JSON 字符串')
|
||||
return
|
||||
}
|
||||
|
||||
commitSubmitting.value = true
|
||||
try {
|
||||
const res: any = await wechatCommit({
|
||||
template_id: templateId,
|
||||
ext_json: extJson,
|
||||
user_version: version,
|
||||
user_desc: desc
|
||||
})
|
||||
if (!res || !okCode(res.code)) {
|
||||
ElMessage.error(res?.message || '上传代码失败')
|
||||
return
|
||||
}
|
||||
const payload = (res.data ?? {}) as { appid?: string; template_id?: number }
|
||||
ElMessage.success(
|
||||
payload.template_id != null
|
||||
? `代码已上传,体验版已生成(模板 #${payload.template_id})`
|
||||
: '代码已上传,体验版已生成'
|
||||
)
|
||||
// 后端会回写 wms_wechat_app.template_id,刷新基础信息保持一致
|
||||
await loadConfig({ silent: true })
|
||||
// 体验版内容已变化,旧二维码作废并自动重取
|
||||
trialQRCodeUrl.value = ''
|
||||
await loadTrialQRCode({ silent: true })
|
||||
} catch (e: unknown) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '上传代码失败')
|
||||
} finally {
|
||||
commitSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 获取体验版二维码(wechat.getTrialQRCode;path 选填,不传则由后端处理) */
|
||||
async function loadTrialQRCode(options: { silent?: boolean } = {}) {
|
||||
if (!options.silent) trialQRCodeLoading.value = true
|
||||
try {
|
||||
const path = trialQRCodePath.value.trim()
|
||||
const res: any = await wechatGetTrialQRCode(path ? { path } : {})
|
||||
if (!res || !okCode(res.code)) {
|
||||
if (!options.silent) ElMessage.error(res?.message || '获取体验版二维码失败')
|
||||
return null
|
||||
}
|
||||
const payload = (res.data ?? {}) as { url?: string }
|
||||
trialQRCodeUrl.value = payload.url || ''
|
||||
if (!trialQRCodeUrl.value && !options.silent) ElMessage.error('未获取到二维码地址')
|
||||
return trialQRCodeUrl.value
|
||||
} catch (e: unknown) {
|
||||
if (!options.silent) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '获取体验版二维码失败')
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
if (!options.silent) trialQRCodeLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代码审核(wechat.submitAudit)。
|
||||
* item_list 后端未提供可选类目接口,按微信格式手填(JSON 数组,留空则不传)。
|
||||
*/
|
||||
async function submitAudit() {
|
||||
let itemList: WeChatAuditItem[] | undefined
|
||||
const rawItemList = auditForm.item_list_text.trim()
|
||||
if (rawItemList) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(rawItemList)
|
||||
if (!Array.isArray(parsed)) {
|
||||
ElMessage.error('审核类目必须是 JSON 数组')
|
||||
return
|
||||
}
|
||||
itemList = parsed as WeChatAuditItem[]
|
||||
} catch {
|
||||
ElMessage.error('审核类目不是合法的 JSON')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
auditSubmitting.value = true
|
||||
try {
|
||||
const res: any = await wechatSubmitAudit({
|
||||
version_desc: auditForm.version_desc.trim() || undefined,
|
||||
privacy_api_not_use: auditForm.privacy_api_not_use || undefined,
|
||||
...(itemList ? { item_list: itemList } : {})
|
||||
})
|
||||
if (!res || !okCode(res.code)) {
|
||||
ElMessage.error(res?.message || '提交审核失败')
|
||||
return
|
||||
}
|
||||
const payload = (res.data ?? {}) as WeChatSubmitAuditData
|
||||
auditResult.value = {
|
||||
appid: payload.appid,
|
||||
auditid: payload.auditid,
|
||||
submittedAt: toLocalDateTime(new Date())
|
||||
}
|
||||
ElMessage.success(
|
||||
payload.auditid != null ? `已提交审核(审核单 ${payload.auditid})` : '已提交审核'
|
||||
)
|
||||
// 后端已回写 audit_status / audit_id,刷新一次让基础信息同步
|
||||
await loadConfig({ silent: true })
|
||||
} catch (e: unknown) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '提交审核失败')
|
||||
} finally {
|
||||
auditSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 授权(点击按钮后才获取链接并弹小窗)
|
||||
// ============================================================
|
||||
/** 从响应中取链接(字段名多形态兼容,兜底扫描 http 开头的字符串):授权链接与代注册链接共用 */
|
||||
/** 从响应中取链接(字段名多形态兼容,兜底扫描 http 开头的字符串) */
|
||||
function pickUrl(raw: Record<string, unknown>): string {
|
||||
for (const key of AUTH_URL_KEYS) {
|
||||
const value = raw[key]
|
||||
@ -675,8 +1306,8 @@ function pickUrl(raw: Record<string, unknown>): string {
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 在新小窗口中打开链接(授权 / 代注册共用) */
|
||||
function openSmallWindow(url: string, windowName: string, tipText: string, kind: WeChatFlowKind) {
|
||||
/** 在新小窗口中打开链接(授权) */
|
||||
function openSmallWindow(url: string, windowName: string, tipText: string) {
|
||||
const width = 760
|
||||
const height = 780
|
||||
const left = Math.max(0, Math.round((window.screen.width - width) / 2))
|
||||
@ -689,7 +1320,7 @@ function openSmallWindow(url: string, windowName: string, tipText: string, kind:
|
||||
return
|
||||
}
|
||||
ElMessage.info(tipText)
|
||||
startWatch(kind)
|
||||
startWatch()
|
||||
}
|
||||
|
||||
/** 点击「去授权」:获取授权链接 → 打开小窗(仅主域名可用) */
|
||||
@ -710,7 +1341,7 @@ async function handleAuthorize() {
|
||||
ElMessage.error('未获取到授权链接,请稍后重试')
|
||||
return
|
||||
}
|
||||
openSmallWindow(url, 'wx-miniprogram-authorize', '请在新打开的小窗口中完成微信授权,完成后本页会自动刷新', 'auth')
|
||||
openSmallWindow(url, 'wx-miniprogram-authorize', '请在新打开的小窗口中完成微信授权,完成后本页会自动刷新')
|
||||
} catch (e: unknown) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '获取微信授权链接失败')
|
||||
} finally {
|
||||
@ -718,34 +1349,60 @@ async function handleAuthorize() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 点击「代注册小程序」:获取代注册链接 → 打开小窗(仅主域名可用) */
|
||||
async function handleRegister() {
|
||||
if (!isMainDomain) {
|
||||
ElMessage.warning(mainDomainTip)
|
||||
return
|
||||
}
|
||||
registerUrlLoading.value = true
|
||||
/** 点击「代注册小程序」:打开企业信息弹窗(wechat.registerMiniprogram,不走小窗 / 不受主域名限制) */
|
||||
function handleRegister() {
|
||||
registerDialogVisible.value = true
|
||||
}
|
||||
|
||||
/** 重置代注册表单 */
|
||||
function resetRegisterForm() {
|
||||
registerFormRef.value?.clearValidate()
|
||||
Object.assign(registerForm, {
|
||||
name: '',
|
||||
code: '',
|
||||
code_type: 1,
|
||||
legal_persona_wechat: '',
|
||||
legal_persona_name: '',
|
||||
component_phone: ''
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代注册:后端调微信 fastregisterweapp?action=create 创建注册任务。
|
||||
* 响应为 { errcode, errmsg }(无链接),errcode=0 视为提交成功;
|
||||
* 之后由法人微信完成人脸核身,审核结果经微信事件回调后端,认证进度用 wechat.queryauth 查看。
|
||||
*/
|
||||
async function submitRegister() {
|
||||
const form = registerFormRef.value
|
||||
if (!form) return
|
||||
const valid = await form.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
registerSubmitting.value = true
|
||||
try {
|
||||
const res: any = await wechatGetRegisterUrl()
|
||||
if (!res || !okCode(res.code)) {
|
||||
ElMessage.error(res?.message || '获取代注册链接失败')
|
||||
const res: any = await wechatRegisterMiniprogram({ ...registerForm })
|
||||
const raw = (res ?? {}) as Record<string, any>
|
||||
const nested = (raw.data && typeof raw.data === 'object' ? raw.data : {}) as Record<string, any>
|
||||
const errcode = Number(nested.errcode ?? raw.errcode)
|
||||
const errmsg = String(nested.errmsg ?? raw.errmsg ?? raw.message ?? '')
|
||||
if (!(okCode(raw.code) || errcode === 0)) {
|
||||
ElMessage.error(errmsg || '提交代注册失败')
|
||||
return
|
||||
}
|
||||
const url = pickUrl({ ...unwrapSettingWarehousePayload(res) })
|
||||
if (!url) {
|
||||
ElMessage.error('未获取到代注册链接,请稍后重试')
|
||||
return
|
||||
}
|
||||
openSmallWindow(url, 'wx-miniprogram-register', '请在新打开的小窗口中完成小程序代注册,完成后本页会自动刷新', 'register')
|
||||
ElMessage.success('注册任务已提交:请法人本人留意微信模板消息并完成人脸核身')
|
||||
registerDialogVisible.value = false
|
||||
resetRegisterForm()
|
||||
// 注册结果由微信事件回调后端,这里刷新一次配置与认证进度
|
||||
await Promise.all([loadConfig({ silent: true }), loadAuthStatus({ silent: true })])
|
||||
} catch (e: unknown) {
|
||||
ElMessage.error(e instanceof Error ? e.message : '获取代注册链接失败')
|
||||
ElMessage.error(e instanceof Error ? e.message : '提交代注册失败')
|
||||
} finally {
|
||||
registerUrlLoading.value = false
|
||||
registerSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 小窗打开期间轮询配置:流程完成即自动刷新 */
|
||||
function startWatch(kind: WeChatFlowKind) {
|
||||
function startWatch() {
|
||||
stopAuthWatch()
|
||||
authWatchStartedAt = Date.now()
|
||||
authWatchTimer = window.setInterval(async () => {
|
||||
@ -766,7 +1423,11 @@ function startWatch(kind: WeChatFlowKind) {
|
||||
const payload = await loadConfig({ silent: true })
|
||||
if (payload && Object.entries(payload).some(([key, value]) => !NEUTRAL_KEYS.has(key.toLowerCase()) && !isEmptyValue(value))) {
|
||||
stopAuthWatch()
|
||||
ElMessage.success(kind === 'register' ? '小程序代注册完成,配置已刷新' : '微信小程序授权成功,配置已刷新')
|
||||
ElMessage.success('微信小程序授权成功,配置已刷新')
|
||||
// 授权可能换绑小程序(appid 变化),认证状态需重新查询
|
||||
certLoaded.value = false
|
||||
certInfo.value = null
|
||||
if (activeMenu.value === 'cert') void loadAuthStatus()
|
||||
}
|
||||
} finally {
|
||||
authWatchBusy = false
|
||||
@ -944,6 +1605,73 @@ onBeforeUnmount(() => {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ===== 认证状态(wechat.queryauth) ===== */
|
||||
.mp-cert {
|
||||
min-height: 80px;
|
||||
}
|
||||
|
||||
.mp-cert__desc {
|
||||
max-width: 560px;
|
||||
}
|
||||
|
||||
.mp-cert__actions {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* ===== 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode) ===== */
|
||||
.mp-publish-form {
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
.mp-publish-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.mp-publish-select {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.mp-publish-input {
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.mp-publish-hint {
|
||||
margin: 4px 0 0;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.mp-publish-inline-hint {
|
||||
margin-left: 8px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.mp-audit-result {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.mp-qrcode {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mp-qrcode__img {
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
border: 1px solid #ebeef5;
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ===== 已授权:左菜单 + 右明细(均铺满高度) ===== */
|
||||
.mp-layout {
|
||||
flex: 1;
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
|
||||
@ -1,175 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,132 +0,0 @@
|
||||
<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>
|
||||
@ -1,159 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,227 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,727 +0,0 @@
|
||||
/**
|
||||
* 【页面模板】配置文件 v2 — 基于 waveOrder2 架构设计
|
||||
*
|
||||
* ===== 核心设计 =====
|
||||
*
|
||||
* 1. FIELD_DICT — 全局字段预设表,每个字段拥有唯一翻译(label)和完整元数据
|
||||
* 2. VALUE_MAPS — 值翻译映射表(select options 和 tag 翻译共用)
|
||||
* 3. TAG_RESOLVERS — 标签颜色解析器(集中管理 tag 颜色逻辑)
|
||||
* 4. 各标签页通过 key 引用所需字段(scanBoxFieldKeys / tableColumnKeys)
|
||||
* 5. resolveTabConfig() — 加载时将 key 列表展开为完整配置
|
||||
*
|
||||
* ===== 快速上手 =====
|
||||
* 1. 复制整个 views/mode/ 文件夹,重命名为你的页面名
|
||||
* 2. 在 FIELD_DICT 中添加你需要的字段定义
|
||||
* 3. 在 tabPages 中配置标签页(引用 FIELD_DICT 的 key)
|
||||
* 4. 在 TabPageApiConfig 中接入真实接口
|
||||
* 5. 在 router/map.ts 中添加路由
|
||||
*/
|
||||
|
||||
import type { Component } from 'vue'
|
||||
import DetailPanel from './components/DetailPanel.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
|
||||
// ============================================================
|
||||
// 〇、全局页面配置
|
||||
// ============================================================
|
||||
export const PAGE_CONFIG = {
|
||||
/** 是否显示顶部多标签栏 */
|
||||
showTabArea: true,
|
||||
/** 单页模式:不显示标签栏,仅一个标签页内容 */
|
||||
singlePage: false,
|
||||
/** 是否启用详情面板(底部分栏 + 显示/隐藏详情按钮),false 时表格占满全高 */
|
||||
enableDetailPanel: true
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 〇-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 — 值翻译映射(select options 和 tag 翻译共用)
|
||||
// ============================================================
|
||||
export const VALUE_MAPS: Record<string, Record<string, string>> = {
|
||||
status: { 'pending': '待处理', 'processing': '处理中', 'done': '已完成', '待处理': '待处理', '处理中': '处理中', '已完成': '已完成' },
|
||||
type: { 'A': '类型A', 'B': '类型B', 'C': '类型C', '类型A': '类型A', '类型B': '类型B', '类型C': '类型C' },
|
||||
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 — 标签颜色解析器
|
||||
// ============================================================
|
||||
// 颜色规则:未xx=info(灰) 已xx=success(绿) xx中/部分xx=warning(黄) 错误=danger(红)
|
||||
export const TAG_RESOLVERS: Record<string, (val: any) => string> = {
|
||||
resolveStatusTag(v) {
|
||||
if (!v) return 'info'
|
||||
if (v === '已完成' || v === 'done') return 'success'
|
||||
if (v === '处理中' || v === 'processing') return 'warning'
|
||||
return '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> = {
|
||||
code: {
|
||||
key: 'code',
|
||||
label: '编号',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 160, fixed: 'left', copyAction: 'copy', showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '编号'
|
||||
},
|
||||
name: {
|
||||
key: 'name',
|
||||
label: '名称',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 150, showOverflowTooltip: true },
|
||||
slot: null,
|
||||
detailLabel: '名称'
|
||||
},
|
||||
type: {
|
||||
key: 'type',
|
||||
label: '类型',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.basic, options: getOptions('type') },
|
||||
table: { minWidth: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagType: 'info', translateField: 'type' },
|
||||
detailLabel: '类型',
|
||||
filterParamMap: { '类型A': 'A', '类型B': 'B', '类型C': 'C' }
|
||||
},
|
||||
status: {
|
||||
key: 'status',
|
||||
label: '状态',
|
||||
scanBox: { type: 'select', group: SCANBOX_GROUPS.process, options: getOptions('status') },
|
||||
table: { minWidth: 100, align: 'center' },
|
||||
slot: { type: 'tag', tagResolver: 'resolveStatusTag', translateField: 'status' },
|
||||
detailLabel: '状态',
|
||||
filterParamMap: { '待处理': 'pending', '处理中': 'processing', '已完成': 'done' }
|
||||
},
|
||||
count: {
|
||||
key: 'count',
|
||||
label: '数量',
|
||||
scanBox: null,
|
||||
table: { minWidth: 80, align: 'center', sortable: true },
|
||||
slot: null
|
||||
},
|
||||
amount: {
|
||||
key: 'amount',
|
||||
label: '金额(元)',
|
||||
scanBox: null,
|
||||
table: { minWidth: 110, align: 'center', sortable: true },
|
||||
slot: null
|
||||
},
|
||||
creator: {
|
||||
key: 'creator',
|
||||
label: '创建人',
|
||||
scanBox: { type: 'text', group: SCANBOX_GROUPS.basic },
|
||||
table: { minWidth: 100 },
|
||||
slot: null,
|
||||
detailLabel: '创建人'
|
||||
},
|
||||
create_time: {
|
||||
key: 'create_time',
|
||||
label: '创建时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { minWidth: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '创建时间'
|
||||
},
|
||||
update_time: {
|
||||
key: 'update_time',
|
||||
label: '更新时间',
|
||||
scanBox: { type: 'daterange', group: SCANBOX_GROUPS.time },
|
||||
table: { minWidth: 170, sortable: true },
|
||||
slot: { type: 'text', format: 'datetime' },
|
||||
detailLabel: '更新时间'
|
||||
},
|
||||
/** 操作列(虚拟字段,仅用于表格列渲染) */
|
||||
operation: {
|
||||
key: 'operation',
|
||||
label: '操作',
|
||||
scanBox: null,
|
||||
table: { minWidth: 180, 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
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十、工具栏按钮系统
|
||||
// ============================================================
|
||||
// 按钮分为三类:
|
||||
// common — 公共按钮(刷新、导出)
|
||||
// function — 功能按钮(打开表单/确认窗口)
|
||||
// basic — 基础操作(字段设置、隐藏详情)
|
||||
|
||||
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'
|
||||
},
|
||||
export: {
|
||||
key: 'export',
|
||||
label: '导出',
|
||||
category: 'common',
|
||||
size: 'small',
|
||||
loadingKey: 'exportLoading',
|
||||
action: 'handleExport',
|
||||
buttonType: 'dropdown',
|
||||
dropdownOptions: [
|
||||
{ label: '不含明细', action: 'handleExport' },
|
||||
{ label: '含明细', action: 'handleExportItem', divided: true }
|
||||
]
|
||||
},
|
||||
// ===== 基础操作 =====
|
||||
columnConfig: {
|
||||
key: 'columnConfig',
|
||||
label: '字段设置',
|
||||
category: 'basic',
|
||||
size: 'small',
|
||||
action: 'openColumnConfigPanel'
|
||||
},
|
||||
toggleDetail: {
|
||||
key: 'toggleDetail',
|
||||
label: '显示详情',
|
||||
category: 'basic',
|
||||
dynamicLabelKey: 'detailToggleLabel',
|
||||
size: 'small',
|
||||
action: 'toggleDetailVisible'
|
||||
}
|
||||
// ★ 在此添加功能按钮(如批量操作)★
|
||||
}
|
||||
|
||||
/** 按标签页名称获取工具栏按钮列表(自动根据 PAGE_CONFIG 过滤) */
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十一、批量操作配置(可选,接入 BatchOperationForm 时使用)
|
||||
// ============================================================
|
||||
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> = {
|
||||
// batchExample: {
|
||||
// action: 'batchExample',
|
||||
// title: '批量操作示例',
|
||||
// confirmText: '确定对选中的 {count} 项执行操作吗?',
|
||||
// confirmType: 'warning',
|
||||
// confirmButtonText: '确认操作',
|
||||
// successText: '批量操作成功',
|
||||
// failText: '批量操作失败',
|
||||
// apiMethod: yourBatchApi,
|
||||
// payloadKey: 'ids',
|
||||
// idField: 'id'
|
||||
// }
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 十二、标签页注册表 — 在此定义你的页面标签页
|
||||
// ============================================================
|
||||
export const tabPages: TabPageRawConfig[] = [
|
||||
// ===== 示例标签页一 =====
|
||||
{
|
||||
name: 'tab1',
|
||||
label: '标签页一',
|
||||
scanBoxCacheKey: 'template-tab1',
|
||||
scanBoxFieldKeys: ['code', 'type', 'status', 'creator', 'create_time'],
|
||||
tableColumnKeys: ['code', 'name', 'type', 'status', 'count', 'amount', 'creator', 'create_time', 'operation'],
|
||||
upperTableDefaults: {
|
||||
title: '示例列表一',
|
||||
showSelection: true
|
||||
},
|
||||
detailTabs: [
|
||||
{ name: 'detail', label: '明细', componentKey: 'DetailPanel' },
|
||||
{ name: 'log', label: '操作日志', componentKey: 'LogPanel' }
|
||||
],
|
||||
detailSections: [
|
||||
{
|
||||
title: '基础信息',
|
||||
columnCount: 3,
|
||||
fieldKeys: ['code', 'name', 'type', 'status', 'count', 'amount', 'creator']
|
||||
},
|
||||
{
|
||||
title: '时间信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['create_time', 'update_time']
|
||||
}
|
||||
],
|
||||
/** ★ 接入真实接口时取消注释 */
|
||||
// api: {
|
||||
// list: yourListApi,
|
||||
// detail: { source: 'list' },
|
||||
// parseListResponse(res) {
|
||||
// return { list: res.data?.list ?? [], total: res.data?.pagination?.total ?? 0 }
|
||||
// },
|
||||
// buildListParams({ pagination, conditions, sort }) {
|
||||
// return {
|
||||
// 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: 'warning'
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// ===== 示例标签页二 =====
|
||||
{
|
||||
name: 'tab2',
|
||||
label: '标签页二',
|
||||
scanBoxCacheKey: 'template-tab2',
|
||||
scanBoxFieldKeys: ['code', 'status', 'create_time'],
|
||||
tableColumnKeys: ['code', 'name', 'status', 'count', 'creator', 'create_time', 'operation'],
|
||||
upperTableDefaults: {
|
||||
title: '示例列表二',
|
||||
showSelection: true
|
||||
},
|
||||
detailSections: [
|
||||
{
|
||||
title: '基础信息',
|
||||
columnCount: 3,
|
||||
fieldKeys: ['code', 'name', 'status', 'count', 'creator']
|
||||
},
|
||||
{
|
||||
title: '时间信息',
|
||||
columnCount: 2,
|
||||
fieldKeys: ['create_time', 'update_time']
|
||||
}
|
||||
],
|
||||
operationButtons: [
|
||||
{
|
||||
key: 'viewDetail',
|
||||
label: '查看详情',
|
||||
actionType: 'action',
|
||||
type: 'primary'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
// ============================================================
|
||||
// 十三、向后兼容导出
|
||||
// ============================================================
|
||||
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
@ -1,107 +0,0 @@
|
||||
<!--
|
||||
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>
|
||||
@ -1,966 +0,0 @@
|
||||
<template>
|
||||
<div class="order-sub-container" :style="{ height: containerHeight }">
|
||||
<scan-box
|
||||
ref="scanBox"
|
||||
width="220px"
|
||||
:tree-props="{ children: 'children', label: 'label' }"
|
||||
:auto-submit="false"
|
||||
:preset-tree="presetTree"
|
||||
:available-fields="availableFieldsRef"
|
||||
@condition-change="handleConditionChange"
|
||||
@reset="handleConditionReset"
|
||||
@condition-clear="handleConditionClear"
|
||||
@submit="handleSubmit"
|
||||
/>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<order-toolbar-button-group
|
||||
:buttons="toolbarButtons"
|
||||
:resolve-disabled="resolveButtonDisabled"
|
||||
:resolve-loading="resolveButtonLoading"
|
||||
:resolve-label="resolveButtonLabel"
|
||||
layout-key="workbench"
|
||||
@action="handleToolbarButtonClick"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="upper-wrapper">
|
||||
<upper-table
|
||||
ref="upperTable"
|
||||
title="工作台列表"
|
||||
table-id="setting-workbench"
|
||||
:data="tableData"
|
||||
:columns="columns"
|
||||
:table-size="tableSize"
|
||||
:pagination="pagination"
|
||||
:show-index="true"
|
||||
:show-actions="true"
|
||||
:loading="loading"
|
||||
:query-time="queryTime"
|
||||
row-key="id"
|
||||
@page-change="handlePageChange"
|
||||
@page-size-change="handlePageSizeChange"
|
||||
@refresh="loadList"
|
||||
>
|
||||
<template #column-status="{ row }">
|
||||
<span :class="getStatusTextClass(formatWorkbenchStatus(row.status).type)">
|
||||
{{ formatWorkbenchStatus(row.status).text }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<template #column-device_ids="{ row }">
|
||||
<span
|
||||
v-if="Array.isArray(row.device_ids) && row.device_ids.length > 0"
|
||||
:class="getStatusTextClass('success')"
|
||||
>已绑定 {{ row.device_ids.length }} 个</span>
|
||||
<span v-else :class="getStatusTextClass('info')">未绑定</span>
|
||||
</template>
|
||||
|
||||
<template #column-created_at="{ row }">
|
||||
<el-text size="small">{{ formatTime(row.created_at) }}</el-text>
|
||||
</template>
|
||||
|
||||
<template #column-updated_at="{ row }">
|
||||
<el-text size="small">{{ formatTime(row.updated_at) }}</el-text>
|
||||
</template>
|
||||
|
||||
<template #column-actions="{ row }">
|
||||
<div class="workbench-operation-actions">
|
||||
<el-button link type="primary" size="small" @click.stop="openDetail(row)">详情</el-button>
|
||||
<el-button link type="primary" size="small" @click.stop="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="warning" size="small" @click.stop="openBind(row)">绑定</el-button>
|
||||
<el-button link type="danger" size="small" @click.stop="openResetLoginCode(row)">重置登录码</el-button>
|
||||
<el-button link type="success" size="small" @click.stop="openBindCamera(row)">摄像头</el-button>
|
||||
<el-button link type="danger" size="small" @click.stop="handleDelete(row)">删除</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">暂无工作台数据,可调整左侧筛选条件或点击新增</div>
|
||||
</template>
|
||||
</upper-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 新增 / 编辑 -->
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
:title="dialogMode === 'create' ? '新增工作台' : '编辑工作台'"
|
||||
width="520px"
|
||||
align-center
|
||||
@close="resetForm"
|
||||
>
|
||||
<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
|
||||
<el-form-item label="名称" prop="name">
|
||||
<el-input v-model="formData.name" placeholder="请输入工作台名称" maxlength="100" show-word-limit />
|
||||
</el-form-item>
|
||||
<el-form-item label="条码" prop="barcode">
|
||||
<el-input
|
||||
v-model="formData.barcode"
|
||||
placeholder="仓库内唯一,可选"
|
||||
maxlength="64"
|
||||
show-word-limit
|
||||
@blur="handleBarcodeBlur"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="barcodeCheckHint">
|
||||
<el-text :type="barcodeCheckHint.type" size="small">{{ barcodeCheckHint.text }}</el-text>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-radio-group v-model="formData.status">
|
||||
<el-radio :label="1">启用</el-radio>
|
||||
<el-radio :label="0">禁用</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="可选" maxlength="200" show-word-limit />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 详情 -->
|
||||
<el-drawer v-model="detailVisible" title="工作台详情" size="480px" @close="detailData = null">
|
||||
<div v-loading="detailLoading" class="detail-body">
|
||||
<template v-if="detailData">
|
||||
<el-descriptions :column="1" border size="small">
|
||||
<el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="仓库ID">{{ detailData.warehouse_id || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="名称">{{ detailData.name || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="条码">{{ detailData.barcode || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="状态">
|
||||
<span :class="getStatusTextClass(formatWorkbenchStatus(detailData.status).type)">
|
||||
{{ formatWorkbenchStatus(detailData.status).text }}
|
||||
</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="备注">{{ detailData.remark || '--' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="创建时间">{{ formatTime(detailData.created_at) }}</el-descriptions-item>
|
||||
<el-descriptions-item label="更新时间">{{ formatTime(detailData.updated_at) }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</template>
|
||||
<el-empty v-else-if="!detailLoading" description="暂无详情" />
|
||||
</div>
|
||||
</el-drawer>
|
||||
|
||||
<!-- 绑定摄像头 -->
|
||||
<el-dialog
|
||||
v-model="bindCameraVisible"
|
||||
:title="`绑定摄像头 — ${bindCameraWorkbenchName}`"
|
||||
width="640px"
|
||||
align-center
|
||||
@close="resetBindCamera"
|
||||
>
|
||||
<div v-loading="bindCameraLoading" class="bind-camera-body">
|
||||
<div class="bind-camera-toolbar">
|
||||
<el-input
|
||||
v-model="cameraSearchKeyword"
|
||||
placeholder="搜索摄像头名称"
|
||||
clearable
|
||||
size="small"
|
||||
style="width: 240px"
|
||||
@input="filterCameraList"
|
||||
>
|
||||
<template #prefix>
|
||||
<el-icon><Search /></el-icon>
|
||||
</template>
|
||||
</el-input>
|
||||
<div class="bind-camera-count">
|
||||
已选 <strong>{{ selectedCameraIds.length }}</strong> / {{ allCameras.length }} 个摄像头
|
||||
</div>
|
||||
</div>
|
||||
<el-checkbox-group v-model="selectedCameraIds" class="camera-checkbox-group">
|
||||
<el-checkbox
|
||||
v-for="cam in filteredCameras"
|
||||
:key="cam.id"
|
||||
:label="cam.id"
|
||||
class="camera-checkbox-item"
|
||||
>
|
||||
<div class="camera-item-info">
|
||||
<span class="camera-item-name">{{ cam.custom_name || cam.channel_name || `摄像头-${cam.id}` }}</span>
|
||||
<span class="camera-item-server">{{ cam.server?.name || '' }}</span>
|
||||
</div>
|
||||
</el-checkbox>
|
||||
</el-checkbox-group>
|
||||
<el-empty v-if="filteredCameras.length === 0 && !bindCameraLoading" description="暂无摄像头" :image-size="60" />
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="bindCameraVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="bindCameraSaving" @click="submitBindCamera">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 绑定工作台(workbench.bind):输入设备端显示的绑定码,将工作台与设备关联 -->
|
||||
<el-dialog
|
||||
v-model="bindVisible"
|
||||
title="绑定工作台"
|
||||
width="460px"
|
||||
align-center
|
||||
@close="resetBind"
|
||||
>
|
||||
<el-form ref="bindFormRef" :model="bindForm" :rules="bindRules" label-width="96px" size="small">
|
||||
<el-form-item label="目标工作台">
|
||||
<el-input :model-value="bindTargetDesc" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="绑定码" prop="code">
|
||||
<el-input
|
||||
v-model="bindForm.code"
|
||||
placeholder="请输入工作台屏幕上显示的 6 位绑定码"
|
||||
maxlength="6"
|
||||
clearable
|
||||
@input="handleBindCodeInput"
|
||||
/>
|
||||
<div class="field-tip">
|
||||
绑定码由工作台设备端生成并显示(6 位大写字母/数字)。确认绑定后,设备端将自动获取访问令牌,原工作台令牌失效。
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button size="small" @click="bindVisible = false">取消</el-button>
|
||||
<el-button size="small" type="primary" :loading="bindSaving" @click="submitBind">确认绑定</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 重置登录码(workbench.resetLoginCode):重新生成 64 位登录码,旧登录码失效 -->
|
||||
<el-dialog
|
||||
v-model="resetLoginCodeVisible"
|
||||
title="重置登录码"
|
||||
width="480px"
|
||||
align-center
|
||||
@close="closeResetLoginCode"
|
||||
>
|
||||
<div v-if="!resetResult" class="reset-login-code-body">
|
||||
<el-alert
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
title="重置后旧登录码将立即失效"
|
||||
description="将为本工作台重新生成 64 位登录码(wblc 前缀);访问令牌保持不变,不影响已绑定设备正常使用。"
|
||||
/>
|
||||
<div class="reset-target">目标工作台:{{ resetWorkbenchName || '--' }}</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="reset-login-code-result">
|
||||
<div class="result-head">
|
||||
<span class="result-title">重置成功,旧登录码已失效</span>
|
||||
</div>
|
||||
<div class="login-code-box">
|
||||
<span class="login-code-text">{{ resetResult.login_code || '--' }}</span>
|
||||
</div>
|
||||
<div class="result-tip">请将以上 64 位登录码配置到对应工作台设备(token 保持不变)。</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<template v-if="!resetResult">
|
||||
<el-button size="small" @click="resetLoginCodeVisible = false">取消</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
type="danger"
|
||||
:loading="resetLoginCodeSaving"
|
||||
@click="submitResetLoginCode"
|
||||
>
|
||||
立即重置
|
||||
</el-button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-button size="small" type="primary" @click="copyLoginCode">复制登录码</el-button>
|
||||
<el-button size="small" @click="closeResetLoginCode">完成</el-button>
|
||||
</template>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Search } from '@element-plus/icons-vue'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import ScanBox from '@/components/ScanBox/index.vue'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import OrderToolbarButtonGroup from '@/views/order/orderManagement/component/OrderToolbarButtonGroup.vue'
|
||||
import {
|
||||
getStatusTextClass,
|
||||
type ToolbarButtonConfig
|
||||
} from '@/views/order/orderManagement/config/order-common-config'
|
||||
import {
|
||||
list as workbenchList,
|
||||
detail as workbenchDetail,
|
||||
create as workbenchCreate,
|
||||
update as workbenchUpdate,
|
||||
del as workbenchDelete,
|
||||
checkBarcode as workbenchCheckBarcode,
|
||||
bindCamera as workbenchBindCamera,
|
||||
bind as workbenchBind,
|
||||
resetLoginCode as workbenchResetLoginCode
|
||||
} from '@/api/workbench/workbench'
|
||||
import { list as cameraList } from '@/api/camera/camera'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
import {
|
||||
buildWorkbenchListPayload,
|
||||
formatWorkbenchStatus,
|
||||
formatTime,
|
||||
normalizeWorkbenchScanConditionToWhere,
|
||||
workbenchColumns,
|
||||
workbenchScanFields,
|
||||
type WorkbenchDetail,
|
||||
type WorkbenchRecord
|
||||
} from './workbench-config'
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
const scanBox = ref<any>(null)
|
||||
const upperTable = ref<any>(null)
|
||||
|
||||
const presetTree = ref<any[]>([])
|
||||
const availableFieldsRef = reactive(JSON.parse(JSON.stringify(workbenchScanFields)))
|
||||
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
const containerHeight = computed(() =>
|
||||
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
|
||||
)
|
||||
|
||||
const columns = workbenchColumns
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const tableData = ref<WorkbenchRecord[]>([])
|
||||
const queryTime = ref(0)
|
||||
const tableSize = ref<'small' | 'default' | 'large'>('small')
|
||||
const currentConditionRaw = ref<any>(null)
|
||||
|
||||
// ---- toolbar 按钮配置(分类排序,对齐 waveOrder) ----
|
||||
const toolbarButtons: ToolbarButtonConfig[] = [
|
||||
{ key: 'refresh', label: '刷新', category: 'refresh', size: 'small', action: 'loadList' },
|
||||
{ key: 'create', label: '新增工作台', category: 'action', size: 'small', action: 'openCreate' }
|
||||
]
|
||||
|
||||
function resolveButtonDisabled(_key?: string): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
function resolveButtonLoading(key?: string): boolean {
|
||||
if (key === 'loading') return loading.value
|
||||
return false
|
||||
}
|
||||
|
||||
function resolveButtonLabel(defaultLabel: string, _dynamicLabelKey?: string): string {
|
||||
return defaultLabel
|
||||
}
|
||||
|
||||
const toolbarActionMap: Record<string, () => void> = {
|
||||
loadList,
|
||||
openCreate
|
||||
}
|
||||
|
||||
function handleToolbarButtonClick(action: string) {
|
||||
toolbarActionMap[action]?.()
|
||||
}
|
||||
|
||||
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const dialogMode = ref<'create' | 'edit'>('create')
|
||||
const formRef = ref<FormInstance>()
|
||||
const formData = reactive({
|
||||
id: undefined as number | undefined,
|
||||
name: '',
|
||||
barcode: '',
|
||||
status: 1,
|
||||
remark: ''
|
||||
})
|
||||
|
||||
const barcodeCheckHint = ref<{ text: string; type: 'success' | 'warning' | 'danger' | 'info' } | null>(null)
|
||||
|
||||
const rules: FormRules = {
|
||||
name: [{ required: true, message: '请输入工作台名称', trigger: 'blur' }],
|
||||
status: [{ required: true, message: '请选择状态', trigger: 'change' }]
|
||||
}
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detailData = ref<WorkbenchDetail | null>(null)
|
||||
|
||||
const isSuccess = (res: any) => res && [0, 1, 200].includes(res.code)
|
||||
|
||||
// ─── 列表 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function loadList() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
const start = Date.now()
|
||||
try {
|
||||
const where = normalizeWorkbenchScanConditionToWhere(currentConditionRaw.value)
|
||||
const res: any = await workbenchList(
|
||||
buildWorkbenchListPayload({
|
||||
page: pagination.currentPage,
|
||||
pageSize: pagination.pageSize,
|
||||
where
|
||||
})
|
||||
)
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '获取工作台列表失败')
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
return
|
||||
}
|
||||
const data = res?.data || res
|
||||
tableData.value = data.list || []
|
||||
pagination.total = Number(data.pagination?.total ?? data.total ?? 0)
|
||||
} catch {
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
ElMessage.error('获取工作台列表失败')
|
||||
} finally {
|
||||
queryTime.value = Date.now() - start
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
// ─── 筛选 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function handleConditionChange(condition: any) {
|
||||
currentConditionRaw.value = condition
|
||||
}
|
||||
|
||||
function handleConditionReset() {
|
||||
currentConditionRaw.value = null
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handleConditionClear() {
|
||||
currentConditionRaw.value = null
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
// ─── 新增 / 编辑 ─────────────────────────────────────────────────────────────
|
||||
|
||||
function resetFormData() {
|
||||
formData.id = undefined
|
||||
formData.name = ''
|
||||
formData.barcode = ''
|
||||
formData.status = 1
|
||||
formData.remark = ''
|
||||
barcodeCheckHint.value = null
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
dialogMode.value = 'create'
|
||||
resetFormData()
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(row: WorkbenchRecord) {
|
||||
dialogMode.value = 'edit'
|
||||
resetFormData()
|
||||
formData.id = row.id
|
||||
formData.name = row.name || ''
|
||||
formData.barcode = row.barcode || ''
|
||||
formData.status = row.status ?? 1
|
||||
formData.remark = row.remark || ''
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
formRef.value?.resetFields()
|
||||
resetFormData()
|
||||
}
|
||||
|
||||
async function handleBarcodeBlur() {
|
||||
const code = formData.barcode?.trim()
|
||||
if (!code) {
|
||||
barcodeCheckHint.value = null
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await workbenchCheckBarcode({
|
||||
barcode: code,
|
||||
excludeId: formData.id
|
||||
})
|
||||
if (isSuccess(res)) {
|
||||
const exists = res?.data?.exists
|
||||
if (exists) {
|
||||
barcodeCheckHint.value = { text: '该条码已存在', type: 'danger' }
|
||||
} else {
|
||||
barcodeCheckHint.value = { text: '条码可用', type: 'success' }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 静默处理,不阻塞用户
|
||||
}
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const payload: any = {
|
||||
name: formData.name,
|
||||
status: formData.status
|
||||
}
|
||||
if (formData.barcode?.trim()) payload.barcode = formData.barcode.trim()
|
||||
if (formData.remark?.trim()) payload.remark = formData.remark.trim()
|
||||
|
||||
let res: any
|
||||
if (dialogMode.value === 'create') {
|
||||
res = await workbenchCreate(payload)
|
||||
} else {
|
||||
res = await workbenchUpdate({ id: formData.id!, ...payload })
|
||||
}
|
||||
|
||||
if (isSuccess(res)) {
|
||||
ElMessage.success(dialogMode.value === 'create' ? '新增成功' : '更新成功')
|
||||
dialogVisible.value = false
|
||||
loadList()
|
||||
} else {
|
||||
ElMessage.error(res?.message || (dialogMode.value === 'create' ? '新增失败' : '更新失败'))
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error(dialogMode.value === 'create' ? '新增失败' : '更新失败')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 详情 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function openDetail(row: WorkbenchRecord) {
|
||||
if (!row.id) return
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
detailData.value = null
|
||||
try {
|
||||
const res: any = await workbenchDetail({ id: row.id })
|
||||
if (isSuccess(res)) {
|
||||
detailData.value = res?.data?.data ?? res?.data ?? null
|
||||
} else {
|
||||
ElMessage.error(res?.message || '获取详情失败')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('获取详情失败')
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 绑定摄像头 ──────────────────────────────────────────────────────────────
|
||||
|
||||
type CameraOption = {
|
||||
id: number
|
||||
channel_name?: string
|
||||
custom_name?: string
|
||||
server?: { id?: number; name?: string }
|
||||
}
|
||||
|
||||
const bindCameraVisible = ref(false)
|
||||
const bindCameraLoading = ref(false)
|
||||
const bindCameraSaving = ref(false)
|
||||
const bindCameraWorkbenchId = ref<number | undefined>(undefined)
|
||||
const bindCameraWorkbenchName = ref('')
|
||||
const allCameras = ref<CameraOption[]>([])
|
||||
const filteredCameras = ref<CameraOption[]>([])
|
||||
const selectedCameraIds = ref<number[]>([])
|
||||
const cameraSearchKeyword = ref('')
|
||||
|
||||
function filterCameraList() {
|
||||
const keyword = cameraSearchKeyword.value.trim().toLowerCase()
|
||||
if (!keyword) {
|
||||
filteredCameras.value = allCameras.value
|
||||
return
|
||||
}
|
||||
filteredCameras.value = allCameras.value.filter((cam) => {
|
||||
const name = (cam.custom_name || cam.channel_name || '').toLowerCase()
|
||||
const server = (cam.server?.name || '').toLowerCase()
|
||||
return name.includes(keyword) || server.includes(keyword)
|
||||
})
|
||||
}
|
||||
|
||||
async function openBindCamera(row: WorkbenchRecord) {
|
||||
if (!row.id) return
|
||||
bindCameraWorkbenchId.value = row.id
|
||||
bindCameraWorkbenchName.value = row.name || `工作台-${row.id}`
|
||||
bindCameraVisible.value = true
|
||||
bindCameraLoading.value = true
|
||||
cameraSearchKeyword.value = ''
|
||||
|
||||
// 从列表行数据中直接读取已绑定的 device_ids
|
||||
selectedCameraIds.value = Array.isArray(row.device_ids) ? [...row.device_ids] : []
|
||||
|
||||
try {
|
||||
const camRes: any = await cameraList({ pagination: { page: 1, pageSize: 999 } })
|
||||
if (isSuccess(camRes)) {
|
||||
allCameras.value = camRes?.list || []
|
||||
} else {
|
||||
allCameras.value = []
|
||||
}
|
||||
filterCameraList()
|
||||
} catch {
|
||||
allCameras.value = []
|
||||
filteredCameras.value = []
|
||||
} finally {
|
||||
bindCameraLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetBindCamera() {
|
||||
bindCameraWorkbenchId.value = undefined
|
||||
bindCameraWorkbenchName.value = ''
|
||||
allCameras.value = []
|
||||
filteredCameras.value = []
|
||||
selectedCameraIds.value = []
|
||||
cameraSearchKeyword.value = ''
|
||||
}
|
||||
|
||||
async function submitBindCamera() {
|
||||
if (bindCameraWorkbenchId.value === undefined || bindCameraSaving.value) return
|
||||
|
||||
bindCameraSaving.value = true
|
||||
try {
|
||||
const res: any = await workbenchBindCamera({
|
||||
id: bindCameraWorkbenchId.value,
|
||||
camera_ids: selectedCameraIds.value.length > 0 ? selectedCameraIds.value : undefined
|
||||
})
|
||||
if (isSuccess(res)) {
|
||||
ElMessage.success('摄像头绑定更新成功')
|
||||
bindCameraVisible.value = false
|
||||
loadList()
|
||||
} else {
|
||||
ElMessage.error(res?.message || '绑定失败')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('绑定失败')
|
||||
} finally {
|
||||
bindCameraSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 绑定工作台(workbench.bind) ────────────────────────────────────────────
|
||||
|
||||
const bindVisible = ref(false)
|
||||
const bindSaving = ref(false)
|
||||
const bindFormRef = ref<FormInstance>()
|
||||
const bindWorkbenchId = ref<number | undefined>(undefined)
|
||||
const bindWorkbenchName = ref('')
|
||||
const bindForm = reactive({ code: '' })
|
||||
|
||||
const bindTargetDesc = computed(() => {
|
||||
const name = bindWorkbenchName.value || '工作台'
|
||||
return bindWorkbenchId.value != null ? `${name}(ID: ${bindWorkbenchId.value})` : name
|
||||
})
|
||||
|
||||
const bindRules: FormRules = {
|
||||
code: [
|
||||
{ required: true, message: '请输入绑定码', trigger: 'blur' },
|
||||
{ pattern: /^[A-Z0-9]{6}$/, message: '绑定码为 6 位大写字母或数字', trigger: 'blur' }
|
||||
]
|
||||
}
|
||||
|
||||
function handleBindCodeInput() {
|
||||
bindForm.code = String(bindForm.code || '')
|
||||
.replace(/[^a-zA-Z0-9]/g, '')
|
||||
.toUpperCase()
|
||||
.slice(0, 6)
|
||||
}
|
||||
|
||||
function openBind(row: WorkbenchRecord) {
|
||||
if (!row.id) return
|
||||
bindWorkbenchId.value = row.id
|
||||
bindWorkbenchName.value = row.name || `工作台-${row.id}`
|
||||
bindForm.code = ''
|
||||
bindVisible.value = true
|
||||
nextTick(() => bindFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function resetBind() {
|
||||
bindForm.code = ''
|
||||
bindWorkbenchId.value = undefined
|
||||
bindWorkbenchName.value = ''
|
||||
bindFormRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
async function submitBind() {
|
||||
if (bindWorkbenchId.value === undefined || bindSaving.value) return
|
||||
const valid = await bindFormRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
bindSaving.value = true
|
||||
try {
|
||||
const res: any = await workbenchBind({
|
||||
id: bindWorkbenchId.value,
|
||||
code: bindForm.code
|
||||
})
|
||||
if (isSuccess(res)) {
|
||||
ElMessage.success('绑定成功,设备端将自动获取访问令牌')
|
||||
bindVisible.value = false
|
||||
loadList()
|
||||
} else {
|
||||
ElMessage.error(res?.message || '绑定失败,请核对绑定码是否有效')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('绑定失败,请稍后重试')
|
||||
} finally {
|
||||
bindSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 重置登录码(workbench.resetLoginCode) ─────────────────────────────────
|
||||
|
||||
const resetLoginCodeVisible = ref(false)
|
||||
const resetLoginCodeSaving = ref(false)
|
||||
const resetWorkbenchId = ref<number | undefined>(undefined)
|
||||
const resetWorkbenchName = ref('')
|
||||
const resetResult = ref<{ id?: number; login_code?: string } | null>(null)
|
||||
|
||||
function openResetLoginCode(row: WorkbenchRecord) {
|
||||
if (!row.id) return
|
||||
resetWorkbenchId.value = row.id
|
||||
resetWorkbenchName.value = row.name || `工作台-${row.id}`
|
||||
resetResult.value = null
|
||||
resetLoginCodeVisible.value = true
|
||||
}
|
||||
|
||||
function closeResetLoginCode() {
|
||||
resetLoginCodeVisible.value = false
|
||||
resetResult.value = null
|
||||
}
|
||||
|
||||
async function submitResetLoginCode() {
|
||||
if (resetWorkbenchId.value === undefined || resetLoginCodeSaving.value) return
|
||||
resetLoginCodeSaving.value = true
|
||||
resetResult.value = null
|
||||
try {
|
||||
const res: any = await workbenchResetLoginCode({ id: resetWorkbenchId.value })
|
||||
if (isSuccess(res)) {
|
||||
const data: any = res?.data ?? res ?? {}
|
||||
const payload = data?.data && typeof data.data === 'object' ? data.data : data
|
||||
resetResult.value = {
|
||||
id: payload?.id,
|
||||
login_code: payload?.login_code ?? ''
|
||||
}
|
||||
ElMessage.success('登录码已重置')
|
||||
} else {
|
||||
ElMessage.error(res?.message || '重置登录码失败')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('重置登录码失败,请稍后重试')
|
||||
} finally {
|
||||
resetLoginCodeSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyLoginCode() {
|
||||
const code = String(resetResult.value?.login_code || '')
|
||||
if (!code) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(code)
|
||||
ElMessage.success('登录码已复制')
|
||||
} catch {
|
||||
const ta = document.createElement('textarea')
|
||||
ta.value = code
|
||||
ta.style.position = 'fixed'
|
||||
ta.style.opacity = '0'
|
||||
document.body.appendChild(ta)
|
||||
ta.select()
|
||||
try {
|
||||
document.execCommand('copy')
|
||||
ElMessage.success('登录码已复制')
|
||||
} catch {
|
||||
ElMessage.error('复制失败,请手动复制')
|
||||
} finally {
|
||||
document.body.removeChild(ta)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 删除 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function handleDelete(row: WorkbenchRecord) {
|
||||
if (!row.id) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`确定要删除工作台「${row.name || row.id}」吗?删除后数据不可恢复。`,
|
||||
'删除确认',
|
||||
{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const res: any = await workbenchDelete({ id: row.id })
|
||||
if (isSuccess(res)) {
|
||||
ElMessage.success('删除成功')
|
||||
loadList()
|
||||
} else {
|
||||
ElMessage.error(res?.message || '删除失败')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('删除失败')
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 初始化 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
onMounted(() => {
|
||||
loadList()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@use "../../../order/orderManagement/styles/order-sub.scss";
|
||||
|
||||
.workbench-operation-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 2px;
|
||||
justify-content: center;
|
||||
|
||||
:deep(.el-button) {
|
||||
font-size: 11px;
|
||||
padding: 0 4px;
|
||||
height: 20px;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
:deep(.el-button + .el-button) {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
:deep(.el-button.is-link) {
|
||||
padding: 0 4px;
|
||||
height: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 绑定摄像头弹窗 ──────────────────────────────────────────────────────────
|
||||
.bind-camera-body {
|
||||
min-height: 280px;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.bind-camera-toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.bind-camera-count {
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
}
|
||||
|
||||
.camera-checkbox-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.camera-checkbox-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #ebeef5;
|
||||
border-radius: 6px;
|
||||
margin-right: 0;
|
||||
transition: background 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: #f5f7fa;
|
||||
}
|
||||
}
|
||||
|
||||
.camera-item-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-left: 4px;
|
||||
|
||||
.camera-item-name {
|
||||
font-size: 14px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.camera-item-server {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 绑定工作台 / 重置登录码弹窗 ─────────────────────────────────────────────
|
||||
.field-tip {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.reset-login-code-body {
|
||||
.reset-target {
|
||||
margin-top: 16px;
|
||||
font-size: 13px;
|
||||
color: #303133;
|
||||
}
|
||||
}
|
||||
|
||||
.reset-login-code-result {
|
||||
text-align: center;
|
||||
|
||||
.result-head {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 16px;
|
||||
|
||||
.result-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #67c23a;
|
||||
}
|
||||
}
|
||||
|
||||
.login-code-box {
|
||||
padding: 12px;
|
||||
background: #f5f7fa;
|
||||
border: 1px dashed #dcdfe6;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 10px;
|
||||
word-break: break-all;
|
||||
|
||||
.login-code-text {
|
||||
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 14px;
|
||||
color: #303133;
|
||||
user-select: text;
|
||||
}
|
||||
}
|
||||
|
||||
.result-tip {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -1,154 +0,0 @@
|
||||
export type WorkbenchRecord = {
|
||||
id?: number
|
||||
warehouse_id?: number
|
||||
name?: string
|
||||
barcode?: string
|
||||
status?: number
|
||||
type?: string
|
||||
remark?: string
|
||||
device_ids?: number[] | null
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
deleted_at?: string | null
|
||||
}
|
||||
|
||||
export type WorkbenchDetail = WorkbenchRecord
|
||||
|
||||
export const workbenchColumns = [
|
||||
{ prop: 'id', label: 'ID', width: '80', sortable: true },
|
||||
{ prop: 'name', label: '工作台名称', minWidth: '140', showOverflowTooltip: true },
|
||||
{ prop: 'barcode', label: '条码', minWidth: '120', showOverflowTooltip: true },
|
||||
{ prop: 'warehouse_id', label: '仓库ID', width: '100' },
|
||||
{ prop: 'status', label: '状态', width: '80' },
|
||||
{ prop: 'remark', label: '备注', minWidth: '140', showOverflowTooltip: true },
|
||||
{ prop: 'device_ids', label: '绑定摄像头', width: '120' },
|
||||
{ prop: 'created_at', label: '创建时间', minWidth: '160' },
|
||||
{ prop: 'updated_at', label: '更新时间', minWidth: '160' },
|
||||
{ prop: 'actions', label: '操作', width: '400', fixed: 'right' }
|
||||
]
|
||||
|
||||
export const workbenchScanFields = [
|
||||
{
|
||||
value: 'quickWhere',
|
||||
label: '关键词',
|
||||
type: 'text',
|
||||
placeholder: '名称/条码',
|
||||
operators: ['contains'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'name',
|
||||
label: '名称',
|
||||
type: 'text',
|
||||
placeholder: '请输入工作台名称',
|
||||
operators: ['eq', 'contains', 'like'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'barcode',
|
||||
label: '条码',
|
||||
type: 'text',
|
||||
placeholder: '请输入条码',
|
||||
operators: ['eq', 'contains', 'like'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'status',
|
||||
label: '状态',
|
||||
type: 'select',
|
||||
clearable: true,
|
||||
options: [
|
||||
{ label: '启用', value: '1' },
|
||||
{ label: '禁用', value: '0' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
export function formatWorkbenchStatus(status: unknown): { text: string; type: 'success' | 'info' } {
|
||||
const v = Number(status ?? 1)
|
||||
return v === 1 ? { text: '启用', type: 'success' } : { text: '禁用', type: 'info' }
|
||||
}
|
||||
|
||||
function pad(n: number) {
|
||||
return String(n).padStart(2, '0')
|
||||
}
|
||||
|
||||
export function formatTime(value: unknown): string {
|
||||
if (!value) return '--'
|
||||
const d = new Date(value as string)
|
||||
if (isNaN(d.getTime())) return String(value)
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
function getFieldConfig(key: string, fields: typeof workbenchScanFields) {
|
||||
return fields.find((f) => f.value === key)
|
||||
}
|
||||
|
||||
function mapFieldType(type: string, value: unknown) {
|
||||
if (typeof value === 'number') return 'number'
|
||||
return 'text'
|
||||
}
|
||||
|
||||
function processConditionValue(key: string, raw: any, fields: typeof workbenchScanFields) {
|
||||
if (key === 'quickWhere') {
|
||||
const val = raw?.value !== undefined ? raw.value : raw
|
||||
const text = val == null ? '' : String(val).trim()
|
||||
return text ? text : null
|
||||
}
|
||||
|
||||
const config = getFieldConfig(key, fields)
|
||||
const fieldType = config?.type || 'text'
|
||||
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
const op = raw.operator || (fieldType === 'select' ? 'eq' : 'contains')
|
||||
const type = raw.type || mapFieldType(fieldType, raw.value)
|
||||
const value = raw.value
|
||||
|
||||
if (fieldType === 'select') {
|
||||
return { operator: 'eq', value: value != null ? Number(value) : undefined }
|
||||
}
|
||||
return { operator: op, type, value }
|
||||
}
|
||||
|
||||
if (fieldType === 'select') {
|
||||
return raw != null ? { operator: 'eq', value: Number(raw) } : null
|
||||
}
|
||||
if (fieldType === 'number' && raw != null) {
|
||||
return { operator: 'eq', value: Number(raw) }
|
||||
}
|
||||
|
||||
return raw != null ? raw : null
|
||||
}
|
||||
|
||||
export function normalizeWorkbenchScanConditionToWhere(rawCondition: any): Record<string, unknown> {
|
||||
if (!rawCondition) return {}
|
||||
|
||||
const where: Record<string, unknown> = {}
|
||||
const entries = Array.isArray(rawCondition) ? rawCondition : Object.entries(rawCondition)
|
||||
|
||||
for (const [key, raw] of entries) {
|
||||
const processed = processConditionValue(String(key), raw, workbenchScanFields)
|
||||
if (processed == null) continue
|
||||
|
||||
if (key === 'quickWhere') {
|
||||
where.name = { operator: 'contains', value: processed }
|
||||
where.barcode = { operator: 'contains', value: processed }
|
||||
continue
|
||||
}
|
||||
|
||||
where[key] = processed
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
|
||||
export function buildWorkbenchListPayload(params: {
|
||||
page: number
|
||||
pageSize: number
|
||||
where?: Record<string, unknown>
|
||||
}) {
|
||||
return {
|
||||
pagination: { page: params.page, pageSize: params.pageSize },
|
||||
where: params.where || {}
|
||||
}
|
||||
}
|
||||
@ -1,192 +0,0 @@
|
||||
<template>
|
||||
<div class="camera-player" ref="containerRef">
|
||||
<div v-if="!ready" class="camera-player__loading">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
<span>加载播放插件…</span>
|
||||
</div>
|
||||
<iframe
|
||||
ref="iframeRef"
|
||||
:src="playerUrl"
|
||||
class="camera-player__iframe"
|
||||
frameborder="0"
|
||||
allow="autoplay"
|
||||
@load="handleIframeLoad"
|
||||
@error="handleIframeError"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onBeforeUnmount, watch } from 'vue'
|
||||
import { Loading } from '@element-plus/icons-vue'
|
||||
|
||||
export interface PlayerLoginParams {
|
||||
ip: string
|
||||
port?: number
|
||||
user: string
|
||||
pass: string
|
||||
}
|
||||
|
||||
export interface PlayerStartParams {
|
||||
channel: number
|
||||
streamType?: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
loginParams: PlayerLoginParams | null
|
||||
startParams: PlayerStartParams | null
|
||||
autoPlay?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
ready: []
|
||||
loginSuccess: [device: string]
|
||||
loginError: [status: number]
|
||||
playSuccess: [device: string, channel: number]
|
||||
playError: [status: number]
|
||||
error: [message: string]
|
||||
}>()
|
||||
|
||||
const containerRef = ref<HTMLElement | null>(null)
|
||||
const iframeRef = ref<HTMLIFrameElement | null>(null)
|
||||
const ready = ref(false)
|
||||
|
||||
const playerUrl = '/hikvision/player.html'
|
||||
|
||||
function sendMessage(data: Record<string, unknown>) {
|
||||
const iframe = iframeRef.value
|
||||
if (iframe?.contentWindow) {
|
||||
iframe.contentWindow.postMessage(JSON.stringify(data), '*')
|
||||
}
|
||||
}
|
||||
|
||||
function handleIframeLoad() {
|
||||
// iframe 加载完成后,等待 ready 消息
|
||||
}
|
||||
|
||||
function handleIframeError() {
|
||||
emit('error', '播放器加载失败')
|
||||
}
|
||||
|
||||
// 监听来自 iframe 的消息
|
||||
function handleMessage(e: MessageEvent) {
|
||||
let data: Record<string, any>
|
||||
try {
|
||||
data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
switch (data.type) {
|
||||
case 'ready':
|
||||
ready.value = true
|
||||
emit('ready')
|
||||
// 就绪后自动登录
|
||||
if (props.loginParams) {
|
||||
sendMessage({ type: 'login', ...props.loginParams })
|
||||
}
|
||||
break
|
||||
case 'loginSuccess':
|
||||
emit('loginSuccess', data.device)
|
||||
// 登录成功后自动播放
|
||||
if (props.startParams && props.autoPlay !== false) {
|
||||
sendMessage({ type: 'startRealPlay', ...props.startParams })
|
||||
}
|
||||
break
|
||||
case 'loginError':
|
||||
emit('loginError', data.status)
|
||||
break
|
||||
case 'playSuccess':
|
||||
emit('playSuccess', data.device, data.channel)
|
||||
break
|
||||
case 'playError':
|
||||
emit('playError', data.status)
|
||||
break
|
||||
case 'error':
|
||||
emit('error', data.msg || data.code || '播放异常')
|
||||
break
|
||||
case 'playbackEnd':
|
||||
case 'networkError':
|
||||
// 可自行处理
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 登录
|
||||
function login(params: PlayerLoginParams) {
|
||||
sendMessage({ type: 'login', ...params })
|
||||
}
|
||||
|
||||
// 开始播放
|
||||
function startRealPlay(params: PlayerStartParams) {
|
||||
sendMessage({ type: 'startRealPlay', ...params })
|
||||
}
|
||||
|
||||
// 停止播放
|
||||
function stop() {
|
||||
sendMessage({ type: 'stop' })
|
||||
}
|
||||
|
||||
// 登出
|
||||
function logout() {
|
||||
sendMessage({ type: 'logout' })
|
||||
}
|
||||
|
||||
// 监听 props 变化
|
||||
watch(() => props.loginParams, (val) => {
|
||||
if (val && ready.value) {
|
||||
sendMessage({ type: 'login', ...val })
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => props.startParams, (val) => {
|
||||
if (val && ready.value) {
|
||||
sendMessage({ type: 'startRealPlay', ...val })
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stop()
|
||||
logout()
|
||||
window.removeEventListener('message', handleMessage)
|
||||
})
|
||||
|
||||
// 挂载消息监听
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('message', handleMessage)
|
||||
}
|
||||
|
||||
defineExpose({ login, startRealPlay, stop, logout })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.camera-player {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 360px;
|
||||
background: #000;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.camera-player__loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: #909399;
|
||||
font-size: 13px;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.camera-player__iframe {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 400px;
|
||||
border: none;
|
||||
z-index: 2;
|
||||
}
|
||||
</style>
|
||||
@ -1,314 +0,0 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
title="摄像头预览"
|
||||
width="800px"
|
||||
align-center
|
||||
destroy-on-close
|
||||
@update:model-value="onDialogVisibleChange"
|
||||
@closed="handleClosed"
|
||||
>
|
||||
<div class="preview-container">
|
||||
<div v-if="error" class="preview-error">
|
||||
<p class="preview-error-title">服务暂不可用</p>
|
||||
<p class="preview-error-sub">{{ error }}</p>
|
||||
<el-button v-if="errorLink" type="primary" size="small" class="preview-error-btn" @click="openDownload">
|
||||
下载打印控件
|
||||
</el-button>
|
||||
</div>
|
||||
<div v-else-if="streamReady && streamSrc" class="preview-video-wrapper">
|
||||
<img
|
||||
ref="videoImgRef"
|
||||
:key="streamKey"
|
||||
:src="streamSrc"
|
||||
class="preview-video"
|
||||
/>
|
||||
<div v-if="retryHint" class="preview-hint">{{ retryHint }}</div>
|
||||
</div>
|
||||
<div v-else class="preview-placeholder">
|
||||
{{ loading ? '正在获取流地址…' : streamSrc ? '正在连接录像机…' : '正在连接…' }}
|
||||
</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="onDialogVisibleChange(false)">关闭</el-button>
|
||||
<el-button type="primary" :loading="loading" @click="reloadStream">刷新</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, nextTick } from 'vue'
|
||||
import { getLiveStreamUrl } from '@/api/camera_server/localServerApi'
|
||||
import { list as serverList, detail as serverDetail } from '@/api/camera_server/camera_server'
|
||||
|
||||
export interface CameraPreviewRow {
|
||||
id?: number
|
||||
server_id?: number
|
||||
channel_id?: number
|
||||
channel_name?: string
|
||||
custom_name?: string
|
||||
ip?: string
|
||||
port?: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
cameraRow: CameraPreviewRow | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: boolean]
|
||||
}>()
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const errorLink = ref(false)
|
||||
const retryHint = ref('')
|
||||
const streamReady = ref(false)
|
||||
const streamKey = ref(0)
|
||||
const videoImgRef = ref<HTMLImageElement | null>(null)
|
||||
let probeAbort: AbortController | null = null
|
||||
|
||||
const nvrIp = ref('')
|
||||
const nvrPort = ref<number | undefined>(undefined)
|
||||
const nvrUser = ref('')
|
||||
const nvrPass = ref('')
|
||||
const internalIp = ref('')
|
||||
const publicIp = ref('')
|
||||
const internalPort = ref<number | undefined>(undefined)
|
||||
const publicPort = ref<number | undefined>(undefined)
|
||||
const serverCache = ref<Record<number, any>>({})
|
||||
|
||||
const streamSrc = computed(() => {
|
||||
const row = props.cameraRow
|
||||
if (!row || !row.channel_id || !nvrIp.value || !nvrUser.value || !nvrPass.value) return null
|
||||
return getLiveStreamUrl({
|
||||
ip: nvrIp.value,
|
||||
user: nvrUser.value,
|
||||
pass: nvrPass.value,
|
||||
channel: row.channel_id,
|
||||
streamType: 0,
|
||||
port: nvrPort.value
|
||||
})
|
||||
})
|
||||
|
||||
const ok = (res: any) => res && [0, 1, 200].includes(res.code)
|
||||
|
||||
async function getServerInfo(id: number) {
|
||||
if (serverCache.value[id]) return serverCache.value[id]
|
||||
try {
|
||||
const res: any = await serverList({ pagination: { page: 1, pageSize: 999 } })
|
||||
if (ok(res)) {
|
||||
for (const item of res?.list || []) {
|
||||
if (item.id) serverCache.value[item.id] = item
|
||||
}
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
return serverCache.value[id] || null
|
||||
}
|
||||
|
||||
async function init() {
|
||||
const row = props.cameraRow
|
||||
if (!row) return
|
||||
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
errorLink.value = false
|
||||
retryHint.value = ''
|
||||
nvrIp.value = ''
|
||||
nvrPort.value = undefined
|
||||
internalIp.value = ''
|
||||
internalPort.value = undefined
|
||||
publicIp.value = ''
|
||||
publicPort.value = undefined
|
||||
|
||||
const sid = row.server_id
|
||||
if (!sid) { error.value = '未关联录像服务器'; loading.value = false; return }
|
||||
|
||||
const srv = await getServerInfo(sid)
|
||||
if (!srv) { error.value = '未找到服务器信息'; loading.value = false; return }
|
||||
|
||||
let pwd = srv.password
|
||||
if (!pwd) {
|
||||
try {
|
||||
const d: any = await serverDetail({ id: sid })
|
||||
if (ok(d) && d?.data?.password) pwd = d.data.password
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
if (!pwd) { error.value = '缺少服务器密码'; loading.value = false; return }
|
||||
|
||||
internalIp.value = (srv.internal_ip || '').trim()
|
||||
internalPort.value = srv.internal_port || srv.port
|
||||
publicIp.value = (srv.public_ip || '').trim()
|
||||
publicPort.value = srv.public_port || srv.port
|
||||
nvrUser.value = srv.username || ''
|
||||
nvrPass.value = pwd
|
||||
|
||||
const ip = internalIp.value || publicIp.value
|
||||
if (!ip) { error.value = '服务器未配置 IP'; loading.value = false; return }
|
||||
|
||||
nvrIp.value = ip
|
||||
nvrPort.value = internalIp.value ? internalPort.value : publicPort.value
|
||||
streamReady.value = false
|
||||
loading.value = false
|
||||
|
||||
// 用 fetch 探测流端点是否可达(502 等错误 <img> 不会触发 @error)
|
||||
await probeStream()
|
||||
}
|
||||
|
||||
/** fetch 探测流地址,成功后才让 <img> 渲染 */
|
||||
async function probeStream() {
|
||||
if (probeAbort) { probeAbort.abort(); probeAbort = null }
|
||||
|
||||
const url = streamSrc.value
|
||||
if (!url) return
|
||||
|
||||
probeAbort = new AbortController()
|
||||
const { signal } = probeAbort
|
||||
const t = setTimeout(() => probeAbort?.abort(), 8000)
|
||||
|
||||
try {
|
||||
const resp = await fetch(url, { signal })
|
||||
clearTimeout(t)
|
||||
if (!signal.aborted && resp.ok) {
|
||||
streamReady.value = true
|
||||
} else if (!signal.aborted) {
|
||||
// HTTP 错误(502 等)→ NVR 不通
|
||||
await handleProbeFail('nvr')
|
||||
}
|
||||
} catch (e: any) {
|
||||
clearTimeout(t)
|
||||
if (signal.aborted) return
|
||||
// 网络错误(连接拒绝等)→ 本地代理未启动
|
||||
await handleProbeFail(e.name === 'TypeError' ? 'proxy' : 'nvr')
|
||||
}
|
||||
}
|
||||
|
||||
/** 探测失败:尝试公网 IP 回退,或显示错误 */
|
||||
async function handleProbeFail(reason: 'proxy' | 'nvr') {
|
||||
stopStream()
|
||||
nvrIp.value = ''
|
||||
nvrPort.value = undefined
|
||||
streamReady.value = false
|
||||
|
||||
// 本地代理未启动
|
||||
if (reason === 'proxy') {
|
||||
error.value = '本地打印服务未启动,请下载安装后再试'
|
||||
errorLink.value = true
|
||||
return
|
||||
}
|
||||
|
||||
// NVR 不通,尝试公网 IP 回退
|
||||
if (internalIp.value && nvrIp.value !== publicIp.value && publicIp.value && publicIp.value !== internalIp.value) {
|
||||
retryHint.value = '内网无法访问,正在尝试公网…'
|
||||
nvrIp.value = ''
|
||||
nvrPort.value = undefined
|
||||
await nextTick()
|
||||
nvrIp.value = publicIp.value
|
||||
nvrPort.value = publicPort.value
|
||||
streamKey.value++
|
||||
retryHint.value = ''
|
||||
await nextTick()
|
||||
await probeStream()
|
||||
return
|
||||
}
|
||||
|
||||
const tried = [internalIp.value, publicIp.value].filter(Boolean).join('、')
|
||||
error.value = `无法连接录像机(已尝试:${tried}),请检查网络或服务器配置`
|
||||
}
|
||||
|
||||
function reloadStream() {
|
||||
if (probeAbort) { probeAbort.abort(); probeAbort = null }
|
||||
streamReady.value = false
|
||||
streamKey.value++
|
||||
init()
|
||||
}
|
||||
|
||||
function stopStream() {
|
||||
if (probeAbort) { probeAbort.abort(); probeAbort = null }
|
||||
if (videoImgRef.value) videoImgRef.value.src = ''
|
||||
}
|
||||
|
||||
function openDownload() {
|
||||
window.open('/download', '_blank')
|
||||
}
|
||||
|
||||
function onDialogVisibleChange(val: boolean) {
|
||||
if (!val) stopStream()
|
||||
emit('update:modelValue', val)
|
||||
}
|
||||
|
||||
function handleClosed() {
|
||||
error.value = ''
|
||||
errorLink.value = false
|
||||
retryHint.value = ''
|
||||
streamReady.value = false
|
||||
nvrIp.value = ''
|
||||
nvrPort.value = undefined
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (v) => {
|
||||
if (v) {
|
||||
if (probeAbort) { probeAbort.abort(); probeAbort = null }
|
||||
streamReady.value = false
|
||||
streamKey.value++
|
||||
init()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.preview-container {
|
||||
min-height: 200px;
|
||||
}
|
||||
.preview-video-wrapper {
|
||||
background: #000;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
line-height: 0;
|
||||
}
|
||||
.preview-video {
|
||||
width: 100%;
|
||||
min-height: 360px;
|
||||
display: block;
|
||||
object-fit: contain;
|
||||
background: #000;
|
||||
}
|
||||
.preview-hint {
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
color: #e6a23c;
|
||||
background: #fdf6ec;
|
||||
}
|
||||
.preview-error {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 360px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 4px;
|
||||
text-align: center;
|
||||
}
|
||||
.preview-error-title {
|
||||
font-size: 18px;
|
||||
color: #e6a23c;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.preview-error-sub {
|
||||
font-size: 13px;
|
||||
color: #909399;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.preview-error-btn {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.preview-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 200px;
|
||||
color: #909399;
|
||||
font-size: 14px;
|
||||
}
|
||||
</style>
|
||||
@ -1,993 +0,0 @@
|
||||
<template>
|
||||
<div class="order-sub-container" :style="{ height: containerHeight }">
|
||||
<scan-box
|
||||
ref="scanBox"
|
||||
cache-key="video-camera"
|
||||
width="220px"
|
||||
title="摄像头筛选"
|
||||
:preset-tree="presetTree"
|
||||
:available-fields="availableFields"
|
||||
@condition-change="handleConditionChange"
|
||||
@reset="handleReset"
|
||||
/>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-button size="small" type="primary" :loading="loading" @click="loadList">刷新</el-button>
|
||||
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag>
|
||||
</div>
|
||||
<el-button type="success" size="small" @click="openCreate">新增摄像头</el-button>
|
||||
</div>
|
||||
|
||||
<div class="upper-wrapper">
|
||||
<upper-table
|
||||
ref="upperTable"
|
||||
title="摄像头列表"
|
||||
default-align="center"
|
||||
table-id="video-camera"
|
||||
:data="tableData"
|
||||
:columns="columns"
|
||||
:table-size="tableSize"
|
||||
:pagination="pagination"
|
||||
:show-index="true"
|
||||
:show-actions="false"
|
||||
:loading="loading"
|
||||
:query-time="queryTime"
|
||||
row-key="id"
|
||||
@page-change="handlePageChange"
|
||||
@page-size-change="handlePageSizeChange"
|
||||
@refresh="loadList"
|
||||
>
|
||||
<template #column-server_name="{ row }">
|
||||
<span>{{ row.server?.name || row.server_name || '--' }}</span>
|
||||
</template>
|
||||
|
||||
<template #column-status="{ row }">
|
||||
<el-tag :type="formatStatus(row.status).type" size="small">
|
||||
{{ formatStatus(row.status).text }}
|
||||
</el-tag>
|
||||
</template>
|
||||
|
||||
<template #column-actions="{ row }">
|
||||
<el-button link type="primary" size="small" @click.stop="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" size="small" @click.stop="handleDelete(row)">删除</el-button>
|
||||
<el-button link type="warning" size="small" @click.stop="openOsd(row)">OSD</el-button>
|
||||
<el-button link type="success" size="small" @click.stop="openPreview(row)">预览</el-button>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">暂无摄像头数据,可调整左侧筛选条件</div>
|
||||
</template>
|
||||
</upper-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 新增/编辑弹窗 -->
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
:title="formData.id ? '编辑摄像头' : '新增摄像头'"
|
||||
width="560px"
|
||||
align-center
|
||||
z-index="2500"
|
||||
@close="resetForm"
|
||||
>
|
||||
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
|
||||
<el-form-item label="所属录像服务器" prop="server_id">
|
||||
<el-select
|
||||
v-model="formData.server_id"
|
||||
placeholder="请选择录像服务器"
|
||||
filterable
|
||||
style="width: 100%"
|
||||
@focus="loadServerOptions"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in serverOptions"
|
||||
:key="item.id"
|
||||
:label="item.name"
|
||||
:value="item.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="selectedServerNeedsPassword" label="服务器密码" prop="serverPassword">
|
||||
<el-input
|
||||
v-model="serverPassword"
|
||||
type="password"
|
||||
placeholder="请输入服务器密码以拉取通道列表"
|
||||
show-password
|
||||
@blur="fetchChannelList"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="选择通道" prop="channel_id">
|
||||
<el-select
|
||||
v-model="formData.channel_id"
|
||||
placeholder="请先选择服务器,再选择通道"
|
||||
filterable
|
||||
style="width: 100%"
|
||||
:loading="channelLoading"
|
||||
:disabled="!formData.server_id"
|
||||
@focus="fetchChannelList"
|
||||
@change="handleChannelSelect"
|
||||
>
|
||||
<el-option
|
||||
v-for="ch in channelOptions"
|
||||
:key="ch.value"
|
||||
:label="ch.label"
|
||||
:value="ch.value"
|
||||
:disabled="ch.enabled === false"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="通道名称" prop="channel_name">
|
||||
<el-input v-model="formData.channel_name" placeholder="选择通道后自动填充" maxlength="100" show-word-limit disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="IP 地址">
|
||||
<el-input v-model="formData.ip" placeholder="选择通道后自动填充" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="SDK 端口">
|
||||
<el-input-number v-model="formData.port" placeholder="选择通道后自动填充" :min="1" :max="65535" style="width: 100%" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="型号">
|
||||
<el-input v-model="formData.model" placeholder="选择通道后自动填充" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="序列号">
|
||||
<el-input v-model="formData.serial_number" placeholder="选择通道后自动填充" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="码流类型">
|
||||
<el-input v-model="formData.stream_type" placeholder="选择通道后自动填充" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="自定义名称" prop="custom_name">
|
||||
<el-input v-model="formData.custom_name" placeholder="请输入自定义名称" maxlength="100" show-word-limit />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-switch
|
||||
v-model="formData.status"
|
||||
:active-value="1"
|
||||
:inactive-value="0"
|
||||
active-text="启用"
|
||||
inactive-text="禁用"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注" prop="remark">
|
||||
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="200" show-word-limit />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- OSD 文字叠加设置弹窗 -->
|
||||
<el-dialog
|
||||
v-model="osdVisible"
|
||||
title="设置 OSD 文字叠加"
|
||||
width="520px"
|
||||
align-center
|
||||
:close-on-click-modal="false"
|
||||
@close="resetOsdForm"
|
||||
>
|
||||
<div class="osd-camera-info">
|
||||
<span class="osd-label">摄像头:</span>
|
||||
<span>{{ osdCameraName }}</span>
|
||||
</div>
|
||||
<el-form ref="osdFormRef" :model="osdForm" :rules="osdRules" label-width="100px" class="osd-form">
|
||||
<el-form-item label="叠加文字" prop="text">
|
||||
<el-input
|
||||
v-model="osdForm.text"
|
||||
placeholder="请输入要在画面中叠加的文字"
|
||||
maxlength="64"
|
||||
show-word-limit
|
||||
clearable
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="X 坐标">
|
||||
<div class="osd-coord-row">
|
||||
<el-slider
|
||||
v-model="osdForm.x"
|
||||
:min="-1"
|
||||
:max="1"
|
||||
:step="0.1"
|
||||
:marks="osdCoordMarks"
|
||||
show-input
|
||||
style="flex:1"
|
||||
/>
|
||||
</div>
|
||||
<div class="osd-coord-hint">范围 -1(左)~ 1(右),默认 -0.9</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="Y 坐标">
|
||||
<div class="osd-coord-row">
|
||||
<el-slider
|
||||
v-model="osdForm.y"
|
||||
:min="-1"
|
||||
:max="1"
|
||||
:step="0.1"
|
||||
:marks="osdCoordMarks"
|
||||
show-input
|
||||
style="flex:1"
|
||||
/>
|
||||
</div>
|
||||
<div class="osd-coord-hint">范围 -1(上)~ 1(下),默认 0.8</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="osd-preview-box">
|
||||
<div class="osd-preview-label">位置预览</div>
|
||||
<div class="osd-preview-canvas">
|
||||
<span
|
||||
class="osd-preview-dot"
|
||||
:style="osdDotStyle"
|
||||
title="OSD 文字参考位置"
|
||||
>●</span>
|
||||
</div>
|
||||
<div class="osd-preview-pos">当前坐标:({{ osdForm.x.toFixed(1) }}, {{ osdForm.y.toFixed(1) }})</div>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="osdVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="osdSaving" @click="submitOsd">
|
||||
应用 OSD
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<!-- 预览弹窗 -->
|
||||
<CameraPreviewDialog v-model="previewVisible" :camera-row="previewCameraRow" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import ScanBox from '@/components/ScanBox/index.vue'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import CameraPreviewDialog from './component/CameraPreviewDialog.vue'
|
||||
import { list, create, update, del, setOsd } from '@/api/camera/camera'
|
||||
import { list as serverList, detail as serverDetail } from '@/api/camera_server/camera_server'
|
||||
import { getHikvisionChannels } from '@/api/camera_server/localServerApi'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
|
||||
type CameraRecord = {
|
||||
id?: number
|
||||
server_id?: number
|
||||
server_name?: string
|
||||
channel_id?: number
|
||||
channel_name?: string
|
||||
ip?: string
|
||||
port?: number
|
||||
model?: string
|
||||
serial_number?: string
|
||||
stream_type?: string
|
||||
custom_name?: string
|
||||
status?: number
|
||||
remark?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
type ChannelItem = {
|
||||
label: string
|
||||
value: number
|
||||
ip?: string
|
||||
port?: number
|
||||
model?: string
|
||||
serial_number?: string
|
||||
stream_type?: string
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
type ServerOption = {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
const scanBox = ref<any>(null)
|
||||
const upperTable = ref<any>(null)
|
||||
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
const containerHeight = computed(() =>
|
||||
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
|
||||
)
|
||||
|
||||
const columns = [
|
||||
{ prop: 'id', label: 'ID', width: '80', sortable: true },
|
||||
{ prop: 'server_name', label: '所属服务器', minWidth: '150', showOverflowTooltip: true },
|
||||
{ prop: 'channel_id', label: '通道ID', width: '100' },
|
||||
{ prop: 'channel_name', label: '通道名称', width: '140', showOverflowTooltip: true },
|
||||
{ prop: 'ip', label: 'IP', width: '140', showOverflowTooltip: true },
|
||||
{ prop: 'model', label: '型号', width: '150', showOverflowTooltip: true },
|
||||
{ prop: 'custom_name', label: '自定义名称', minWidth: '160', showOverflowTooltip: true },
|
||||
{ prop: 'status', label: '状态', width: '90' },
|
||||
{ prop: 'remark', label: '备注', minWidth: '160', showOverflowTooltip: true },
|
||||
{ prop: 'actions', label: '操作', width: '220', fixed: 'right' }
|
||||
]
|
||||
|
||||
const availableFields = [
|
||||
{
|
||||
value: 'quickWhere',
|
||||
label: '关键词',
|
||||
type: 'text',
|
||||
placeholder: '通道名称/自定义名称',
|
||||
operators: ['contains'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'server_id',
|
||||
label: '所属服务器',
|
||||
type: 'select',
|
||||
filterable: true,
|
||||
clearable: true,
|
||||
options: [] as { label: string; value: string | number }[]
|
||||
},
|
||||
{
|
||||
value: 'custom_name',
|
||||
label: '自定义名称',
|
||||
type: 'text',
|
||||
placeholder: '请输入自定义名称',
|
||||
operators: ['contains'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'status',
|
||||
label: '状态',
|
||||
type: 'select',
|
||||
clearable: true,
|
||||
options: [
|
||||
{ label: '启用', value: '1' },
|
||||
{ label: '禁用', value: '0' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const presetTree = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const isEditingMode = ref(false)
|
||||
const tableData = ref<CameraRecord[]>([])
|
||||
const serverOptions = ref<ServerOption[]>([])
|
||||
/** 服务器完整信息映射(用于连通通道拉取) */
|
||||
const serverDetailMap = ref<Record<number, { internal_ip?: string; public_ip?: string; port?: number; username?: string; password?: string }>>({})
|
||||
const channelLoading = ref(false)
|
||||
const channelOptions = ref<ChannelItem[]>([])
|
||||
const serverPassword = ref('')
|
||||
const selectedServerNeedsPassword = ref(false)
|
||||
const previewVisible = ref(false)
|
||||
const previewCameraRow = ref<CameraRecord | null>(null)
|
||||
|
||||
// --- OSD 文字叠加 ---
|
||||
const osdVisible = ref(false)
|
||||
const osdSaving = ref(false)
|
||||
const osdCameraRow = ref<CameraRecord | null>(null)
|
||||
const osdFormRef = ref<FormInstance>()
|
||||
const osdForm = reactive({ text: '', x: -0.9, y: 0.8 })
|
||||
const osdRules: FormRules = {
|
||||
text: [{ required: true, message: '请输入叠加文字', trigger: 'blur' }]
|
||||
}
|
||||
const osdCoordMarks = { '-1': '-1', '0': '0', '1': '1' }
|
||||
|
||||
const osdCameraName = computed(() => {
|
||||
const row = osdCameraRow.value
|
||||
if (!row) return '--'
|
||||
return row.custom_name || row.channel_name || `摄像头 #${row.id}`
|
||||
})
|
||||
|
||||
const osdDotStyle = computed(() => {
|
||||
const left = ((osdForm.x + 1) / 2) * 100
|
||||
const top = ((1 - osdForm.y) / 2) * 100
|
||||
return { left: `${left}%`, top: `${top}%` }
|
||||
})
|
||||
const queryTime = ref(0)
|
||||
const tableSize = ref<'small' | 'default' | 'large'>('small')
|
||||
const currentConditionRaw = ref<any>(null)
|
||||
|
||||
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const dialogMode = ref<'create' | 'edit'>('create')
|
||||
const formRef = ref<FormInstance>()
|
||||
const formData = reactive({
|
||||
id: undefined as number | undefined,
|
||||
server_id: undefined as number | undefined,
|
||||
channel_id: undefined as number | undefined,
|
||||
channel_name: '',
|
||||
ip: '',
|
||||
port: undefined as number | undefined,
|
||||
model: '',
|
||||
serial_number: '',
|
||||
stream_type: '',
|
||||
custom_name: '',
|
||||
status: 1 as number,
|
||||
remark: ''
|
||||
})
|
||||
|
||||
const rules: FormRules = {
|
||||
server_id: [{ required: true, message: '请选择录像服务器', trigger: 'change' }],
|
||||
channel_id: [{ required: true, message: '请选择通道', trigger: 'change' }],
|
||||
custom_name: [{ required: true, message: '请输入自定义名称', trigger: 'blur' }]
|
||||
}
|
||||
|
||||
const isSuccess = (res: any) => res && [0, 1, 200].includes(res.code)
|
||||
|
||||
function formatStatus(status: number | undefined) {
|
||||
if (status === 1) return { text: '启用', type: 'success' as const }
|
||||
if (status === 0) return { text: '禁用', type: 'info' as const }
|
||||
return { text: '--', type: 'info' as const }
|
||||
}
|
||||
|
||||
/** 解包 ScanBox 的条件对象值,转为 API where 可接受的格式 */
|
||||
function unwrapConditionValue(raw: unknown): string | number | null | Record<string, unknown> {
|
||||
if (raw === null || raw === undefined || raw === '') return null
|
||||
if (Array.isArray(raw) && raw.length === 0) return null
|
||||
|
||||
// ScanBox 对象值格式:{ operator, value }
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
const obj = raw as Record<string, unknown>
|
||||
if (['isnull', 'isnotnull'].includes(String(obj.operator ?? ''))) {
|
||||
return { operator: obj.operator as string, value: null }
|
||||
}
|
||||
const val = obj.value !== undefined ? obj.value : raw
|
||||
if (val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {
|
||||
return null
|
||||
}
|
||||
return { operator: obj.operator || 'eq', value: val }
|
||||
}
|
||||
|
||||
return raw as string | number
|
||||
}
|
||||
|
||||
function buildWhere(raw: any): Record<string, unknown> {
|
||||
if (!raw) return {}
|
||||
|
||||
// ScanBox 发出 { conditions: { ... } },先解包
|
||||
const conds =
|
||||
raw.conditions && typeof raw.conditions === 'object' && !Array.isArray(raw.conditions)
|
||||
? raw.conditions
|
||||
: raw
|
||||
|
||||
if (!conds || typeof conds !== 'object') return {}
|
||||
|
||||
const where: Record<string, unknown> = {}
|
||||
|
||||
for (const key of Object.keys(conds)) {
|
||||
const result = unwrapConditionValue(conds[key])
|
||||
if (result === null) continue
|
||||
|
||||
if (key === 'quickWhere') {
|
||||
// quickWhere 直接传字符串
|
||||
where.quickWhere = typeof result === 'string' ? result : String((result as Record<string, unknown>).value ?? result)
|
||||
} else if (key === 'status' || key === 'server_id') {
|
||||
where[key] = typeof result === 'object' ? Number((result as Record<string, unknown>).value) : Number(result)
|
||||
} else {
|
||||
where[key] = result
|
||||
}
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
const start = Date.now()
|
||||
try {
|
||||
const where = buildWhere(currentConditionRaw.value)
|
||||
const res: any = await list({
|
||||
pagination: { page: pagination.currentPage, pageSize: pagination.pageSize },
|
||||
where
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '获取摄像头列表失败')
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
return
|
||||
}
|
||||
tableData.value = res?.list || []
|
||||
pagination.total = Number(res?.pagination?.total ?? res?.total ?? 0)
|
||||
} catch {
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
ElMessage.error('获取摄像头列表失败')
|
||||
} finally {
|
||||
queryTime.value = Date.now() - start
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadServerOptions() {
|
||||
if (serverOptions.value.length > 0) return
|
||||
try {
|
||||
const res: any = await serverList({ pagination: { page: 1, pageSize: 999 } })
|
||||
if (!isSuccess(res)) return
|
||||
const list = res?.list || []
|
||||
serverOptions.value = list.map((item: any) => ({
|
||||
id: item.id,
|
||||
name: item.name || `服务器-${item.id}`
|
||||
}))
|
||||
// 缓存服务器详细信息
|
||||
list.forEach((item: any) => {
|
||||
if (item.id) {
|
||||
serverDetailMap.value[item.id] = {
|
||||
internal_ip: item.internal_ip,
|
||||
public_ip: item.public_ip,
|
||||
port: item.port,
|
||||
username: item.username,
|
||||
password: item.password
|
||||
}
|
||||
}
|
||||
})
|
||||
// 同步到筛选下拉
|
||||
const field = availableFields.find((f: any) => f.value === 'server_id')
|
||||
if (field) {
|
||||
field.options = serverOptions.value.map((item) => ({
|
||||
label: item.name,
|
||||
value: item.id
|
||||
}))
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据选中的服务器拉取通道列表
|
||||
* 优先使用内网 IP,失败则回退公网 IP
|
||||
*/
|
||||
async function fetchChannelList() {
|
||||
const serverId = formData.server_id
|
||||
if (!serverId) {
|
||||
channelOptions.value = []
|
||||
return
|
||||
}
|
||||
|
||||
// 确保服务器数据已加载
|
||||
await loadServerOptions()
|
||||
|
||||
const server = serverDetailMap.value[serverId]
|
||||
if (!server) {
|
||||
ElMessage.warning('未找到服务器信息')
|
||||
return
|
||||
}
|
||||
|
||||
let password = server.password || serverPassword.value
|
||||
|
||||
// 密码缺失则尝试通过 detail API 获取
|
||||
if (!password && serverId) {
|
||||
try {
|
||||
const detailRes: any = await serverDetail({ id: serverId })
|
||||
if (isSuccess(detailRes) && detailRes?.data?.password) {
|
||||
password = detailRes.data.password
|
||||
serverDetailMap.value[serverId] = { ...server, password }
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
selectedServerNeedsPassword.value = true
|
||||
ElMessage.warning('请填写服务器密码后重新拉取通道')
|
||||
return
|
||||
}
|
||||
selectedServerNeedsPassword.value = false
|
||||
|
||||
channelLoading.value = true
|
||||
const localBaseUrl = 'http://localhost:17311'
|
||||
|
||||
const tryFetch = async (label: string, ip: string) => {
|
||||
try {
|
||||
const channels = await getHikvisionChannels(localBaseUrl, {
|
||||
ip,
|
||||
port: server.port,
|
||||
user: server.username || '',
|
||||
pass: password
|
||||
})
|
||||
if (Array.isArray(channels) && channels.length) {
|
||||
channelOptions.value = channels.map((ch: any) => ({
|
||||
label: `${ch.name || `通道${ch.id}`} (ID: ${ch.id})${ch.enabled === false ? ' [已禁用]' : ''}`,
|
||||
value: ch.id,
|
||||
ip: ch.ip,
|
||||
port: ch.port,
|
||||
model: ch.model,
|
||||
serial_number: ch.serialNumber ?? ch.serial_number,
|
||||
stream_type: ch.streamType ?? ch.stream_type,
|
||||
enabled: ch.enabled
|
||||
}))
|
||||
ElMessage.success(`成功拉取 ${channelOptions.value.length} 个通道(${label}:${ip})`)
|
||||
return true
|
||||
}
|
||||
channelOptions.value = []
|
||||
ElMessage.warning(`服务器返回空通道列表(${label}:${ip})`)
|
||||
return false
|
||||
} catch (e: any) {
|
||||
console.warn(`[拉取通道] ${label} ${ip} 失败:`, e?.message || e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 先内网,后公网
|
||||
const internalIp = server.internal_ip?.trim()
|
||||
const publicIp = server.public_ip?.trim()
|
||||
|
||||
if (internalIp) {
|
||||
const ok = await tryFetch('内网IP', internalIp)
|
||||
if (ok) { channelLoading.value = false; return }
|
||||
}
|
||||
if (publicIp && publicIp !== internalIp) {
|
||||
const ok = await tryFetch('公网IP', publicIp)
|
||||
if (ok) { channelLoading.value = false; return }
|
||||
}
|
||||
|
||||
channelLoading.value = false
|
||||
channelOptions.value = []
|
||||
ElMessage.error('无法拉取通道列表,请检查服务器配置与连通性')
|
||||
}
|
||||
|
||||
/** 选中通道后自动填充通道名称及设备信息 */
|
||||
function handleChannelSelect(value: number) {
|
||||
const channel = channelOptions.value.find((ch) => ch.value === value)
|
||||
if (channel) {
|
||||
// 从 label 中提取通道名称(格式:通道名 (ID: xxx))
|
||||
const nameMatch = channel.label.match(/^(.+?)\s*\(ID:/)
|
||||
formData.channel_name = nameMatch ? nameMatch[1] || channel.label : channel.label
|
||||
formData.ip = channel.ip || ''
|
||||
formData.port = channel.port
|
||||
formData.model = channel.model || ''
|
||||
formData.serial_number = channel.serial_number || ''
|
||||
formData.stream_type = channel.stream_type || ''
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => formData.server_id, (newId, oldId) => {
|
||||
if (newId && newId !== oldId) {
|
||||
// 编辑模式下不自动清空字段,由 openEdit 手动填充
|
||||
if (!isEditingMode.value) {
|
||||
formData.channel_id = undefined
|
||||
formData.channel_name = ''
|
||||
formData.ip = ''
|
||||
formData.port = undefined
|
||||
formData.model = ''
|
||||
formData.serial_number = ''
|
||||
formData.stream_type = ''
|
||||
channelOptions.value = []
|
||||
selectedServerNeedsPassword.value = false
|
||||
serverPassword.value = ''
|
||||
}
|
||||
fetchChannelList()
|
||||
}
|
||||
})
|
||||
|
||||
function handleConditionChange(condition: any) {
|
||||
currentConditionRaw.value = condition
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
currentConditionRaw.value = null
|
||||
pagination.currentPage = 1
|
||||
if (scanBox.value?.reset) scanBox.value.reset()
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
formData.id = undefined
|
||||
formData.server_id = undefined
|
||||
formData.channel_id = undefined
|
||||
formData.channel_name = ''
|
||||
formData.ip = ''
|
||||
formData.port = undefined
|
||||
formData.model = ''
|
||||
formData.serial_number = ''
|
||||
formData.stream_type = ''
|
||||
formData.custom_name = ''
|
||||
formData.status = 1
|
||||
formData.remark = ''
|
||||
channelOptions.value = []
|
||||
channelLoading.value = false
|
||||
serverPassword.value = ''
|
||||
selectedServerNeedsPassword.value = false
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
dialogMode.value = 'create'
|
||||
dialogVisible.value = true
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function openEdit(row: CameraRecord) {
|
||||
if (!row.id) return
|
||||
dialogMode.value = 'edit'
|
||||
dialogVisible.value = true
|
||||
// 标记编辑模式,防止 watch 清空已填充的字段
|
||||
isEditingMode.value = true
|
||||
formData.id = row.id
|
||||
formData.server_id = row.server_id
|
||||
formData.channel_id = row.channel_id
|
||||
formData.channel_name = row.channel_name || ''
|
||||
formData.ip = row.ip || ''
|
||||
formData.port = row.port
|
||||
formData.model = row.model || ''
|
||||
formData.serial_number = row.serial_number || ''
|
||||
formData.stream_type = row.stream_type || ''
|
||||
formData.custom_name = row.custom_name || ''
|
||||
formData.status = row.status ?? 1
|
||||
formData.remark = row.remark || ''
|
||||
serverPassword.value = ''
|
||||
selectedServerNeedsPassword.value = false
|
||||
formRef.value?.clearValidate()
|
||||
// 延迟解除编辑标记,确保 watch 回调(pre-flush)执行完毕
|
||||
setTimeout(() => { isEditingMode.value = false }, 0)
|
||||
}
|
||||
|
||||
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 (!formData.id) {
|
||||
const res: any = await create({
|
||||
server_id: formData.server_id!,
|
||||
channel_id: formData.channel_id!,
|
||||
channel_name: formData.channel_name.trim() || undefined,
|
||||
ip: formData.ip.trim() || undefined,
|
||||
port: formData.port,
|
||||
model: formData.model.trim() || undefined,
|
||||
serial_number: formData.serial_number.trim() || undefined,
|
||||
stream_type: formData.stream_type.trim() || undefined,
|
||||
custom_name: formData.custom_name.trim() || undefined,
|
||||
status: formData.status,
|
||||
remark: formData.remark.trim() || undefined
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '新增失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('新增成功')
|
||||
} else {
|
||||
if (!formData.id) return
|
||||
const res: any = await update({
|
||||
id: formData.id,
|
||||
server_id: formData.server_id,
|
||||
channel_id: formData.channel_id,
|
||||
channel_name: formData.channel_name.trim() || undefined,
|
||||
ip: formData.ip.trim() || undefined,
|
||||
port: formData.port,
|
||||
model: formData.model.trim() || undefined,
|
||||
serial_number: formData.serial_number.trim() || undefined,
|
||||
stream_type: formData.stream_type.trim() || undefined,
|
||||
custom_name: formData.custom_name.trim() || undefined,
|
||||
status: formData.status,
|
||||
remark: formData.remark.trim() || undefined
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '更新失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('更新成功')
|
||||
}
|
||||
dialogVisible.value = false
|
||||
loadList()
|
||||
} catch {
|
||||
ElMessage.error('保存失败')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleDelete(row: CameraRecord) {
|
||||
if (!row.id) return
|
||||
const name = row.custom_name || row.channel_name || String(row.id)
|
||||
ElMessageBox.confirm(`确认删除摄像头「${name}」吗?`, '提示', { type: 'warning' })
|
||||
.then(async () => {
|
||||
const res: any = await del({ id: row.id as number })
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '删除失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('删除成功')
|
||||
if (tableData.value.length === 1 && pagination.currentPage > 1) {
|
||||
pagination.currentPage -= 1
|
||||
}
|
||||
loadList()
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开预览弹窗
|
||||
*/
|
||||
function openPreview(row: CameraRecord) {
|
||||
previewCameraRow.value = row
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
/** 打开 OSD 设置弹窗 */
|
||||
function openOsd(row: CameraRecord) {
|
||||
osdCameraRow.value = row
|
||||
resetOsdForm()
|
||||
osdVisible.value = true
|
||||
}
|
||||
|
||||
function resetOsdForm() {
|
||||
osdForm.text = ''
|
||||
osdForm.x = -0.9
|
||||
osdForm.y = 0.8
|
||||
osdFormRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
/** 提交 OSD 文字叠加 */
|
||||
async function submitOsd() {
|
||||
if (!osdFormRef.value || osdSaving.value) return
|
||||
const valid = await osdFormRef.value.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
|
||||
const row = osdCameraRow.value
|
||||
if (!row?.id) {
|
||||
ElMessage.error('未找到摄像头信息')
|
||||
return
|
||||
}
|
||||
|
||||
osdSaving.value = true
|
||||
try {
|
||||
const res: any = await setOsd({
|
||||
id: row.id,
|
||||
text: osdForm.text.trim(),
|
||||
x: osdForm.x,
|
||||
y: osdForm.y
|
||||
})
|
||||
if (isSuccess(res)) {
|
||||
ElMessage.success(`已为「${osdCameraName.value}」设置 OSD 文字`)
|
||||
osdVisible.value = false
|
||||
} else {
|
||||
ElMessage.error(res?.message || 'OSD 设置失败')
|
||||
}
|
||||
} catch {
|
||||
ElMessage.error('OSD 设置失败,请检查网络连接')
|
||||
} finally {
|
||||
osdSaving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadList()
|
||||
loadServerOptions()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
/* ===== 引入 waveOrder 共享样式(scan-box / toolbar / split-stack / pane-resizer / lower-level 等) ===== */
|
||||
@use "../../order/orderManagement/styles/order-sub.scss";
|
||||
|
||||
/* ===== 覆盖 ScanBox"筛选/过滤"标签样式(对齐页面顶部 TabArea 风格) ===== */
|
||||
.order-sub-container {
|
||||
: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;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
color: #909399;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
/* --- OSD 弹窗样式 --- */
|
||||
.osd-camera-info {
|
||||
padding: 8px 12px;
|
||||
margin-bottom: 16px;
|
||||
background: #f5f7fa;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
color: #303133;
|
||||
}
|
||||
.osd-label {
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.osd-form {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.osd-coord-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.osd-coord-hint {
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.osd-preview-box {
|
||||
margin-top: 16px;
|
||||
border: 1px solid #e4e7ed;
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.osd-preview-label {
|
||||
font-size: 13px;
|
||||
color: #606266;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.osd-preview-canvas {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
background: #1a1a2e;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.osd-preview-dot {
|
||||
position: absolute;
|
||||
font-size: 16px;
|
||||
color: #67c23a;
|
||||
transform: translate(-50%, -50%);
|
||||
text-shadow: 0 0 4px rgba(103, 194, 58, 0.6);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.osd-preview-pos {
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@ -1,626 +0,0 @@
|
||||
<template>
|
||||
<div class="video-container" :style="{ height: containerHeight }">
|
||||
<scan-box
|
||||
ref="scanBox"
|
||||
cache-key="video-camera-server"
|
||||
width="220px"
|
||||
title="录像服务器筛选"
|
||||
:preset-tree="presetTree"
|
||||
:available-fields="availableFields"
|
||||
@condition-change="handleConditionChange"
|
||||
@reset="handleReset"
|
||||
/>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="toolbar">
|
||||
<div class="toolbar-left">
|
||||
<el-button size="small" type="primary" :loading="loading" @click="loadList">刷新</el-button>
|
||||
<el-tag size="small" type="info">共 {{ pagination.total }} 条</el-tag>
|
||||
</div>
|
||||
<el-button type="success" size="small" @click="openCreate">新增录像服务器</el-button>
|
||||
</div>
|
||||
|
||||
<div class="upper-wrapper">
|
||||
<upper-table
|
||||
ref="upperTable"
|
||||
title="录像服务器列表"
|
||||
default-align="center"
|
||||
table-id="video-camera-server"
|
||||
:data="tableData"
|
||||
:columns="columns"
|
||||
:table-size="tableSize"
|
||||
:pagination="pagination"
|
||||
:show-index="true"
|
||||
:show-actions="false"
|
||||
:loading="loading"
|
||||
:query-time="queryTime"
|
||||
row-key="id"
|
||||
@page-change="handlePageChange"
|
||||
@page-size-change="handlePageSizeChange"
|
||||
@refresh="loadList"
|
||||
>
|
||||
<template #column-status="{ row }">
|
||||
<el-tag :type="formatStatus(row.status).type" size="small">
|
||||
{{ formatStatus(row.status).text }}
|
||||
</el-tag>
|
||||
</template>
|
||||
|
||||
<template #column-actions="{ row }">
|
||||
<el-button link type="primary" size="small" @click.stop="openEdit(row)">编辑</el-button>
|
||||
<el-button link type="danger" size="small" @click.stop="handleDelete(row)">删除</el-button>
|
||||
</template>
|
||||
|
||||
<template #column-connectivity="{ row }">
|
||||
<el-button
|
||||
size="small"
|
||||
type="warning"
|
||||
plain
|
||||
:loading="testLoadingMap[row.id!]"
|
||||
@click.stop="handleTestConnection(row)"
|
||||
>
|
||||
连通测试
|
||||
</el-button>
|
||||
</template>
|
||||
|
||||
<template #empty>
|
||||
<div class="empty-tip">暂无录像服务器数据,可调整左侧筛选条件</div>
|
||||
</template>
|
||||
</upper-table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 新增/编辑弹窗 -->
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
:title="dialogMode === 'create' ? '新增录像服务器' : '编辑录像服务器'"
|
||||
width="560px"
|
||||
align-center
|
||||
@close="resetForm"
|
||||
>
|
||||
<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
|
||||
<el-form-item label="服务器名称" prop="name">
|
||||
<el-input v-model="formData.name" placeholder="请输入服务器名称" maxlength="100" show-word-limit />
|
||||
</el-form-item>
|
||||
<el-form-item label="品牌" prop="brand">
|
||||
<el-select v-model="formData.brand" placeholder="请选择品牌" clearable style="width: 100%">
|
||||
<el-option label="海康威视" value="hikvision" />
|
||||
<el-option label="大华" value="dahua" />
|
||||
<el-option label="宇视" value="uniview" />
|
||||
<el-option label="其他" value="other" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="公网IP" prop="public_ip">
|
||||
<div class="ip-port-row">
|
||||
<el-input v-model="formData.public_ip" placeholder="请输入公网IP" maxlength="50" class="ip-input" />
|
||||
<el-input-number v-model="formData.public_port" :min="1" :max="65535" placeholder="端口" class="port-input" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="内网IP" prop="internal_ip">
|
||||
<div class="ip-port-row">
|
||||
<el-input v-model="formData.internal_ip" placeholder="请输入内网IP" maxlength="50" class="ip-input" />
|
||||
<el-input-number v-model="formData.internal_port" :min="1" :max="65535" placeholder="端口" class="port-input" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="用户名" prop="username">
|
||||
<el-input v-model="formData.username" placeholder="请输入用户名" maxlength="50" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码" prop="password">
|
||||
<el-input v-model="formData.password" type="password" placeholder="请输入密码" maxlength="50" show-password />
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-switch
|
||||
v-model="formData.status"
|
||||
:active-value="1"
|
||||
:inactive-value="0"
|
||||
active-text="启用"
|
||||
inactive-text="禁用"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注" prop="remark">
|
||||
<el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" maxlength="200" show-word-limit />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="submitForm">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import type { FormInstance, FormRules } from 'element-plus'
|
||||
import ScanBox from '@/components/ScanBox/index.vue'
|
||||
import UpperTable from '@/components/UpperTable/index.vue'
|
||||
import { list, create, update, del } from '@/api/camera_server/camera_server'
|
||||
import { testConnection } from '@/api/camera_server/localServerApi'
|
||||
import { useSettingsStore } from '@/stores/modules/settings'
|
||||
|
||||
type CameraServerRecord = {
|
||||
id?: number
|
||||
name?: string
|
||||
brand?: string
|
||||
public_ip?: string
|
||||
public_port?: number
|
||||
internal_ip?: string
|
||||
internal_port?: number
|
||||
port?: number
|
||||
username?: string
|
||||
password?: string
|
||||
status?: number
|
||||
remark?: string
|
||||
created_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
const settingsStore = useSettingsStore()
|
||||
const scanBox = ref<any>(null)
|
||||
const upperTable = ref<any>(null)
|
||||
|
||||
const shortcutExpanded = computed(() => settingsStore.shortcutExpanded)
|
||||
const containerHeight = computed(() =>
|
||||
shortcutExpanded.value ? 'calc(100vh - 150px)' : 'calc(100vh - 100px)'
|
||||
)
|
||||
|
||||
const columns = [
|
||||
{ prop: 'id', label: 'ID', width: '80', sortable: true },
|
||||
{ prop: 'name', label: '服务器名称', minWidth: '160', showOverflowTooltip: true },
|
||||
{ prop: 'brand', label: '品牌', width: '120' },
|
||||
{ prop: 'public_ip', label: '公网IP', width: '150' },
|
||||
{ prop: 'internal_ip', label: '内网IP', width: '150' },
|
||||
{ prop: 'port', label: '端口', width: '80' },
|
||||
{ prop: 'username', label: '用户名', width: '120' },
|
||||
{ prop: 'status', label: '状态', width: '90' },
|
||||
{ prop: 'connectivity', label: '连通', width: '110' },
|
||||
{ prop: 'remark', label: '备注', minWidth: '160', showOverflowTooltip: true },
|
||||
{ prop: 'actions', label: '操作', width: '150', fixed: 'right' }
|
||||
]
|
||||
|
||||
const availableFields = [
|
||||
{
|
||||
value: 'quickWhere',
|
||||
label: '关键词',
|
||||
type: 'text',
|
||||
placeholder: '服务器名称/IP',
|
||||
operators: ['contains'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'name',
|
||||
label: '服务器名称',
|
||||
type: 'text',
|
||||
placeholder: '请输入名称',
|
||||
operators: ['contains'],
|
||||
defaultOperator: 'contains'
|
||||
},
|
||||
{
|
||||
value: 'status',
|
||||
label: '状态',
|
||||
type: 'select',
|
||||
clearable: true,
|
||||
options: [
|
||||
{ label: '启用', value: '1' },
|
||||
{ label: '禁用', value: '0' }
|
||||
]
|
||||
},
|
||||
{
|
||||
value: 'brand',
|
||||
label: '品牌',
|
||||
type: 'select',
|
||||
clearable: true,
|
||||
options: [
|
||||
{ label: '海康威视', value: 'hikvision' },
|
||||
{ label: '大华', value: 'dahua' },
|
||||
{ label: '宇视', value: 'uniview' },
|
||||
{ label: '其他', value: 'other' }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const presetTree = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const testLoadingMap = ref<Record<number, boolean>>({})
|
||||
const tableData = ref<CameraServerRecord[]>([])
|
||||
const queryTime = ref(0)
|
||||
const tableSize = ref<'small' | 'default' | 'large'>('small')
|
||||
const currentConditionRaw = ref<any>(null)
|
||||
|
||||
const pagination = reactive({ currentPage: 1, pageSize: 20, total: 0 })
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const dialogMode = ref<'create' | 'edit'>('create')
|
||||
const formRef = ref<FormInstance>()
|
||||
const formData = reactive({
|
||||
id: undefined as number | undefined,
|
||||
name: '',
|
||||
brand: '',
|
||||
public_ip: '',
|
||||
public_port: undefined as number | undefined,
|
||||
internal_ip: '',
|
||||
internal_port: undefined as number | undefined,
|
||||
port: undefined as number | undefined,
|
||||
username: '',
|
||||
password: '',
|
||||
status: 1 as number,
|
||||
remark: ''
|
||||
})
|
||||
|
||||
const rules: FormRules = {
|
||||
name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }]
|
||||
}
|
||||
|
||||
const isSuccess = (res: any) => res && [0, 1, 200].includes(res.code)
|
||||
|
||||
function formatStatus(status: number | undefined) {
|
||||
if (status === 1) return { text: '启用', type: 'success' as const }
|
||||
if (status === 0) return { text: '禁用', type: 'info' as const }
|
||||
return { text: '--', type: 'info' as const }
|
||||
}
|
||||
|
||||
/** 解包 ScanBox 的条件对象值,转为 API where 可接受的格式 */
|
||||
function unwrapConditionValue(raw: unknown): string | number | null | Record<string, unknown> {
|
||||
if (raw === null || raw === undefined || raw === '') return null
|
||||
if (Array.isArray(raw) && raw.length === 0) return null
|
||||
|
||||
// ScanBox 对象值格式:{ operator, value }
|
||||
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
||||
const obj = raw as Record<string, unknown>
|
||||
if (['isnull', 'isnotnull'].includes(String(obj.operator ?? ''))) {
|
||||
return { operator: obj.operator as string, value: null }
|
||||
}
|
||||
const val = obj.value !== undefined ? obj.value : raw
|
||||
if (val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {
|
||||
return null
|
||||
}
|
||||
return { operator: obj.operator || 'eq', value: val }
|
||||
}
|
||||
|
||||
return raw as string | number
|
||||
}
|
||||
|
||||
function buildWhere(raw: any): Record<string, unknown> {
|
||||
if (!raw) return {}
|
||||
|
||||
// ScanBox 发出 { conditions: { ... } },先解包
|
||||
const conds =
|
||||
raw.conditions && typeof raw.conditions === 'object' && !Array.isArray(raw.conditions)
|
||||
? raw.conditions
|
||||
: raw
|
||||
|
||||
if (!conds || typeof conds !== 'object') return {}
|
||||
|
||||
const where: Record<string, unknown> = {}
|
||||
|
||||
for (const key of Object.keys(conds)) {
|
||||
const result = unwrapConditionValue(conds[key])
|
||||
if (result === null) continue
|
||||
|
||||
if (key === 'quickWhere') {
|
||||
// quickWhere 直接传字符串
|
||||
where.quickWhere = typeof result === 'string' ? result : String((result as Record<string, unknown>).value ?? result)
|
||||
} else if (key === 'status') {
|
||||
where.status = typeof result === 'object' ? Number((result as Record<string, unknown>).value) : Number(result)
|
||||
} else {
|
||||
where[key] = result
|
||||
}
|
||||
}
|
||||
|
||||
return where
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
const start = Date.now()
|
||||
try {
|
||||
const where = buildWhere(currentConditionRaw.value)
|
||||
const res: any = await list({
|
||||
pagination: { page: pagination.currentPage, pageSize: pagination.pageSize },
|
||||
where
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '获取录像服务器列表失败')
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
return
|
||||
}
|
||||
tableData.value = res?.list || []
|
||||
pagination.total = Number(res?.pagination?.total ?? res?.total ?? 0)
|
||||
} catch {
|
||||
tableData.value = []
|
||||
pagination.total = 0
|
||||
ElMessage.error('获取录像服务器列表失败')
|
||||
} finally {
|
||||
queryTime.value = Date.now() - start
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleConditionChange(condition: any) {
|
||||
currentConditionRaw.value = condition
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
currentConditionRaw.value = null
|
||||
pagination.currentPage = 1
|
||||
if (scanBox.value?.reset) scanBox.value.reset()
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
pagination.currentPage = page
|
||||
loadList()
|
||||
}
|
||||
|
||||
function handlePageSizeChange(size: number) {
|
||||
pagination.pageSize = size
|
||||
pagination.currentPage = 1
|
||||
loadList()
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
formData.id = undefined
|
||||
formData.name = ''
|
||||
formData.brand = ''
|
||||
formData.public_ip = ''
|
||||
formData.public_port = undefined
|
||||
formData.internal_ip = ''
|
||||
formData.internal_port = undefined
|
||||
formData.port = undefined
|
||||
formData.username = ''
|
||||
formData.password = ''
|
||||
formData.status = 1
|
||||
formData.remark = ''
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
dialogMode.value = 'create'
|
||||
dialogVisible.value = true
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function openEdit(row: CameraServerRecord) {
|
||||
if (!row.id) return
|
||||
dialogMode.value = 'edit'
|
||||
dialogVisible.value = true
|
||||
formData.id = row.id
|
||||
formData.name = row.name || ''
|
||||
formData.brand = row.brand || ''
|
||||
formData.public_ip = row.public_ip || ''
|
||||
formData.public_port = row.public_port
|
||||
formData.internal_ip = row.internal_ip || ''
|
||||
formData.internal_port = row.internal_port
|
||||
formData.port = row.port
|
||||
formData.username = row.username || ''
|
||||
formData.password = ''
|
||||
formData.status = row.status ?? 1
|
||||
formData.remark = row.remark || ''
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
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 (dialogMode.value === 'create') {
|
||||
const res: any = await create({
|
||||
name: formData.name.trim(),
|
||||
brand: formData.brand || undefined,
|
||||
public_ip: formData.public_ip.trim() || undefined,
|
||||
public_port: formData.public_port,
|
||||
internal_ip: formData.internal_ip.trim() || undefined,
|
||||
internal_port: formData.internal_port,
|
||||
port: formData.port,
|
||||
username: formData.username.trim() || undefined,
|
||||
password: formData.password || undefined,
|
||||
status: formData.status,
|
||||
remark: formData.remark.trim() || undefined
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '新增失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('新增成功')
|
||||
} else {
|
||||
if (!formData.id) return
|
||||
const res: any = await update({
|
||||
id: formData.id,
|
||||
name: formData.name.trim() || undefined,
|
||||
brand: formData.brand || undefined,
|
||||
public_ip: formData.public_ip.trim() || undefined,
|
||||
public_port: formData.public_port,
|
||||
internal_ip: formData.internal_ip.trim() || undefined,
|
||||
internal_port: formData.internal_port,
|
||||
port: formData.port,
|
||||
username: formData.username.trim() || undefined,
|
||||
password: formData.password || undefined,
|
||||
status: formData.status,
|
||||
remark: formData.remark.trim() || undefined
|
||||
})
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '更新失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('更新成功')
|
||||
}
|
||||
dialogVisible.value = false
|
||||
loadList()
|
||||
} catch {
|
||||
ElMessage.error('保存失败')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleDelete(row: CameraServerRecord) {
|
||||
if (!row.id) return
|
||||
const name = row.name || String(row.id)
|
||||
ElMessageBox.confirm(`确认删除录像服务器「${name}」吗?删除后关联的摄像头将不可用`, '提示', { type: 'warning' })
|
||||
.then(async () => {
|
||||
const res: any = await del({ id: row.id as number })
|
||||
if (!isSuccess(res)) {
|
||||
ElMessage.error(res?.message || '删除失败')
|
||||
return
|
||||
}
|
||||
ElMessage.success('删除成功')
|
||||
if (tableData.value.length === 1 && pagination.currentPage > 1) {
|
||||
pagination.currentPage -= 1
|
||||
}
|
||||
loadList()
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* 连通测试:先尝试内网 IP,失败后回退到公网 IP
|
||||
* 若列表数据不含密码,则弹出输入框让用户填写
|
||||
*/
|
||||
async function handleTestConnection(row: CameraServerRecord) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// 先尝试内网 IP(使用内网端口,回退到 SDK 端口)
|
||||
if (internalIp) {
|
||||
const ok = await tryIp('内网IP', internalIp, row.internal_port)
|
||||
if (ok) {
|
||||
testLoadingMap.value = { ...testLoadingMap.value, [id]: false }
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 回退到公网 IP(使用公网端口,回退到 SDK 端口)
|
||||
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})`)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadList()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.video-container {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.toolbar-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.upper-wrapper {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.empty-tip {
|
||||
color: #909399;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
/* IP + 端口 左右布局 */
|
||||
.ip-port-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ip-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.port-input {
|
||||
width: 130px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
Loading…
x
Reference in New Issue
Block a user