<?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.czg.service.account.mapper.CallQueueMapper">

    <select id="selectCallRecord" resultType="com.czg.account.dto.calltable.CallRecordVO">
        select tb_call_queue.*, tb_call_table.note, TIMESTAMPDIFF(SECOND, tb_call_queue.create_time, NOW()) as since_at
        from tb_call_queue
        left join tb_call_table on tb_call_queue.call_table_id = tb_call_table.id
        ${qwSql}
        limit ${pageOffset}, ${pageSize}
    </select>
    <select id="selectCallRecord_COUNT" resultType="java.lang.Long">
        select count(1)
        from tb_call_queue
                 left join tb_call_table on tb_call_queue.call_table_id = tb_call_table.id
        ${qwSql}
    </select>
    <select id="selectInfoByOpenId" resultType="com.czg.account.vo.CallQueueInfoVO">
        SELECT
        d.shop_name,
        d.logo,
        d.status AS shop_state,
        a.call_num,
        a.id,  -- 用户的排队记录ID
        a.state,
        a.user_id,  -- 用户ID
        b.name AS table_name,  -- 桌子名称
        b.note AS table_note,  -- 桌子备注
        (
        SELECT COUNT(1)
        FROM tb_call_queue c
        WHERE
        c.call_table_id = a.call_table_id
        and c.shop_id=a.shop_id		-- 同一张桌子
        AND c.create_time &lt; a.create_time  -- 在当前用户之前排队
        AND c.state IN (0, 1)  -- 排队中或等待中的人
        AND c.create_day=#{today}
        ) AS waiting_count,  -- 前面有几个人
        (
        SELECT COUNT(1) * b.wait_time
        FROM tb_call_queue c
        WHERE
        c.call_table_id = a.call_table_id
        AND c.shop_id=a.shop_id			-- 同一张桌子
        AND c.create_time &lt; a.create_time  -- 在当前用户之前排队
        AND c.state IN (0, 1)  -- 排队中或等待中的人
        AND c.create_day=#{today}
        ) AS wait_time  -- 预计等待时间
        FROM
        tb_call_queue a
        LEFT JOIN
        tb_shop_info d ON a.shop_id = d.id
        LEFT JOIN
        tb_call_table b ON a.call_table_id = b.id
        WHERE
        a.shop_id = #{shopId}
        AND a.create_day = #{today}  -- 替换为目标日期

        <if test="queueId != null">
            and a.id = #{queueId} and (a.open_id = #{openId} or a.open_id is null)
        </if>

        <if test="queueId == null">
            and a.open_id = #{openId}  -- 替换为目标用户的 open_id
        </if>

        and a.state in (0, 1)
        GROUP BY
        a.id, a.user_id, b.name, b.note, b.wait_time
        ORDER BY
        a.create_time asc
    </select>
</mapper>
