<?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.restaurant.DishesOrderStatisticsMapper">

    <!--
        一般情况下，尽可能使用 Mapper 进行 CRUD 增删改查即可。
        无法满足的场景，例如说多表关联查询，才使用 XML 编写 SQL。
        代码生成器暂时只生成 Mapper XML 文件本身，更多推荐 MybatisX 快速开发插件来生成查询。
        文档可见：https://www.iocoder.cn/MyBatis/x-plugins/
     -->

    <select id="getDishesOrderStatisticsPage"
            resultType="cn.iocoder.yudao.module.system.dal.dataobject.restaurant.DishesOrderStatisticsDO">
        select rdos.id,
        rdos.elder_id,
        rdos.elder_name,
        rdos.restaurant_id,
        rdos.month,
        rdos.count,
        rdos.total_amount,
        rdos.remarks,
        rdos.status,
        rdos.created_time,
        rdos.submitter_name,
        r.restaurant_name
        from restaurant_dishes_order_statistics_v2 rdos
        LEFT JOIN restaurant_management r ON rdos.restaurant_id = r.id
        left join elderly_info ei on ei.id = rdos.elder_id
        <where>
            <if test="params.elderName != null and params.elderName != ''">
                and ei.elder_name like concat('%',#{params.elderName} ,'%')
            </if>
            <if test="params.restaurantName != null and params.restaurantName != ''">
                and r.restaurant_name like concat('%',#{params.restaurantName} ,'%')
            </if>
            <if test="params.month != null and params.month != ''">
                and rdos.month = #{params.month}
            </if>
            <if test="params.tenantId != null">
                and rdos.tenant_id = #{params.tenantId}
            </if>
        </where>
        order by rdos.created_time desc
    </select>

    <select id="getDishesOrderExportList"
            parameterType="cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.DishesOrderStatisticsPageReqVO"
            resultType="cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.DishesOrderExportVO">
        SELECT
        o.id,
        r.restaurant_name as restaurantName,
        i.order_time as orderTime,
        e.elder_name as elderName,
        d.food_name as foodName,
        d.category_name as foodCategory,  <!-- 直接从restaurant_dishes表获取品类名称 -->
        i.count,
        i.amount as totalAmount,
        o.elder_id as elderId,           <!-- 用于后续查询床位号 -->
        i.food_id as foodId,         <!-- 用于关联菜品信息 -->
        o.submitter_name as submitterName,
        o.user_type userType,
        <!-- 直接在SQL中组装完整的床位号，避免N+1查询问题 -->
        <!-- 使用CONCAT_WS自动处理NULL值，格式：楼栋-楼层-房间-床位 -->
        CONCAT_WS('-', 
            NULLIF(TRIM(bd.build_name), ''), 
            NULLIF(TRIM(bf.floor_name), ''), 
            NULLIF(TRIM(br.room_name), ''), 
            NULLIF(TRIM(bb.bed_name), '')
        ) as bedNumber
        FROM restaurant_dishes_order_statistics_v2 o
        LEFT JOIN restaurant_management r ON o.restaurant_id = r.id
        LEFT JOIN restaurant_dishes_order_item_v2 i ON o.id = i.order_statistics_id
        LEFT JOIN elderly_info e ON o.elder_id = e.id
        LEFT JOIN restaurant_dishes d ON i.food_id = d.id  <!-- 关联菜品表获取品类 -->
        <!-- 关联床位相关表获取完整床位号 -->
        LEFT JOIN org_build_bed bb ON e.bed_id = bb.id
        LEFT JOIN org_build_room br ON bb.room_id = br.id
        LEFT JOIN org_build_floor bf ON br.floor_id = bf.id
        LEFT JOIN org_build bd ON bf.build_id = bd.id
        <where>
            <if test="restaurantName != null and restaurantName != ''">
                AND r.restaurant_name LIKE CONCAT('%', #{restaurantName}, '%')
            </if>
            <if test="month != null and month != ''" >
                AND o.month = #{month}
            </if>
            <if test="tenantId != null">
                AND o.tenant_id = #{tenantId}
            </if>
            <if test="elderName != null and elderName != ''">
                AND e.elder_name = #{elderName}
            </if>
            <if test="id != null">
                AND o.id = #{id}
            </if>
        </where>
        ORDER BY i.order_time DESC
    </select>
    <select id="getDishesOrderExportPage"
            resultType="cn.iocoder.yudao.module.system.controller.admin.restaurant.vo.DishesOrderExportVO">
        SELECT
        o.id,
        r.restaurant_name as restaurantName,
        i.order_time as orderTime,
        e.elder_name as elderName,
        d.food_name as foodName,
        d.category_name as foodCategory,
        i.count,
        i.amount as totalAmount,
        o.elder_id as elderId,
        i.food_id as foodId,
        o.submitter_name as submitterName,
        o.user_type userType,
        CONCAT_WS('-',
        NULLIF(TRIM(bd.build_name), ''),
        NULLIF(TRIM(bf.floor_name), ''),
        NULLIF(TRIM(br.room_name), ''),
        NULLIF(TRIM(bb.bed_name), '')
        ) as bedNumber
        FROM restaurant_dishes_order_statistics_v2 o
        LEFT JOIN restaurant_management r ON o.restaurant_id = r.id
        LEFT JOIN restaurant_dishes_order_item_v2 i ON o.id = i.order_statistics_id
        LEFT JOIN elderly_info e ON o.elder_id = e.id
        LEFT JOIN restaurant_dishes d ON i.food_id = d.id
        LEFT JOIN org_build_bed bb ON e.bed_id = bb.id
        LEFT JOIN org_build_room br ON bb.room_id = br.id
        LEFT JOIN org_build_floor bf ON br.floor_id = bf.id
        LEFT JOIN org_build bd ON bf.build_id = bd.id
        <where>
            <if test="params.restaurantName != null and params.restaurantName != ''">
                AND r.restaurant_name LIKE CONCAT('%', #{params.restaurantName}, '%')
            </if>
            <if test="params.month != null and params.month != ''" >
                AND o.month = #{params.month}
            </if>
            <if test="params.tenantId != null">
                AND o.tenant_id = #{params.tenantId}
            </if>
            <if test="params.elderName != null and params.elderName != ''">
                AND e.elder_name = #{params.elderName}
            </if>
            <if test="params.id != null">
                AND o.id = #{params.id}
            </if>
        </where>
        ORDER BY i.order_time DESC
    </select>
    <!-- 基础的主表ResultMap -->
    <resultMap id="baseMainResultMap" type="cn.iocoder.yudao.module.system.dal.dataobject.restaurant.EmployeeDishesOrderReportVO">
        <id property="id" column="id"/>
        <result property="employeeOpenId" column="employee_open_id"/>
        <result property="employeeName" column="employee_name"/>
        <result property="tenantId" column="tenant_id"/>
        <result property="mealDate" column="meal_date"/>
        <result property="remarks" column="remarks"/>
        <result property="status" column="status"/>
        <result property="createdTime" column="created_time"/>
    </resultMap>
    <select id="selectMainPage" resultMap="baseMainResultMap">
        SELECT DISTINCT rdorv2.*
        FROM restaurant_dishes_order_report_v2 rdorv2
        <where>
            <if test="params.id != null and params.id != ''">
                and rdorv2.id = #{params.id}
            </if>
            <if test="params.employeeOpenId != null and params.employeeOpenId != ''">
                and rdorv2.employee_open_id = #{params.employeeOpenId}
            </if>
            <if test="params.employeeName != null and params.employeeName != ''">
                and rdorv2.employee_name like concat('%',#{params.employeeName} ,'%')
            </if>
            <if test="params.tenantId != null and params.tenantId != ''">
                and rdorv2.tenant_id = #{params.tenantId}
            </if>
            <if test="params.mealDate != null">
                <!-- 根据你的mealDate类型调整 -->
                and rdorv2.meal_date = #{params.mealDate}
            </if>
            <if test="params.mealTimesList != null and params.mealTimesList.size() > 0">
                <!-- 如果查询条件涉及子表，使用EXISTS子查询 -->
                and EXISTS (
                SELECT 1 FROM restaurant_dishes_order_report_detail rdord
                WHERE rdord.order_id = rdorv2.id
                AND rdord.meal_name in
                <foreach item="mealName" collection="params.mealTimesList" open="(" separator="," close=")">
                    #{mealName}
                </foreach>
                )
            </if>
        </where>
        ORDER BY rdorv2.id DESC
    </select>
    <select id="selectDetailsByMainIds"
            resultType="cn.iocoder.yudao.module.system.dal.dataobject.restaurant.DishesOrderReportDetail">
        SELECT
        rdord.id,
        rdord.order_id as orderId,
        rdord.meal_name as mealName,
        rdord.meal_status as mealStatus,
        rdord.created_at as createdAt
        FROM restaurant_dishes_order_report_detail rdord
        WHERE rdord.order_id IN
        <foreach item="mainId" collection="mainIds" open="(" separator="," close=")">
            #{mainId}
        </foreach>
        <if test="params.mealTimesList != null and params.mealTimesList.size() > 0">
            AND rdord.meal_name in
            <foreach item="mealName" collection="params.mealTimesList" open="(" separator="," close=")">
                #{mealName}
            </foreach>
        </if>
        ORDER BY rdord.order_id, rdord.id
    </select>
</mapper>