<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.openhis.web.outpatientmanage.mapper.OutpatientManageMapper">

    <!-- 门诊皮试记录相关查询-->
    <select id="getSkinTestRecords"
            parameterType="com.openhis.web.outpatientmanage.dto.OutpatientSkinTestRecordSearchParam"
            resultType="com.openhis.web.outpatientmanage.dto.OutpatientSkinTestRecordDto">
        SELECT
        sr.id, --服务申请管理ID
        sr.prescription_no, --处方号
        e.bus_no as encounterBusNo, --就诊号
        pt.name AS patientName, --病人姓名
        pt.bus_no AS patientBusNo, --病人ID（前台显示用）
        sr.patient_id, --病人ID
        ad.name AS medicationInformation, --药品信息
        md.bus_no || ' ' || md.name || ' 规格：' || COALESCE(m.total_volume, '') AS medicationDetail,--药品
        m.lot_number AS medicationLotNumber, --药品批次号
        mr.status_enum AS medicationStatusEnum, --药品状态
        sr.performer_id, --执行护士
        sr.performer_check_id,--核对人
        to_char(sr.occurrence_start_time, 'YYYY-MM-DD HH24:MI:SS') AS occurrenceStartTime, --预计执行时间
        to_char(sr.occurrence_end_time, 'YYYY-MM-DD HH24:MI:SS') AS occurrenceEndTime, --预计结束时间
        ai.clinical_status_enum, --皮试结果
        ai.verification_status_enum, --皮试检查项目状态
        mr.practitioner_id as doctorId, --开单医生
        ai.note --备注
        FROM
        wor_service_request sr
        LEFT JOIN adm_encounter e ON e.id = sr.encounter_id
        LEFT JOIN adm_patient pt ON pt.id = sr.patient_id
        LEFT JOIN wor_activity_definition ad ON ad.id = sr.activity_id
        LEFT JOIN med_medication_request mr ON mr.prescription_no = sr.prescription_no
        LEFT JOIN med_medication m ON m.id = mr.medication_id
        LEFT JOIN med_medication_definition md ON md.id = m.medication_def_id
        LEFT JOIN cli_allergy_intolerance ai ON ai.request_id = sr.id
        <where>
            ad.bus_no = 'ps001' -- 皮试检查的编号，todo：编号未定，后期修改
            AND mr.skin_test_flag = 1
            AND md.skin_test_flag = 1
            AND sr.status_enum in (2,3,6) --服务状态有效

            <!-- 门诊号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.encounterBusNo != null and OutpatientSkinTestRecordSearchParam.encounterBusNo != ''">
                AND e.bus_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.encounterBusNo}, '%')
            </if>

            <!-- 病人号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.patientBusNo != null and OutpatientSkinTestRecordSearchParam.patientBusNo != ''">
                AND pt.bus_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.patientBusNo}, '%')
            </if>

            <!-- 处方号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.prescriptionNo != null and OutpatientSkinTestRecordSearchParam.prescriptionNo != ''">
                AND sr.prescription_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.prescriptionNo}, '%')
            </if>

            <!-- 手机号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.phone != null and OutpatientSkinTestRecordSearchParam.phone != ''">
                AND pt.phone LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.phone}, '%')
            </if>

            <!-- 时间筛选 -->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.beginTime != null and OutpatientSkinTestRecordSearchParam.endTime != null">
                AND ai.recorded_date BETWEEN
                TO_TIMESTAMP(#{OutpatientSkinTestRecordSearchParam.beginTime} || ' 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
                AND
                TO_TIMESTAMP(#{OutpatientSkinTestRecordSearchParam.endTime} || ' 23:59:59', 'YYYY-MM-DD HH24:MI:SS')
            </if>

            <!-- 皮试项目检查状态 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.status != null and OutpatientSkinTestRecordSearchParam.status != null">
                AND ai.verification_status_enum = #{OutpatientSkinTestRecordSearchParam.status}
            </if>
        </where>
        ORDER BY sr.prescription_no,e.bus_no,md.bus_no
        LIMIT #{pageSize} OFFSET #{offset}
    </select>

    <select id="countOutpatientSkinTestRecords" resultType="long">
        SELECT COUNT(*)
        FROM
        wor_service_request sr
        LEFT JOIN adm_encounter e ON e.id = sr.encounter_id
        LEFT JOIN adm_patient pt ON pt.id = sr.patient_id
        LEFT JOIN wor_activity_definition ad ON ad.id = sr.activity_id
        LEFT JOIN med_medication_request mr ON mr.prescription_no = sr.prescription_no
        LEFT JOIN med_medication m ON m.id = mr.medication_id
        LEFT JOIN med_medication_definition md ON md.id = m.medication_def_id
        LEFT JOIN cli_allergy_intolerance ai ON ai.request_id = sr.id
        <where>
            ad.bus_no = 'ps001' -- 皮试检查的编号，todo：编号未定，后期修改
            AND mr.skin_test_flag = 1
            AND md.skin_test_flag = 1
            AND sr.status_enum in (2,3,6) --服务状态有效

            <!-- 门诊号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.encounterBusNo != null and OutpatientSkinTestRecordSearchParam.encounterBusNo != ''">
                AND e.bus_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.encounterBusNo}, '%')
            </if>

            <!-- 病人号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.patientBusNo != null and OutpatientSkinTestRecordSearchParam.patientBusNo != ''">
                AND pt.bus_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.patientBusNo}, '%')
            </if>

            <!-- 处方号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.prescriptionNo != null and OutpatientSkinTestRecordSearchParam.prescriptionNo != ''">
                AND sr.prescription_no LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.prescriptionNo}, '%')
            </if>

            <!-- 手机号 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.phone != null and OutpatientSkinTestRecordSearchParam.phone != ''">
                AND pt.phone LIKE CONCAT('%',#{OutpatientSkinTestRecordSearchParam.phone}, '%')
            </if>

            <!-- 时间筛选 -->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.beginTime != null and OutpatientSkinTestRecordSearchParam.endTime != null">
                AND ai.recorded_date BETWEEN
                TO_TIMESTAMP(#{OutpatientSkinTestRecordSearchParam.beginTime} || ' 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
                AND
                TO_TIMESTAMP(#{OutpatientSkinTestRecordSearchParam.endTime} || ' 23:59:59', 'YYYY-MM-DD HH24:MI:SS')
            </if>

            <!-- 皮试项目检查状态 查询条件-->
            <if test="OutpatientSkinTestRecordSearchParam != null and OutpatientSkinTestRecordSearchParam.status != null and OutpatientSkinTestRecordSearchParam.status != null">
                AND ai.verification_status_enum = #{OutpatientSkinTestRecordSearchParam.status}
            </if>
        </where>
    </select>

    <!-- 门诊输液记录患者列表信息查询-->
    <select id="getOutpatientInfusionPatient"
            resultType="com.openhis.web.outpatientmanage.dto.OutpatientInfusionPatientDto">
        SELECT
        T1.tenant_id,
        T1.service_id,
        T1.prescription_no,
        T1.encounter_bus_no,
        T1.birth_date,
        T1.patient_bus_no,
        T1.patient_id,
        T1.patient_name,
        T1.id_card,
        T1.gender_enum,
        T1.create_time
        FROM
        (
        SELECT DISTINCT
        sr.id AS service_id, --服务申请管理ID
        sr.prescription_no, --处方号
        sr.encounter_id,
        e.bus_no as encounter_bus_no, --就诊号
        TO_CHAR(pt.birth_date, 'YYYY-MM-DD') AS birth_date, --病人生日
        pt.bus_no AS patient_bus_no, --病人ID（前台显示用）
        sr.patient_id, --病人ID
        pt.name AS patient_name, --病人姓名
        pt.id_card AS id_card, --病人身份证号
        sr.tenant_id,
        pt.gender_enum, --病人性别
        to_char(mr.create_time, 'YYYY-MM-DD HH24:MI:SS') AS create_time--开单时间
        FROM
        wor_service_request sr
        LEFT JOIN adm_encounter e ON e.id = sr.encounter_id
        LEFT JOIN adm_patient pt ON pt.id = sr.patient_id
        LEFT JOIN wor_activity_definition ad ON ad.id = sr.activity_id
        LEFT JOIN med_medication_request mr ON mr.prescription_no = sr.prescription_no
        <where>
            ad.bus_no = 'sy001' -- 输液的编号，todo：编号未定，后期修改
            AND mr.infusion_flag = 1
            AND sr.status_enum in (2,3) --服务状态未完成
            AND sr.based_on_id is null
        </where>
        ORDER BY
        create_time,e.bus_no,pt.bus_no
        ) AS T1
        ${ew.customSqlSegment}
    </select>

    <!-- 门诊输液记录初始化，默认显示今天待执行输液记录-->
    <select id="getOutpatientInfusionRecord"
            resultType="com.openhis.web.outpatientmanage.dto.OutpatientInfusionRecordDto">
        SELECT
        T1.service_id,
        T1.request_status,
        T1.bus_no,
        T1.execute_num,
        T1.done_num,
        T1.based_on_id,
        T1.activity_id,
        T1.prescription_no,
        T1.encounter_id,
        T1.encounter_bus_no,
        T1.patient_name,
        T1.gender_enum,
        T1.patient_bus_no,
        T1.patient_id,
        T1.medication_information,
        T1.medication_id,
        T1.medication_quantity,
        T1.medication_status_enum,
        T1.rate_code,
        T1.group_id,
        T1.skin_test_flag,
        T1.speed,
        T1.method_code,
        T1.dose,
        T1.doctor_id,
        T1.perform_org,
        T1.performer_id,
        T1.occurrence_start_time,
        T1.occurrence_end_time,
        T1.create_time
        FROM
        (
        SELECT
        sr.tenant_id,
        sr.id AS service_id, --服务申请管理ID
        sr.bus_no, -- 服务请求编码
        sr.based_on_id, -- 请求基于什么的ID
        sr.activity_id,--请求code,输液
        sr.prescription_no, --处方号
        sr.encounter_id , --就诊ID
        sr.status_enum AS request_status, --服务请求状态
        e.bus_no AS encounter_bus_no, --就诊ID（前台显示用）
        pt.name AS patient_name, --病人姓名
        pt.gender_enum, --病人性别
        pt.bus_no AS patient_bus_no, --病人ID（前台显示用）
        sr.patient_id, --病人ID
        md.id AS medication_id, --药品ID
        md.name AS medication_information, --药品信息
        mr.quantity AS medication_quantity,--药品数量
        mr.status_enum AS medication_status_enum, --药品状态
        mr.rate_code, --药品状态
        mr.execute_num, -- 总执行次数
        mr.group_id, --注射药品组号
        (SELECT COUNT(*)
            FROM  wor_service_request wor
            WHERE wor.based_on_id = sr.id
            AND wor.bus_no LIKE '%-%'
            AND CAST(md.id AS CHAR) = LEFT(split_part(wor.bus_no, '-', 3), POSITION('.' IN split_part(wor.bus_no, '-', 3)) - 1)  --药品ID
            AND mr.group_id = CAST(split_part(wor.bus_no, '-', 2) AS BIGINT)-- 组号ID
        ) AS done_num ,-- 已执行次数
        mr.perform_org,--执行科室
        CASE mr.skin_test_flag
        WHEN 1 THEN 1
        ELSE 0
        END AS skin_test_flag ,--皮试标志
        mr.speed, --输液速度
        mr.method_code,--用法
        mr.dose || ' '|| mr.dose_unit_code AS dose,--单次剂量,剂量单位
        mr.practitioner_id as doctor_id, --开单医生
        mr.org_id,--开单科室
        sr.performer_id, --执行护士
        to_char(sr.occurrence_start_time, 'YYYY-MM-DD HH24:MI:SS') AS occurrence_start_time, --预计执行时间
        to_char(sr.occurrence_end_time, 'YYYY-MM-DD HH24:MI:SS') AS occurrence_end_time, --预计结束时间
        to_char(mr.create_time, 'YYYY-MM-DD HH24:MI:SS') AS create_time--开单时间
        FROM
        wor_service_request sr
        LEFT JOIN adm_encounter e ON e.id = sr.encounter_id
        LEFT JOIN adm_patient pt ON pt.id = sr.patient_id
        LEFT JOIN wor_activity_definition ad ON ad.id = sr.activity_id
        LEFT JOIN med_medication_request mr ON mr.prescription_no = sr.prescription_no
        LEFT JOIN med_medication m ON m.id = mr.medication_id
        LEFT JOIN med_medication_definition md ON md.id = m.medication_def_id
        LEFT JOIN cli_allergy_intolerance ai ON ai.request_id = sr.id
        <where>
            ad.bus_no = 'sy001' -- 输液检查的编号，todo：编号未定，后期修改
            AND mr.infusion_flag = 1

        </where>
        ORDER BY
        create_time desc,e.bus_no,pt.bus_no
        ) AS T1
        ${ew.customSqlSegment}
    </select>

    <!-- 查询药品已执行数量/查询同组内药品数量 -->
    <select id="countExecuteNumOrGroupNum" resultType="long">

        SELECT COUNT(*)
        FROM
        wor_service_request sr
        LEFT JOIN adm_encounter e ON e.id = sr.encounter_id
        LEFT JOIN adm_patient pt ON pt.id = sr.patient_id
        LEFT JOIN wor_activity_definition ad ON ad.id = sr.activity_id
        LEFT JOIN med_medication_request mr ON mr.prescription_no = sr.prescription_no
        LEFT JOIN med_medication m ON m.id = mr.medication_id
        LEFT JOIN med_medication_definition md ON md.id = m.medication_def_id
        <where>
            ad.bus_no = 'sy001' -- 输液检查的编号，todo：编号未定，后期修改
            AND mr.infusion_flag = 1

            <!-- 药品已执行数量 条件筛选 -->
            <if test="flag and paramId != null and paramId != '' and prefixBusNo != null and prefixBusNo != '' ">
                AND sr.based_on_id = #{paramId}
                AND sr.bus_no LIKE CONCAT(#{prefixBusNo}, '%')
                AND CAST(md.id AS CHAR) = LEFT(split_part(sr.bus_no, '-', 3), POSITION('.' IN split_part(sr.bus_no, '-', 3)) - 1) --药品ID
                AND mr.group_id = CAST(split_part(sr.bus_no, '-', 2) AS BIGINT)-- 组号ID
                AND sr.status_enum = 6 --服务状态是已完成

            </if>

            <!-- 同组内药品数量 条件筛选 -->
            <if test="!flag and paramId != null and paramId != '' and groupId != null and groupId != ''">
                AND sr.id = #{paramId}
                AND mr.group_id = #{groupId}
                AND sr.status_enum = 2 --服务状态是进行中
            </if>
        </where>

    </select>

</mapper>