-- ============================================
-- 检查门诊划价"诊疗判断"下没有数据的原因
-- ============================================

-- 1. 检查是否有诊疗类型的收费项目（context_enum = 3）
SELECT 
    COUNT(*) AS total_activity_charge_items,
    COUNT(CASE WHEN delete_flag = '0' THEN 1 END) AS active_charge_items
FROM adm_charge_item
WHERE context_enum = 3;  -- ACTIVITY = 3

-- 2. 检查诊疗类型的收费项目是否能关联到 wor_activity_definition
SELECT 
    T1.id AS charge_item_id,
    T1.encounter_id,
    T1.context_enum,
    T1.product_id,
    T1.status_enum AS charge_status,
    T2.id AS activity_def_id,
    T2.name AS activity_name,
    T2.status_enum AS activity_status,
    T2.delete_flag AS activity_delete_flag,
    CASE 
        WHEN T2.id IS NULL THEN '❌ 无法关联到诊疗项目定义'
        WHEN T2.delete_flag != '0' THEN '❌ 诊疗项目定义已删除'
        WHEN T2.status_enum != 1 THEN '❌ 诊疗项目定义未激活（status_enum != 1）'
        ELSE '✅ 正常'
    END AS match_status
FROM adm_charge_item AS T1
LEFT JOIN wor_activity_definition AS T2
    ON T1.context_enum = 3
    AND T1.product_id = T2.id
    AND T2.delete_flag = '0'
    AND T2.status_enum = 1  -- 当前查询条件
WHERE T1.context_enum = 3
  AND T1.delete_flag = '0'
LIMIT 20;

-- 3. 检查如果移除 status_enum = 1 条件，能关联多少条
SELECT 
    COUNT(*) AS total_count,
    COUNT(CASE WHEN T2.id IS NOT NULL AND T2.delete_flag = '0' AND T2.status_enum = 1 THEN 1 END) AS matched_active,
    COUNT(CASE WHEN T2.id IS NOT NULL AND T2.delete_flag = '0' AND T2.status_enum != 1 THEN 1 END) AS matched_inactive,
    COUNT(CASE WHEN T2.id IS NULL THEN 1 END) AS unmatched
FROM adm_charge_item AS T1
LEFT JOIN wor_activity_definition AS T2
    ON T1.context_enum = 3
    AND T1.product_id = T2.id
    AND T2.delete_flag = '0'
WHERE T1.context_enum = 3
  AND T1.delete_flag = '0';

-- 4. 检查具体某个就诊的诊疗项目（替换 encounterId 为实际值）
-- SELECT 
--     T1.id AS charge_item_id,
--     T1.encounter_id,
--     T1.product_id,
--     T1.status_enum AS charge_status,
--     T2.id AS activity_def_id,
--     T2.name AS activity_name,
--     T2.status_enum AS activity_status,
--     CASE 
--         WHEN T2.id IS NULL THEN '无法关联'
--         WHEN T2.status_enum != 1 THEN '诊疗项目未激活'
--         ELSE '正常'
--     END AS status
-- FROM adm_charge_item AS T1
-- LEFT JOIN wor_activity_definition AS T2
--     ON T1.context_enum = 3
--     AND T1.product_id = T2.id
--     AND T2.delete_flag = '0'
--     AND T2.status_enum = 1
-- WHERE T1.encounter_id = :encounterId  -- 替换为实际的encounterId
--   AND T1.context_enum = 3
--   AND T1.delete_flag = '0';

-- 5. 如果诊疗项目 status_enum != 1，查看这些项目
SELECT 
    T1.id AS charge_item_id,
    T1.encounter_id,
    T1.product_id,
    T2.name AS activity_name,
    T2.status_enum AS activity_status,
    '诊疗项目未激活，导致无法显示' AS issue
FROM adm_charge_item AS T1
INNER JOIN wor_activity_definition AS T2
    ON T1.context_enum = 3
    AND T1.product_id = T2.id
    AND T2.delete_flag = '0'
    AND T2.status_enum != 1  -- 未激活
WHERE T1.context_enum = 3
  AND T1.delete_flag = '0'
LIMIT 20;

