-- 修复手术申请表中申请科室和主刀医生姓名为空的问题
-- 执行时间：2026-03-31
-- 说明：填充 cli_surgery 表中 apply_dept_name 和 main_surgeon_name 为空的记录

-- 1. 查看当前字段的填充情况
SELECT
    COUNT(*) as total_count,
    COUNT(apply_dept_id) as has_apply_dept_id_count,
    COUNT(apply_dept_name) as has_apply_dept_name_count,
    COUNT(*) - COUNT(apply_dept_name) as apply_dept_name_null_count,
    COUNT(main_surgeon_id) as has_main_surgeon_id_count,
    COUNT(main_surgeon_name) as has_main_surgeon_name_count,
    COUNT(*) - COUNT(main_surgeon_name) as main_surgeon_name_null_count
FROM public.cli_surgery
WHERE delete_flag = '0';

-- 2. 修复申请科室名称（根据 apply_dept_id 关联 adm_organization 表）
UPDATE public.cli_surgery s
SET apply_dept_name = o.name
FROM public.adm_organization o
WHERE s.apply_dept_id = o.id
AND (s.apply_dept_name IS NULL OR s.apply_dept_name = '')
AND s.delete_flag = '0';

-- 3. 修复主刀医生姓名（根据 main_surgeon_id 关联 sys_user 表）
UPDATE public.cli_surgery s
SET main_surgeon_name = u.nick_name
FROM public.sys_user u
WHERE s.main_surgeon_id = u.user_id
AND (s.main_surgeon_name IS NULL OR s.main_surgeon_name = '')
AND s.delete_flag = '0';

-- 4. 对于 apply_dept_id 为空但有 org_id 的记录，使用 org_name 作为申请科室
UPDATE public.cli_surgery s
SET apply_dept_name = o.name,
    apply_dept_id = s.org_id
FROM public.adm_organization o
WHERE s.org_id = o.id
AND (s.apply_dept_name IS NULL OR s.apply_dept_name = '')
AND s.delete_flag = '0';

-- 5. 验证修复结果 - 查看仍有空值的记录
SELECT
    id,
    surgery_no,
    patient_name,
    apply_dept_id,
    apply_dept_name,
    main_surgeon_id,
    main_surgeon_name,
    create_time
FROM public.cli_surgery
WHERE delete_flag = '0'
AND (apply_dept_name IS NULL OR apply_dept_name = '' OR main_surgeon_name IS NULL OR main_surgeon_name = '')
ORDER BY create_time DESC
LIMIT 20;
