const BaseService = require('./base'); /** * 海康录像任务服务 * 客户端通过 WebSocket 调用: * hikvision.fetchTasks - 拉取待录像的打包任务 * hikvision.receiveTask - 确认接收任务,更新状态为 recording * hikvision.taskComplete - 任务完成回调,写入结果 */ class HikvisionService extends BaseService { /** * 将 MySQL DATETIME 字符串转为 ISO 8601 带时区偏移 (+08:00) * 输入: "2026-07-26 11:08:48" → 输出: "2026-07-26T11:08:48+08:00" */ _toISO(datetime) { if (!datetime) return null; const str = String(datetime).trim(); // 如果已经是 ISO 格式就不要再转 if (str.includes('T')) return str.replace('Z', '+08:00'); return str.replace(' ', 'T') + '+08:00'; } /** * 拉取待录像任务 * 查询 wms_pack_task 中 pack_mode=1 且无录像记录的任务 * 返回任务信息 + 摄像头信息 + 服务器信息 */ async fetchTasks(data) { const { app } = this; const { print_computer_info } = this.ctx; if (!print_computer_info) { return this.errorResponse('hikvision.fetchTasks', '未绑定打印电脑信息'); } const warehouseId = print_computer_info.warehouse; try { // 1. 查询该仓库待录像的打包任务(pack_mode=1, 状态不是已完成, 未删除) const tasks = await app.mysql.get('wms').query( `SELECT t.id, t.order_id, t.warehouse_id, t.workbench_id, t.wave_no, t.waybill_code, t.device_ids, t.status AS task_status, t.start_time, t.end_time, t.operator_text FROM wms_pack_task t WHERE t.warehouse_id = ? AND t.pack_mode = 1 AND t.deleted_at IS NULL AND t.end_time IS NOT NULL AND t.device_ids IS NOT NULL AND t.device_ids != '[]' AND t.id NOT IN ( SELECT v.pack_task_id FROM wms_pack_task_video v WHERE v.deleted_at IS NULL ) ORDER BY t.id DESC LIMIT 20`, [warehouseId] ); if (!tasks || tasks.length === 0) { return this.successResponse('hikvision.fetchTasks', [], '暂无待录像任务'); } // 2. 获取该仓库的摄像头服务器信息 const servers = await app.mysql.get('wms').select('wms_camera_server', { where: { warehouse_id: warehouseId, deleted_at: null, status: 1 }, }); // 3. 获取该仓库的摄像头列表 const cameras = await app.mysql.get('wms').select('wms_camera', { where: { warehouse_id: warehouseId, deleted_at: null, status: 1 }, }); // 4. 组装返回数据:每个任务的每个摄像头返回一条 const result = []; for (const task of tasks) { let deviceIds = []; try { deviceIds = typeof task.device_ids === 'string' ? JSON.parse(task.device_ids) : (task.device_ids || []); } catch (e) { deviceIds = []; } for (const deviceId of deviceIds) { // 按设备ID匹配摄像头 const matchedCamera = cameras.find(c => c.id === deviceId) || cameras.find(c => c.custom_name && c.custom_name.includes(`${task.workbench_id}号`)) || cameras[0]; if (!matchedCamera) continue; const matchedServer = servers.find(s => s.id === matchedCamera.server_id) || servers[0]; if (!matchedServer) continue; // 先创建录像记录(状态=created),防止重复拉取 const existingVideo = await app.mysql.get('wms').get('wms_pack_task_video', { pack_task_id: task.id, deleted_at: null, }); if (!existingVideo) { await app.mysql.get('wms').insert('wms_pack_task_video', { pack_task_id: task.id, camera_id: matchedCamera.id, video_url: '', status: 'created', }); console.log(`[Hikvision] 创建录像记录: pack_task=${task.id}, camera=${matchedCamera.id}`); } result.push({ pack_task_id: task.id, device_id: deviceId, uniqueCode: `${task.id}_${deviceId}`, order_id: task.order_id, warehouse_id: task.warehouse_id, workbench_id: task.workbench_id, wave_no: task.wave_no, waybill_code: task.waybill_code, task_status: task.task_status, start_time: this._toISO(task.start_time), end_time: this._toISO(task.end_time), operator: task.operator_text, camera: { id: matchedCamera.id, channel_id: matchedCamera.channel_id, channel_name: matchedCamera.channel_name, ip: matchedCamera.ip, port: matchedCamera.port, model: matchedCamera.model, custom_name: matchedCamera.custom_name, }, server: { id: matchedServer.id, brand: matchedServer.brand, internal_ip: matchedServer.internal_ip, internal_port: matchedServer.internal_port || 80, username: matchedServer.username, password: matchedServer.password, }, }); } } console.log(`[Hikvision] 仓库 ${warehouseId} 返回 ${result.length} 个待录像任务`); return this.successResponse('hikvision.fetchTasks', result, '查询成功'); } catch (error) { console.error('[Hikvision] fetchTasks 错误:', error); return this.errorResponse('hikvision.fetchTasks', error.message); } } /** * 客户端确认接收任务 * 创建 wms_pack_task_video 记录,状态改为 recording */ async receiveTask(data) { const { app } = this; const { taskId, uniqueCode, ok, message } = data || {}; if (!uniqueCode) { return this.errorResponse('hikvision.receiveTask', '缺少 uniqueCode'); } try { // 从 uniqueCode 解析 pack_task_id(格式: {task_id}_{device_id}) const parts = uniqueCode.split('_'); const packTaskId = parseInt(parts[0]); if (!packTaskId) { return this.errorResponse('hikvision.receiveTask', '无法解析 pack_task_id'); } if (ok) { // 任务接收成功 → 创建录像记录,状态 recording const existingVideo = await app.mysql.get('wms').get('wms_pack_task_video', { pack_task_id: packTaskId, deleted_at: null, }); if (!existingVideo) { await app.mysql.get('wms').insert('wms_pack_task_video', { pack_task_id: packTaskId, video_url: '', status: 'recording', remark: message || '任务已接收', }); } else if (existingVideo.status === 'created') { await app.mysql.get('wms').update('wms_pack_task_video', { status: 'recording', remark: message || '任务已接收' }, { where: { id: existingVideo.id } } ); } console.log(`[Hikvision] 录像开始: pack_task=${packTaskId}, taskId=${taskId}`); return this.successResponse('hikvision.receiveTask', { packTaskId, status: 'recording' }, '录像已开始'); } else { // 任务接收失败 console.log(`[Hikvision] 任务接收失败: pack_task=${packTaskId}, message=${message}`); return this.errorResponse('hikvision.receiveTask', message || '任务接收失败'); } } catch (error) { console.error('[Hikvision] receiveTask 错误:', error); return this.errorResponse('hikvision.receiveTask', error.message); } } /** * 客户端回调:录像任务完成 * 成功 → 写入 video_url,状态 completed * 失败 → 写入 remark,状态 failed */ async taskComplete(data) { const { app } = this; const { taskId, uniqueCode, status, success, output, size, duration, speed, fileUrl, error: errorMsg } = data || {}; if (!uniqueCode) { return this.errorResponse('hikvision.taskComplete', '缺少 uniqueCode'); } try { const parts = uniqueCode.split('_'); const packTaskId = parseInt(parts[0]); if (!packTaskId) { return this.errorResponse('hikvision.taskComplete', '无法解析 pack_task_id'); } if (success && status === 'completed') { // 录像成功 await app.mysql.get('wms').update('wms_pack_task_video', { video_url: fileUrl || output || '', status: 'completed', remark: `大小:${(size / 1024 / 1024).toFixed(2)}MB, 时长:${duration}s, 倍速:${speed}x`, }, { where: { pack_task_id: packTaskId, deleted_at: null } } ); console.log(`[Hikvision] 录像完成: pack_task=${packTaskId}, url=${fileUrl}, size=${size}`); return this.successResponse('hikvision.taskComplete', { packTaskId, status: 'completed' }, '录像完成'); } else { // 录像失败 await app.mysql.get('wms').update('wms_pack_task_video', { status: 'failed', remark: errorMsg || '录像失败', }, { where: { pack_task_id: packTaskId, deleted_at: null } } ); console.log(`[Hikvision] 录像失败: pack_task=${packTaskId}, error=${errorMsg}`); return this.successResponse('hikvision.taskComplete', { packTaskId, status: 'failed' }, '录像失败已记录'); } } catch (error) { console.error('[Hikvision] taskComplete 错误:', error); return this.errorResponse('hikvision.taskComplete', error.message); } } } module.exports = HikvisionService;