-- 快速诊断诊疗项目检索问题
-- 已知：wor_activity_definition 表中有4条数据
-- 关键：ChargeItemContext.ACTIVITY.getValue() = 3（整数）

-- 步骤1：检查这4条诊疗项目定义的delete_flag状态
SELECT 
    id,
    name,
    delete_flag,
    CASE WHEN delete_flag = '0' THEN '✅ 可用' ELSE '❌ 已删除' END as status
FROM wor_activity_definition
ORDER BY id;

-- 步骤2：检查收费项目中是否有诊疗项目类型（context_enum = 3）的记录
SELECT 
    COUNT(*) as total_count,
    COUNT(CASE WHEN delete_flag = '0' THEN 1 END) as active_count
FROM adm_charge_item
WHERE (context_enum::text = '3' OR context_enum = 3);

-- 步骤3：检查收费项目能否匹配到诊疗项目定义（最关键！）
SELECT 
    aci.id as charge_item_id,
    aci.encounter_id,
    aci.product_id,
    aci.status_enum,
    wad.id as activity_def_id,
    wad.name as activity_name,
    CASE 
        WHEN wad.id IS NULL THEN '❌ 无法匹配：product_id=' || aci.product_id || ' 在诊疗项目定义表中不存在'
        WHEN wad.delete_flag != '0' THEN '❌ 无法匹配：诊疗项目定义已删除'
        WHEN aci.delete_flag != '0' THEN '❌ 无法匹配：收费项目已删除'
        WHEN aci.status_enum NOT IN (1,2,3,4,5,6) THEN '❌ 无法匹配：状态不在查询范围内 status=' || aci.status_enum
        ELSE '✅ 可以匹配'
    END as match_result
FROM adm_charge_item aci
LEFT JOIN wor_activity_definition wad 
    ON aci.product_id = wad.id AND wad.delete_flag = '0'
WHERE (aci.context_enum::text = '3' OR aci.context_enum = 3)
    AND aci.delete_flag = '0'
LIMIT 50;

-- 步骤4：统计匹配情况
SELECT 
    COUNT(*) as total_charge_items,
    COUNT(CASE WHEN wad.id IS NOT NULL AND wad.delete_flag = '0' THEN 1 END) as matched_count,
    COUNT(CASE WHEN wad.id IS NULL THEN 1 END) as unmatched_def_count,
    COUNT(CASE WHEN wad.delete_flag != '0' THEN 1 END) as deleted_def_count,
    COUNT(CASE WHEN wad.id IS NOT NULL AND wad.delete_flag = '0' AND aci.status_enum IN (1,2,3,4,5,6) THEN 1 END) as final_matched_count
FROM adm_charge_item aci
LEFT JOIN wor_activity_definition wad 
    ON aci.product_id = wad.id
WHERE (aci.context_enum::text = '3' OR aci.context_enum = 3)
    AND aci.delete_flag = '0';

-- 步骤5：检查具体就诊的诊疗项目（如果有encounterId，取消注释并替换）
-- SELECT 
--     T1.encounter_id,
--     T1.id as charge_item_id,
--     T1.product_id,
--     T1.status_enum,
--     T2.id as activity_def_id,
--     T2.name as activity_name,
--     CASE 
--         WHEN T2.id IS NULL THEN '❌ 无法匹配'
--         WHEN T2.delete_flag != '0' THEN '❌ 定义已删除'
--         WHEN T1.status_enum NOT IN (1,2,3,4,5,6) THEN '❌ 状态不符合'
--         ELSE '✅ 正常'
--     END as status
-- FROM adm_charge_item AS T1
-- LEFT JOIN wor_activity_definition AS T2
--     ON T1.product_id = T2.id AND T2.delete_flag = '0'
-- WHERE T1.encounter_id = :encounterId  -- 替换为实际的encounterId
--     AND (T1.context_enum::text = '3' OR T1.context_enum = 3)
--     AND T1.delete_flag = '0';
















