<?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.regdoctorstation.mapper.SpecialAdviceAppMapper">

    <select id="getNursingOrdersInfos" resultType="com.openhis.web.regdoctorstation.dto.NursingOrdersDetailDto">
        SELECT
        wad.ID AS definition_id,
        wad.category_code AS category_code,
        wad.category_code AS category_enum,
        wad.NAME AS nursing_order_name
        FROM
        wor_activity_definition AS wad
        WHERE
        wad.delete_flag = '0'
        <if test="categoryCodeList != null and !categoryCodeList.isEmpty()">
            AND wad.category_code IN
            <foreach collection="categoryCodeList" item="itemId" open="(" separator="," close=")">
                #{itemId}
            </foreach>
        </if>
    </select>

    <select id="getEncounterNursingOrdersInfos"
            resultType="com.openhis.web.regdoctorstation.dto.NursingOrdersEncounterDetailDto">
        SELECT wsr.activity_id AS definition_id,
        wsr.category_enum AS category_enum
        FROM wor_service_request AS wsr
        INNER JOIN (
        SELECT category_enum,
        MAX(create_time) AS max_create_time
        FROM wor_service_request
        WHERE delete_flag = '0'
        AND encounter_id = #{encounterId}
        AND (status_enum = #{draft} OR status_enum = #{active} OR status_enum = #{completed})
        <if test="categoryEnumList != null and !categoryEnumList.isEmpty()">
            AND category_enum IN
            <foreach collection="categoryEnumList" item="itemId" open="(" separator="," close=")">
                #{itemId}
            </foreach>
        </if>
        GROUP BY category_enum
        ) AS latest ON wsr.category_enum = latest.category_enum
        AND wsr.create_time = latest.max_create_time
        WHERE wsr.delete_flag = '0'
        AND wsr.encounter_id = #{encounterId}
        AND (wsr.status_enum = #{draft} OR wsr.status_enum = #{active} OR wsr.status_enum = #{completed})
        <if test="categoryEnumList != null and !categoryEnumList.isEmpty()">
            AND wsr.category_enum IN
            <foreach collection="categoryEnumList" item="itemId" open="(" separator="," close=")">
                #{itemId}
            </foreach>
        </if>
    </select>

</mapper>