-- ============================================================
-- Bug #318 历史数据修复 - 简化版SQL脚本
-- 为已存在但未生成手术医嘱的手术申请单补齐数据
-- ============================================================
-- 执行说明：
-- 1. 在数据库管理工具中执行（如 DBeaver、pgAdmin）
-- 2. 建议先执行查询部分确认数据
-- 3. 备份数据库后再执行修复
-- ============================================================

-- 步骤1: 查看需要修复的记录数
-- ============================================================
SELECT 
    '需要修复的手术申请单数量' as 检查项,
    COUNT(*) as 数量
FROM doc_request_form rf
LEFT JOIN wor_service_request sr ON sr.prescription_no = rf.prescription_no 
    AND sr.delete_flag = '0'
WHERE rf.type_code = 'PROCEDURE'
  AND rf.delete_flag = '0'
  AND sr.id IS NULL;

-- 步骤2: 查看详细列表（可选）
-- ============================================================
/*
SELECT 
    rf.id as request_form_id,
    rf.prescription_no as 手术单号,
    rf.encounter_id as 就诊ID,
    rf.patient_id as 患者ID,
    rf.create_time as 申请时间
FROM doc_request_form rf
LEFT JOIN wor_service_request sr ON sr.prescription_no = rf.prescription_no 
    AND sr.delete_flag = '0'
WHERE rf.type_code = 'PROCEDURE'
  AND rf.delete_flag = '0'
  AND sr.id IS NULL
ORDER BY rf.create_time DESC
LIMIT 10;
*/

-- 步骤3: 执行修复 - 生成手术医嘱（ServiceRequest）
-- ============================================================
-- ⚠️ 请在确认备份数据库后执行以下语句

INSERT INTO wor_service_request (
    bus_no,
    prescription_no,
    status_enum,
    generate_source_enum,
    therapy_enum,
    quantity,
    unit_code,
    category_enum,
    patient_id,
    requester_id,
    encounter_id,
    authored_time,
    org_id,
    content_json,
    delete_flag,
    create_time,
    create_by,
    tenant_id
)
SELECT 
    LPAD(FLOOR(RANDOM() * 10000)::TEXT, 4, '0') as bus_no,  -- 生成4位随机数
    rf.prescription_no,
    1 as status_enum,          -- 1-待签发
    1 as generate_source_enum, -- 1-医生处方
    2 as therapy_enum,         -- 2-临时医嘱
    1 as quantity,
    '次' as unit_code,
    4 as category_enum,        -- 4-手术
    rf.patient_id,
    rf.requester_id,
    rf.encounter_id,
    rf.create_time as authored_time,
    rf.org_id,
    rf.desc_json as content_json,  -- 存储手术详情
    '0' as delete_flag,
    rf.create_time,
    rf.requester_id as create_by,
    1 as tenant_id
FROM doc_request_form rf
LEFT JOIN wor_service_request sr ON sr.prescription_no = rf.prescription_no 
    AND sr.delete_flag = '0'
WHERE rf.type_code = 'PROCEDURE'
  AND rf.delete_flag = '0'
  AND sr.id IS NULL;

-- 步骤4: 查看生成的手术医嘱数量
-- ============================================================
SELECT 
    '生成的手术医嘱数量' as 检查项,
    COUNT(*) as 数量
FROM wor_service_request
WHERE category_enum = 4
  AND delete_flag = '0'
  AND create_time > CURRENT_TIMESTAMP - INTERVAL '1 hour';  -- 最近1小时生成的

-- 步骤5: 生成手术收费项目（ChargeItem）
-- ============================================================
-- 先创建临时表存储新生成的ServiceRequest
CREATE TEMPORARY TABLE temp_new_service_requests AS
SELECT 
    sr.id as service_request_id,
    sr.bus_no,
    sr.prescription_no,
    sr.patient_id,
    sr.encounter_id,
    sr.requester_id,
    sr.create_time,
    sr.org_id,
    sr.content_json
