<?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="cn.iocoder.yudao.module.system.dal.mysql.biz.CheckInApplyMapper">

    <select id="selectCheckInListPage" resultType="cn.iocoder.yudao.module.system.api.bpm.vo.CheckInRecordRespVO">
        SELECT
            ecir.*,
            ei.elder_name,
            ei.elder_sex,
            ei.in_status_type,
            ei.nurse_level_name,
            bbf.status AS bpmStatus,
            bbf.process_instance_id,
            bbf.type,
            st.name as tenantName
        FROM
        elderly_check_in_record ecir
        INNER JOIN elderly_info ei ON ecir.elder_id = ei.id
        LEFT JOIN system_tenant st ON st.id = ei.tenant_id
        LEFT JOIN bpm_business_form bbf ON ecir.id = bbf.business_id AND bbf.type = #{pageVO.type}
        WHERE ecir.current_flag = 0
        <if test="pageVO.elderName != null">
            AND ei.elder_name LIKE CONCAT('%', #{pageVO.elderName}, '%')
        </if>
        <if test="pageVO.bpmStatus != null">
            and bbf.`status` = #{pageVO.bpmStatus}
        </if>
        <if test="pageVO.status != null">
            and ecir.`status` = #{pageVO.status}
        </if>
        <if test="pageVO.inStatusType != null">
            and ei.`in_status_type` = #{pageVO.inStatusType}
        </if>
        <if test="pageVO.tenantIds != null">
            and ei.tenant_id in
            <foreach item="id" collection="pageVO.tenantIds" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
        ORDER BY ecir.created_time DESC
    </select>


    <select id="selectLastCheckInApplyByElderIds" resultType="cn.iocoder.yudao.module.system.dal.dataobject.biz.CheckInApplyDO">
        SELECT t.*
        FROM check_in_apply t
        INNER JOIN (
            SELECT elderly_id, MAX(check_in_time) AS max_check_in_time
            FROM check_in_apply
            WHERE tenant_id = #{tenantId}
              AND check_in_time &lt;= #{monthEnd}
              AND (check_in_deadline_time IS NULL OR check_in_deadline_time &gt; #{monthEnd})
              AND elderly_id IN
              <foreach item="id" collection="elderIds" open="(" separator="," close=")">
                  #{id}
              </foreach>
            GROUP BY elderly_id
        ) x ON x.elderly_id = t.elderly_id AND x.max_check_in_time = t.check_in_time
        WHERE t.tenant_id = #{tenantId}
    </select>

</mapper>