-- Bug #437 数据排查：查询手术计费中的重复收费项
-- 用法：在生产环境执行前先在测试环境验证
-- 作者：荀彧

-- 1. 查找手术计费中的重复收费项（同一手术+同一产品产生多条记录）
SELECT 
    encounter_id AS "就诊ID",
    product_table AS "产品表",
    product_id AS "产品ID",
    service_table AS "服务表",
    service_id AS "服务ID",
    generate_source_enum AS "生成来源",
    COUNT(*) AS "重复次数",
    STRING_AGG(id::TEXT, ',') AS "收费项ID列表",
    STRING_AGG(status_enum::TEXT, ',') AS "状态列表",
    STRING_AGG(total_price::TEXT, ',') AS "金额列表",
    STRING_AGG(create_time::TEXT, ',') AS "创建时间列表"
FROM adm_charge_item
WHERE delete_flag = '0'
  AND generate_source_enum IN (1, 2)  -- 医生开立(1) 或 护士划价(2)
  AND product_table IN ('cli_surgery', 'wor_device_request', 'wor_activity_definition')
GROUP BY encounter_id, product_table, product_id, service_table, service_id, generate_source_enum
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC;

-- 2. 查找同一手术单号下是否有重复的收费项
SELECT 
    ci.product_id AS "手术ID",
    cs.surgery_no AS "手术单号",
    cs.surgery_name AS "手术名称",
    COUNT(ci.id) AS "收费项数量",
    STRING_AGG(ci.id::TEXT || '(' || ci.status_enum || ')' || '=' || ci.total_price, '; ') AS "收费项详情"
FROM adm_charge_item ci
LEFT JOIN cli_surgery cs ON ci.product_id = cs.id
WHERE ci.delete_flag = '0'
  AND ci.product_table = 'cli_surgery'
  AND ci.generate_source_enum = 1
GROUP BY ci.product_id, cs.surgery_no, cs.surgery_name
HAVING COUNT(ci.id) > 1
ORDER BY COUNT(ci.id) DESC;

-- 3. 统计重复数据量（用于评估影响范围）
SELECT 
    generate_source_enum AS "生成来源(1=医生开立,2=护士划价)",
    product_table AS "产品表",
    COUNT(*) AS "重复组数",
    SUM(cnt - 1) AS "多余记录数"
FROM (
    SELECT 
        generate_source_enum,
        product_table,
        COUNT(*) AS cnt
    FROM adm_charge_item
    WHERE delete_flag = '0'
    GROUP BY encounter_id, product_table, product_id, service_table, service_id, generate_source_enum
    HAVING COUNT(*) > 1
) sub
GROUP BY generate_source_enum, product_table
ORDER BY SUM(cnt - 1) DESC;
