-- ============================================
-- 修复遗漏的手术医嘱数据
-- ============================================

-- 查看需要修复的记录
SELECT 
    wsr.id,
    wsr.activity_id,
    cs.surgery_name,
    cs.surgery_code,
    wsr.create_time
FROM wor_service_request wsr
LEFT JOIN cli_surgery cs ON cs.id = wsr.activity_id
WHERE wsr.category_enum = 4
AND wsr.delete_flag = '0'
AND (wsr.content_json::jsonb->>'surgeryName' IS NULL OR wsr.content_json::jsonb->>'surgeryName' = '')
AND cs.surgery_name IS NOT NULL
ORDER BY wsr.create_time DESC;

-- 执行修复
UPDATE wor_service_request wsr
SET content_json = 
    COALESCE(
        (wsr.content_json::jsonb || jsonb_build_object(
            'surgeryName', cs.surgery_name,
            'surgeryCode', COALESCE(cs.surgery_code, '')
        ))::text,
        jsonb_build_object(
            'surgeryName', cs.surgery_name,
            'surgeryCode', COALESCE(cs.surgery_code, '')
        )::text
    )
FROM cli_surgery cs
WHERE wsr.category_enum = 4
AND wsr.delete_flag = '0'
AND (wsr.content_json::jsonb->>'surgeryName' IS NULL OR wsr.content_json::jsonb->>'surgeryName' = '')
AND cs.id = wsr.activity_id
AND cs.surgery_name IS NOT NULL
AND cs.delete_flag = '0';

-- 验证修复结果
SELECT 
    'Remaining empty records' as status,
    COUNT(*) as count
FROM wor_service_request
WHERE category_enum = 4
AND delete_flag = '0'
AND (content_json::jsonb->>'surgeryName' IS NULL OR content_json::jsonb->>'surgeryName' = '');
