-- 迁移-添加camera_code字段.sql
-- 功能：为 wvp_stream_proxy 表添加 camera_code 字段作为全局唯一标识

-- 1. 新增 camera_code 列（允许NULL，稍后填充数据）
ALTER TABLE wvp_stream_proxy
  ADD COLUMN camera_code VARCHAR(64) NULL COMMENT '摄像头全局唯一编码（格式：cam_xxxxxxxxxxxx）';

-- 2. 为现有数据生成 camera_code（基于 ID 生成12位哈希）
UPDATE wvp_stream_proxy
  SET camera_code = CONCAT('cam_', SUBSTRING(MD5(CAST(id AS CHAR)), 1, 12))
  WHERE camera_code IS NULL OR camera_code = '';

-- 3. 将 camera_code 设为 NOT NULL 并添加唯一索引
ALTER TABLE wvp_stream_proxy
  MODIFY COLUMN camera_code VARCHAR(64) NOT NULL,
  ADD UNIQUE KEY uk_camera_code (camera_code);

-- 4. 验证数据完整性
SELECT '检查重复的 camera_code' AS check_name, COUNT(*) AS issue_count
FROM (
  SELECT camera_code, COUNT(*) AS cnt
  FROM wvp_stream_proxy
  GROUP BY camera_code
  HAVING cnt > 1
) AS duplicates;

-- 5. 验证 camera_code 格式（应为 cam_xxxxxxxxxxxx，12位十六进制字符）
SELECT '检查格式错误的 camera_code' AS check_name, COUNT(*) AS issue_count
FROM wvp_stream_proxy
WHERE camera_code NOT REGEXP '^cam_[a-f0-9]{12}$';

-- 6. 更新 ROI 表中的 camera_id（从 app/stream 格式改为 camera_code）
UPDATE wvp_ai_roi r
  INNER JOIN wvp_stream_proxy sp ON r.camera_id = CONCAT(sp.app, '/', sp.stream)
  SET r.camera_id = sp.camera_code;

-- 7. 验证 ROI 更新结果
SELECT '检查未匹配的 ROI' AS check_name, COUNT(*) AS issue_count
FROM wvp_ai_roi r
LEFT JOIN wvp_stream_proxy sp ON r.camera_id = sp.camera_code
WHERE sp.camera_code IS NULL;

-- 8. 显示迁移后的样本数据
SELECT id, camera_code, app, stream, name
FROM wvp_stream_proxy
LIMIT 5;

SELECT roi_id, camera_id, name
FROM wvp_ai_roi
LIMIT 5;
