SET NAMES utf8mb4;
SET CHARACTER SET utf8mb4;
SET character_set_client = utf8mb4;
SET character_set_connection = utf8mb4;
SET character_set_results = utf8mb4;

-- 迁移前检查 1：找不到对应本人 biz_id 的亲属记录
SELECT
    child.biz_id AS child_biz_id,
    child.name AS child_name,
    child.person_id AS child_person_id,
    child.related_num_id AS legacy_owner_biz_id
FROM ccdi_biz_intermediary child
LEFT JOIN ccdi_biz_intermediary parent
    ON child.related_num_id = parent.biz_id
   AND parent.person_sub_type = '本人'
WHERE child.person_sub_type <> '本人'
  AND (child.related_num_id IS NULL OR parent.biz_id IS NULL);

-- 迁移前检查 2：本人 person_id 为空的记录
SELECT
    child.biz_id AS child_biz_id,
    child.name AS child_name,
    child.person_id AS child_person_id,
    child.related_num_id AS legacy_owner_biz_id,
    parent.biz_id AS parent_biz_id,
    parent.name AS parent_name,
    parent.person_id AS parent_person_id
FROM ccdi_biz_intermediary child
JOIN ccdi_biz_intermediary parent
    ON child.related_num_id = parent.biz_id
   AND parent.person_sub_type = '本人'
WHERE child.person_sub_type <> '本人'
  AND (parent.person_id IS NULL OR TRIM(parent.person_id) = '');

-- 迁移前检查 3：迁移后同一中介本人下 related_num_id + person_id 冲突的记录
SELECT
    parent.person_id AS owner_person_id,
    child.person_id AS relative_person_id,
    COUNT(*) AS conflict_count,
    GROUP_CONCAT(child.biz_id ORDER BY child.biz_id SEPARATOR ',') AS child_biz_ids
FROM ccdi_biz_intermediary child
JOIN ccdi_biz_intermediary parent
    ON child.related_num_id = parent.biz_id
   AND parent.person_sub_type = '本人'
WHERE child.person_sub_type <> '本人'
  AND parent.person_id IS NOT NULL
  AND TRIM(parent.person_id) <> ''
GROUP BY parent.person_id, child.person_id
HAVING COUNT(*) > 1;

START TRANSACTION;

UPDATE ccdi_biz_intermediary child
JOIN ccdi_biz_intermediary parent
    ON child.related_num_id = parent.biz_id
SET child.related_num_id = parent.person_id
WHERE child.person_sub_type <> '本人';

COMMIT;

-- 迁移后检查：亲属记录应统一按本人证件号码关联
SELECT
    child.biz_id AS child_biz_id,
    child.related_num_id AS owner_person_id,
    parent.biz_id AS parent_biz_id,
    parent.person_id AS parent_person_id
FROM ccdi_biz_intermediary child
LEFT JOIN ccdi_biz_intermediary parent
    ON child.related_num_id = parent.person_id
   AND parent.person_sub_type = '本人'
WHERE child.person_sub_type <> '本人'
  AND (child.related_num_id IS NULL OR parent.biz_id IS NULL);
