-- ============================================
-- 快速检查 pricing_flag = '0' 的数据问题
-- 注意：pricing_flag 是 char(1) 类型，所以要用字符串 '0'
-- ============================================

-- 问题1：检查是否有费用定价但 pricing_flag = '0' 的项目（可能异常）
SELECT 
    '异常：有费用定价但不允许划价' AS issue_type,
    T1.id,
    T1.bus_no,
    T1.name AS activity_name,
    T1.pricing_flag,
    T2.charge_name,
    T2.price
FROM wor_activity_definition AS T1
INNER JOIN adm_charge_item_definition AS T2
    ON T2.instance_id = T1.id
    AND T2.delete_flag = '0'
    AND T2.status_enum = 1
    AND T2.instance_table = 'wor_activity_definition'
WHERE T1.delete_flag = '0'
  AND T1.status_enum = 1
  AND T1.pricing_flag = '0'  -- 不允许划价，但有费用定价（矛盾）
ORDER BY T1.id;

-- 问题2：检查是否已被使用但 pricing_flag = '0' 的项目（可能异常）
SELECT 
    '异常：已有收费记录但不允许划价' AS issue_type,
    T1.id,
    T1.bus_no,
    T1.name AS activity_name,
    T1.pricing_flag,
    COUNT(DISTINCT T3.encounter_id) AS encounter_count,
    COUNT(T3.id) AS charge_item_count
FROM wor_activity_definition AS T1
INNER JOIN adm_charge_item AS T3
    ON T3.product_id = T1.id
    AND T3.context_enum = 3  -- ACTIVITY
    AND T3.delete_flag = '0'
WHERE T1.delete_flag = '0'
  AND T1.pricing_flag = '0'
GROUP BY T1.id, T1.bus_no, T1.name, T1.pricing_flag
ORDER BY charge_item_count DESC;

-- 问题3：查看所有 pricing_flag = '0' 的项目，判断哪些可能应该改为 '1'
SELECT 
    T1.id,
    T1.bus_no,
    T1.name AS activity_name,
    T1.category_code,
    T1.pricing_flag,
    T1.status_enum,
    CASE 
        WHEN T2.id IS NOT NULL THEN '有费用定价'
        ELSE '无费用定价'
    END AS has_charge_definition,
    CASE 
        WHEN EXISTS (
            SELECT 1 FROM adm_charge_item 
            WHERE product_id = T1.id 
            AND context_enum = 3 
            AND delete_flag = '0'
        ) THEN '已被使用'
        ELSE '未使用'
    END AS usage_status,
    CASE 
        WHEN T2.id IS NOT NULL OR EXISTS (
            SELECT 1 FROM adm_charge_item 
            WHERE product_id = T1.id 
            AND context_enum = 3 
            AND delete_flag = '0'
        ) THEN '建议改为 pricing_flag = ''1'''
        ELSE '保持 pricing_flag = ''0''（可能正常）'
    END AS suggestion
FROM wor_activity_definition AS T1
LEFT JOIN adm_charge_item_definition AS T2
    ON T2.instance_id = T1.id
    AND T2.delete_flag = '0'
    AND T2.status_enum = 1
    AND T2.instance_table = 'wor_activity_definition'
WHERE T1.delete_flag = '0'
  AND T1.status_enum = 1
  AND T1.pricing_flag = '0'
ORDER BY T1.id;


