-- 填充手术表中的name字段
-- 执行时间：2025-01-05
-- 说明：根据现有的ID字段反查并填充对应的name字段

-- 1. 查看当前name字段的填充情况
SELECT
    COUNT(*) as total_count,
    COUNT(main_surgeon_name) as has_main_surgeon_name_count,
    COUNT(anesthetist_name) as has_anesthetist_name_count,
    COUNT(assistant_1_name) as has_assistant_1_name_count,
    COUNT(assistant_2_name) as has_assistant_2_name_count,
    COUNT(scrub_nurse_name) as has_scrub_nurse_name_count,
    COUNT(operating_room_name) as has_operating_room_name_count,
    COUNT(org_name) as has_org_name_count,
    COUNT(apply_doctor_name) as has_apply_doctor_name_count,
    COUNT(apply_dept_name) as has_apply_dept_name_count
FROM public.cli_surgery
WHERE delete_flag = '0';

-- 2. 填充主刀医生姓名
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
AND s.delete_flag = '0';

-- 3. 填充麻醉医生姓名
UPDATE public.cli_surgery s
SET anesthetist_name = u.nick_name
FROM public.sys_user u
WHERE s.anesthetist_id = u.user_id
AND s.anesthetist_name IS NULL
AND s.delete_flag = '0';

-- 4. 填充助手1姓名
UPDATE public.cli_surgery s
SET assistant_1_name = u.nick_name
FROM public.sys_user u
WHERE s.assistant_1_id = u.user_id
AND s.assistant_1_name IS NULL
AND s.delete_flag = '0';

-- 5. 填充助手2姓名
UPDATE public.cli_surgery s
SET assistant_2_name = u.nick_name
FROM public.sys_user u
WHERE s.assistant_2_id = u.user_id
AND s.assistant_2_name IS NULL
AND s.delete_flag = '0';

-- 6. 填充巡回护士姓名
UPDATE public.cli_surgery s
SET scrub_nurse_name = u.nick_name
FROM public.sys_user u
WHERE s.scrub_nurse_id = u.user_id
AND s.scrub_nurse_name IS NULL
AND s.delete_flag = '0';

-- 7. 填充手术室名称
UPDATE public.cli_surgery s
SET operating_room_name = r.name
FROM public.cli_operating_room r
WHERE s.operating_room_id = r.id
AND s.operating_room_name IS NULL
AND s.delete_flag = '0';

-- 8. 填充执行科室名称
UPDATE public.cli_surgery s
SET org_name = o.name
FROM public.adm_organization o
WHERE s.org_id = o.id
AND s.org_name IS NULL
AND s.delete_flag = '0';

-- 9. 填充申请医生姓名（如果还没有）
UPDATE public.cli_surgery s
SET apply_doctor_name = u.nick_name
FROM public.sys_user u
WHERE s.apply_doctor_id = u.user_id
AND s.apply_doctor_name IS NULL
AND s.delete_flag = '0';

-- 10. 填充申请科室名称（如果还没有）
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
AND s.delete_flag = '0';

-- 11. 再次查询，验证更新结果
SELECT
    id,
    surgery_no,
    patient_name,
    apply_doctor_name,
    apply_dept_name,
    main_surgeon_name,
    anesthetist_name,
    assistant_1_name,
    assistant_2_name,
    scrub_nurse_name,
    operating_room_name,
    org_name,
    emergency_flag,
    implant_flag,
    operating_room_confirm_time,
    operating_room_confirm_user,
    create_time
FROM public.cli_surgery
WHERE delete_flag = '0'
ORDER BY create_time DESC
LIMIT 10;
