<?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.common.mapper.CommonAppMapper">
    <resultMap id="PrescriptionPrintInfoMap" type="com.openhis.web.common.dto.AdvicePrintInfoDto">
        <id property="departmentName" column="department_name"/>
        <result property="patientName" column="patient_name"/>
        <result property="phone" column="phone"/>
        <result property="encounterNo" column="encounter_no"/>
        <result property="genderEnum" column="gender_enum"/>
        <result property="age" column="age"/>
        <result property="birthDate" column="birth_date"/>
        <result property="reqTime" column="req_time"/>
        <result property="contractName" column="contract_name"/>
        <result property="conditionName" column="condition_name"/>
        <result property="doctorName" column="doctor_name"/>
        <result property="dispenseDoctorName" column="dispense_doctor_name"/>
        <result property="preparerDoctorName" column="preparer_doctor_name"/>
        <result property="chargeDoctorName" column="charge_doctor_name"/>
        <result property="encounterYbClass" column="encounter_yb_class"/>
        <collection property="adviceItemList" ofType="com.openhis.web.common.dto.AdviceItemPrintInfoDto">
            <result property="quantity" column="quantity"/>
            <result property="unitPrice" column="unit_price"/>
            <result property="totalPrice" column="total_price"/>
            <result property="itemName" column="item_name"/>
            <result property="totalVolume" column="total_volume"/>
            <result property="dose" column="dose"/>
            <result property="rateCode" column="rate_code"/>
            <result property="methodCode" column="method_code"/>
            <result property="doseUnitCode" column="dose_unit_code"/>
            <result property="unitCode" column="unit_code"/>
            <result property="prescriptionNo" column="prescription_no"/>
            <result property="groupId" column="group_id"/>
            <result property="sortNumber" column="sort_number"/>
        </collection>
    </resultMap>
    <resultMap id="TreatmentPrintInfoMap" type="com.openhis.web.common.dto.AdvicePrintInfoDto">
        <id property="departmentName" column="department_name"/>
        <result property="patientName" column="patient_name"/>
        <result property="phone" column="phone"/>
        <result property="encounterNo" column="encounter_no"/>
        <result property="genderEnum" column="gender_enum"/>
        <result property="age" column="age"/>
        <result property="birthDate" column="birth_date"/>
        <result property="reqTime" column="req_time"/>
        <result property="contractName" column="contract_name"/>
        <result property="doctorName" column="doctor_name"/>
        <result property="encounterYbClass" column="encounter_yb_class"/>
        <collection property="adviceItemList" ofType="com.openhis.web.common.dto.AdviceItemPrintInfoDto">
            <result property="quantity" column="quantity"/>
            <result property="unitPrice" column="unit_price"/>
            <result property="totalPrice" column="total_price"/>
            <result property="itemName" column="item_name"/>
            <result property="unitCode" column="unit_code"/>
        </collection>
    </resultMap>
    <select id="selectInventoryItemList" resultType="com.openhis.web.common.dto.InventoryItemDto">
        SELECT ii.tenant_id,
        ii.item_type,
        ii.category_code,
        ii.part_percent,
        ii.definition_id,
        ii.name,
        ii.item_bus_no,
        ii.py_str,
        ii.wb_str,
        ii.yb_no,
        ii.product_name,
        ii.unit_code,
        ii.min_unit_code,
        ii.manufacturer,
        ii.volume,
        ii.supplier,
        ii.item_table_name,
        ii.lot_number,
        ii.org_location_id,
        ii.purchase_amount
        FROM ( SELECT T1.tenant_id,
        #{medicine} AS item_type,
        T1.category_code AS category_code,
        T1.part_percent AS part_percent,
        T1.id AS definition_id,
        T1."name" AS "name",
        T1.bus_no AS item_bus_no,
        T1.py_str AS py_str,
        T1.wb_str AS wb_str,
        T1.yb_no AS yb_no,
        T1.merchandise_name AS product_name,
        T1.unit_code AS unit_code,
        T1.min_unit_code AS min_unit_code,
        T1.manufacturer_text AS manufacturer,
        T2.total_volume AS volume,
        T3."name" AS supplier,
        <choose>
            <when test="purchaseFlag != 1">
                T7.item_table AS item_table_name,
                T7.lot_number,
                T7.location_id AS org_location_id,
                NULL AS purchase_amount
            </when>
            <otherwise>
                NULL AS item_table_name,
                NULL AS lot_number,
                NULL AS org_location_id,
                T9.amount AS purchase_amount
            </otherwise>
        </choose>
        FROM med_medication_definition AS T1
        LEFT JOIN med_medication AS T2
        ON T2.medication_def_id = T1.ID
        AND T2.delete_flag = '0'
        LEFT JOIN adm_supplier AS T3
        ON T3.ID = T1.supply_id
        AND T3.delete_flag = '0'
        <if test="purchaseFlag != 1">
            LEFT JOIN wor_inventory_item AS T7
            ON T7.item_id = T1.id
            AND T7.delete_flag = '0'
        </if>
        <if test="purchaseFlag != 0">
            LEFT JOIN adm_charge_item_definition AS T8
            ON T8.instance_id = T1.id
            AND T8.delete_flag = '0'
            LEFT JOIN adm_charge_item_def_detail AS T9
            ON T9.definition_id = T8.id
            AND T9.delete_flag = '0'
        </if>
        WHERE T1.delete_flag = '0'
        AND T2.status_enum != #{retired}
        <if test="purchaseFlag != 1">
            AND T7.item_id IS NOT NULL -- 确保连接有效性
            AND T7.item_table = #{medicationTableName}
        </if>
        <if test="purchaseFlag != 0">
            AND T9.condition_code = #{purchase}
        </if>
        UNION ALL
        SELECT T1.tenant_id,
        #{device} AS item_type,
        T1.category_code AS category_code,
        T1.part_percent AS part_percent,
        T1.id AS definition_id,
        T1."name" AS "name",
        T1.bus_no AS item_bus_no,
        T1.py_str AS py_str,
        T1.wb_str AS wb_str,
        T1.yb_no AS yb_no,
        '' AS product_name,
        T1.unit_code AS unit_code,
        T1.min_unit_code AS min_unit_code,
        T1.manufacturer_text AS manufacturer,
        T1."size" AS volume,
        T2."name" AS supplier,
        <choose>
            <when test="purchaseFlag != 1">
                T7.item_table AS item_table_name,
                T7.lot_number,
                T7.location_id AS org_location_id,
                NULL AS purchase_amount
            </when>
            <otherwise>
                NULL AS item_table_name,
                NULL AS lot_number,
                NULL AS org_location_id,
                T9.amount AS purchase_amount
            </otherwise>
        </choose>
        FROM adm_device_definition AS T1
        LEFT JOIN adm_supplier AS T2
        ON T2.ID = T1.supply_id
        AND T2.delete_flag = '0'
        <if test="purchaseFlag != 1">
            LEFT JOIN wor_inventory_item AS T7
            ON T7.item_id = T1.id
            AND T7.delete_flag = '0'
        </if>
        <if test="purchaseFlag != 0">
            LEFT JOIN adm_charge_item_definition AS T8
            ON T8.instance_id = T1.id
            AND T8.delete_flag = '0'
            LEFT JOIN adm_charge_item_def_detail AS T9
            ON T9.definition_id = T8.id
            AND T9.delete_flag = '0'
        </if>
        WHERE T1.delete_flag = '0'
        AND T1.status_enum != #{retired}
        <if test="purchaseFlag != 1">
            AND T7.item_id IS NOT NULL -- 确保连接有效性
            AND T7.item_table = #{deviceTableName}
        </if>
        <if test="purchaseFlag != 0">
            AND T9.condition_code = #{purchase}
        </if>
        ) AS ii
        ${ew.customSqlSegment}
    </select>
    <select id="selectInventoryItemInfo" resultType="com.openhis.web.common.dto.LocationInventoryDto">
        SELECT T1.item_id,
        T1.item_table,
        T1.location_id,
        SUM(CASE WHEN T1.location_id = #{objLocationId} THEN T1.quantity ELSE 0 END) AS obj_quantity,
        SUM(CASE WHEN T1.location_id = #{orgLocationId} THEN T1.quantity ELSE 0 END) AS org_quantity,
        T1.unit_code,
        T1.production_date,
        T1.lot_number,
        T1.expiration_date,
        MAX(T2."name") AS location_name,
        MAX(T3."name") AS location_store_name,
        T5.amount AS price,
        T1.supplier_id,
        CASE WHEN T1.item_table = #{medicationTableName}
        THEN ( SELECT T7.yb_no
        FROM med_medication_definition AS T7
        WHERE T1.item_id = T7.id
        AND T7.delete_flag = '0')
        WHEN T1.item_table = #{deviceTableName}
        THEN ( SELECT T8.yb_no
        FROM adm_device_definition AS T8
        WHERE T1.item_id = T8.id
        AND T8.delete_flag = '0'
        ) ELSE null END AS yb_no, --医保编码
        CASE WHEN T1.item_table = #{medicationTableName}
        THEN ( SELECT T7.manufacturer_text
        FROM med_medication_definition AS T7
        WHERE T1.item_id = T7.id
        AND T7.delete_flag = '0')
        WHEN T1.item_table = #{deviceTableName}
        THEN ( SELECT T8.manufacturer_text
        FROM adm_device_definition AS T8
        WHERE T1.item_id = T8.id
        AND T8.delete_flag = '0')
        ELSE null END AS manufacturer,--生产厂家
        T6.name AS supplier_name
        FROM wor_inventory_item AS T1
        LEFT JOIN adm_location AS T2
        ON T2.id = T1.location_id
        AND T2.delete_flag = '0'
        LEFT JOIN adm_location AS T3
        ON T3.id = T1.location_store_id
        AND T3.delete_flag = '0'
        LEFT JOIN adm_charge_item_definition AS T4
        ON T4.instance_id = T1.item_id
        AND T4.delete_flag = '0'
        -- 使用子查询确保T5唯一记录 --
        LEFT JOIN (
        SELECT * FROM (
        SELECT definition_id,
        amount,
        ROW_NUMBER() OVER (PARTITION BY definition_id ORDER BY id DESC ) AS rn -- 按ID取最新记录，按需调整排序
        FROM adm_charge_item_def_detail
        WHERE delete_flag = '0'
        AND condition_code = '1'--1:批号进价
        ) AS t
        WHERE rn = 1 -- 确保每个分组只取一条记录
        ) AS T5 ON T5.definition_id = T4.id
        LEFT JOIN adm_supplier AS T6
        ON T6.id = T1.supplier_id
        AND T6.delete_flag = '0'
        WHERE T1.item_id = #{itemId}
        AND T1.inventory_status_enum != 3
        AND T1.delete_flag = '0'
        <choose>
            <when test="lotNumber != null">
                AND T1.lot_number = #{lotNumber}
            </when>
        </choose>
        <choose>
            <when test="objLocationId != null and objLocationId != ''">
                AND T1.location_id IN (#{orgLocationId}, #{objLocationId})
            </when>
            <otherwise>
                AND T1.location_id = #{orgLocationId}
            </otherwise>
        </choose>
        GROUP BY T1.item_id,
        T1.item_table,
        T1.location_id,
        T1.unit_code,
        T1.production_date,
        T1.expiration_date,
        T1.lot_number,
        T5.amount,
        T1.supplier_id,
        T6.name
        ORDER BY T1.lot_number DESC
    </select>

    <select id="getInfoByTraceNo" resultType="com.openhis.administration.domain.TraceNoManage">
        SELECT id,
               item_table,
               item_id,
               location_type_enum,
               location_id,
               location_store_id,
               lot_number,
               trace_no,
               status_enum,
               unit_code,
               operation_type,
               create_by,
               create_time,
               update_by,
               update_time,
               tenant_id,
               delete_flag
        FROM adm_trace_no_manage
        WHERE trace_no like #{traceNo}
          AND (trace_no) IN (
            SELECT trace_no
            FROM adm_trace_no_manage
            WHERE trace_no like #{traceNo}
              AND delete_flag = '0'
            GROUP BY trace_no
            HAVING SUM(CASE WHEN status_enum = 1 THEN 1 ELSE 0 END) > -- 进库次数
                   SUM(CASE WHEN status_enum = 2 THEN 1 ELSE 0 END) -- 出库次数
        )
          AND delete_flag = '0'
        ORDER BY create_time DESC LIMIT 1
    </select>

    <select id="getPractitionerList" resultType="com.openhis.web.common.dto.PractitionerInfoDto">
        SELECT ap.ID AS practitioner_id,
        ap.NAME AS practitioner_name,
        ao.NAME AS organization_name
        FROM adm_practitioner AS ap
        LEFT JOIN adm_organization AS ao ON ap.org_id = ao.ID
        AND ao.delete_flag = '0'
        WHERE ap.delete_flag = '0'
        <if test="searchKey != null and searchKey != ''">
            AND (ap.py_str LIKE concat('%', #{searchKey}, '%') OR ap.NAME LIKE concat('%', #{searchKey}, '%'))
        </if>
    </select>

    <select id="selectPrescriptionPrintInfo" resultMap="PrescriptionPrintInfoMap">
        SELECT ae.yb_class_enum AS encounter_yb_class,
               mmr.prescription_no ,
               fc.contract_name ,
               ap."name" AS patient_name,
               ap.gender_enum ,
               ap.birth_date ,
               ae.bus_no AS encounter_no,
               ao."name" AS department_name,
               ccd."name" AS condition_name,
               ap.phone ,
               mmr.req_authored_time AS req_time,
               ap2."name" AS doctor_name,
               ap3."name" AS dispense_doctor_name,
               ap4."name" AS charge_doctor_name,
               ap5."name" AS preparer_doctor_name,
               mmd2."name" AS item_name,
               mm.total_volume ,
               mmr.dose ,
               mmr.method_code ,
               aci.unit_price ,
               aci.total_price ,
               mmr.quantity,
               mmr.rate_code ,
               mmr.unit_code ,
               mmr.dose_unit_code,
               mmr.sort_number,
               mmr.group_id
        FROM med_medication_request mmr
            LEFT JOIN med_medication_dispense mmd
                ON mmd.med_req_id = mmr.id
                    AND mmd.delete_flag = '0'
            LEFT JOIN med_medication_definition mmd2
                ON mmr.medication_id = mmd2.id
                    AND mmd2.delete_flag = '0'
            LEFT JOIN med_medication mm
                ON mmd2.id = mm.medication_def_id
                    AND mm.delete_flag = '0'
            LEFT JOIN adm_charge_item aci
                ON aci.service_id = mmr.id
                    AND aci.delete_flag = '0'
            LEFT JOIN cli_condition AS cc
                ON mmr.condition_id = cc.id
                    AND cc.delete_flag = '0'
            LEFT JOIN cli_condition_definition AS ccd
                ON cc.definition_id = ccd.id
                    AND ccd.delete_flag = '0'
            LEFT JOIN adm_encounter ae
                ON mmr.encounter_id = ae.id
                    AND ae.delete_flag = '0'
            LEFT JOIN adm_patient ap
                ON ae.patient_id = ap.id
                    AND ap.delete_flag = '0'
            LEFT JOIN adm_organization ao
                ON ao.id = ae.organization_id
                    AND ao.delete_flag = '0'
            LEFT JOIN adm_account aa
                ON ae.id = aa.encounter_id
                    AND aa.encounter_flag = 1
                    AND aa.delete_flag = '0'
            LEFT JOIN fin_contract fc
                ON aa.contract_no = fc.bus_no
                    AND fc.delete_flag = '0'
            LEFT JOIN adm_practitioner ap2
                ON ap2.id = mmr.practitioner_id
                    AND ap2.delete_flag = '0'
            LEFT JOIN adm_practitioner ap3
                ON ap3.id = mmd.practitioner_id
                    AND ap3.delete_flag = '0'
            LEFT JOIN adm_practitioner ap4
                ON ap4.id = aci.performer_id
                    AND ap4.delete_flag = '0'
            LEFT JOIN adm_practitioner ap5
                ON ap5.id = mmd.preparer_id
                    AND ap5.delete_flag = '0'
        WHERE mmr.delete_flag = '0'
            AND mmr.id IN
            <foreach collection="requestIds" item="requestId" separator="," open="(" close=")">
                #{requestId}
            </foreach>
    </select>
    <select id="selectTreatmentPrintInfo" resultMap="TreatmentPrintInfoMap">
        SELECT ae.yb_class_enum AS encounter_yb_class,
               fc.contract_name ,
               ap."name" AS patient_name,
               ap.gender_enum ,
               ap.birth_date ,
               ae.bus_no AS encounter_no,
               ao."name" AS department_name,
               ap.phone ,
               ae.reception_time  AS req_time,
               ap2."name" AS doctor_name,
               aci.unit_price ,
               aci.total_price,
               wdr.quantity ,
               wdr.unit_code ,
               add2."name" AS item_name
        FROM wor_device_request wdr
            LEFT JOIN adm_device_definition add2
                ON wdr.device_def_id  = add2.id
                    AND add2.delete_flag = '0'
            LEFT JOIN adm_charge_item aci
                ON aci.service_id = wdr.id
                    AND aci.delete_flag = '0'
            LEFT JOIN adm_encounter ae
                ON wdr.encounter_id = ae.id
                    AND ae.delete_flag = '0'
            LEFT JOIN adm_patient ap
                ON ae.patient_id = ap.id
                    AND ap.delete_flag = '0'
            LEFT JOIN adm_organization ao
                ON ao.id = ae.organization_id
                    AND ao.delete_flag = '0'
            LEFT JOIN adm_account aa
                ON ae.id = aa.encounter_id
                    AND aa.encounter_flag = 1
                    AND aa.delete_flag = '0'
            LEFT JOIN fin_contract fc
                ON aa.contract_no = fc.bus_no
                    AND fc.delete_flag = '0'
            LEFT JOIN adm_practitioner ap2
                ON ap2.id = wdr.requester_id
                    AND ap2.delete_flag = '0'
        WHERE wdr.delete_flag = '0'
            AND wdr.id IN
            <foreach collection="requestIds" item="requestId" separator="," open="(" close=")">
                #{requestId}
            </foreach>
        UNION
        SELECT ae.yb_class_enum AS encounter_yb_class,
               fc.contract_name ,
               ap."name" AS patient_name,
               ap.gender_enum ,
               ap.birth_date ,
               ae.bus_no AS encounter_no,
               ao."name" AS department_name,
               ap.phone ,
               ae.reception_time  AS req_time,
               ap2."name" AS doctor_name,
               aci.unit_price ,
               aci.total_price,
               wsr.quantity ,
               wsr.unit_code ,
               wad."name" AS item_name
        FROM wor_service_request wsr
            LEFT JOIN wor_activity_definition wad
                ON wsr.activity_id  = wad.id
                    AND wad.delete_flag = '0'
            LEFT JOIN adm_charge_item aci
                ON aci.service_id = wsr.id
                    AND aci.delete_flag = '0'
            LEFT JOIN adm_encounter ae
                ON wsr.encounter_id = ae.id
                    AND ae.delete_flag = '0'
            LEFT JOIN adm_patient ap
                ON ae.patient_id = ap.id
                    AND ap.delete_flag = '0'
            LEFT JOIN adm_organization ao
                ON ao.id = ae.organization_id
                    AND ao.delete_flag = '0'
            LEFT JOIN adm_account aa
                ON ae.id = aa.encounter_id
                    AND aa.encounter_flag = 1
                    AND aa.delete_flag = '0'
            LEFT JOIN fin_contract fc
                ON aa.contract_no = fc.bus_no
                    AND fc.delete_flag = '0'
            LEFT JOIN adm_practitioner ap2
                ON ap2.id = wsr.requester_id
                    AND ap2.delete_flag = '0'
        WHERE wsr.delete_flag = '0'
            AND wsr.id IN
            <foreach collection="requestIds" item="requestId" separator="," open="(" close=")">
                #{requestId}
            </foreach>
    </select>

</mapper>