FROM wor_service_request sr
WHERE sr.category_enum = 4
  AND sr.delete_flag = '0'
  AND sr.create_time > CURRENT_TIMESTAMP - INTERVAL '1 hour';  -- 最近1小时生成的

-- 插入手术费用收费项目
INSERT INTO adm_charge_item (
    bus_no,
    status_enum,
    generate_source_enum,
    patient_id,
    context_enum,
    encounter_id,
    enterer_id,
    entered_date,
    service_table,
    service_id,
    product_table,
    requesting_org_id,
    quantity_value,
    quantity_unit,
    unit_price,
    total_price,
    delete_flag,
    create_time,
    create_by,
    tenant_id
)
SELECT 
    'CI' || t.bus_no as bus_no,
    1 as status_enum,          -- 1-草稿
    1 as generate_source_enum, -- 1-医生处方
    t.patient_id,
    3 as context_enum,         -- 3-诊疗
    t.encounter_id,
    t.requester_id as enterer_id,
    t.create_time as entered_date,
    'wor_service_request' as service_table,
    t.service_request_id as service_id,
    'wor_activity_definition' as product_table,
    t.org_id as requesting_org_id,
    1 as quantity_value,
    '次' as quantity_unit,
    COALESCE((t.content_json::jsonb->>'surgeryFee')::numeric, 0) as unit_price,
    COALESCE((t.content_json::jsonb->>'surgeryFee')::numeric, 0) as total_price,
    '0' as delete_flag,
    t.create_time,
    t.requester_id as create_by,
    1 as tenant_id
FROM temp_new_service_requests t
WHERE COALESCE((t.content_json::jsonb->>'surgeryFee')::numeric, 0) >= 0;

-- 插入麻醉费用收费项目（如果有麻醉费用）
INSERT INTO adm_charge_item (
    bus_no,
    status_enum,
    generate_source_enum,
    patient_id,
    context_enum,
    encounter_id,
    enterer_id,
    entered_date,
    service_table,
    service_id,
    product_table,
    requesting_org_id,
    quantity_value,
    quantity_unit,
    unit_price,
    total_price,
    delete_flag,
    create_time,
    create_by,
    tenant_id
)
SELECT 
    'CI' || t.bus_no || '_A' as bus_no,
    1 as status_enum,
    1 as generate_source_enum,
    t.patient_id,
    3 as context_enum,
    t.encounter_id,
    t.requester_id as enterer_id,
    t.create_time as entered_date,
    'wor_service_request' as service_table,
    t.service_request_id as service_id,
    'wor_activity_definition' as product_table,
    t.org_id as requesting_org_id,
    1 as quantity_value,
    '次' as quantity_unit,
    (t.content_json::jsonb->>'anesthesiaFee')::numeric as unit_price,
    (t.content_json::jsonb->>'anesthesiaFee')::numeric as total_price,
    '0' as delete_flag,
    t.create_time,
    t.requester_id as create_by,
    1 as tenant_id
FROM temp_new_service_requests t
WHERE t.content_json::jsonb->>'anesthesiaFee' IS NOT NULL
  AND (t.content_json::jsonb->>'anesthesiaFee')::numeric > 0;

-- 步骤6: 验证修复结果
-- ============================================================
SELECT 
    '手术医嘱总数' as 检查项,
    COUNT(*) as 数量
FROM wor_service_request
WHERE category_enum = 4
  AND delete_flag = '0';

SELECT 
    '手术收费项目总数' as 检查项,
    COUNT(*) as 数量
FROM adm_charge_item ci
WHERE ci.service_table = 'wor_service_request'
  AND EXISTS (
      SELECT 1 FROM wor_service_request sr 
      WHERE sr.id = ci.service_id AND sr.category_enum = 4
  );

-- 清理临时表
DROP TABLE IF EXISTS temp_new_service_requests;

-- ============================================================
-- ✓ 修复完成！
-- ============================================================
