<?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.haha.mapper.DoorRecordMapper">

    <resultMap id="DoorRecordResult" type="com.haha.entity.DoorRecord">
        <id property="id" column="id"/>
        <result property="activityId" column="activity_id"/>
        <result property="deviceId" column="device_id"/>
        <result property="userId" column="user_id"/>
        <result property="doorIndex" column="door_index"/>
        <result property="openType" column="open_type"/>
        <result property="doorStatus" column="door_status"/>
        <result property="nobuy" column="nobuy"/>
        <result property="orderId" column="order_id"/>
        <result property="openTime" column="open_time"/>
        <result property="closeTime" column="close_time"/>
        <result property="duration" column="duration"/>
        <result property="source" column="source"/>
        <result property="remark" column="remark"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
    </resultMap>

    <!-- 根据活动 ID 查询开门记录 -->
    <select id="getByActivityId" resultMap="DoorRecordResult">
        SELECT * 
        FROM t_door_record 
        WHERE activity_id = #{activityId}
        LIMIT 1
    </select>

    <!-- 根据用户 ID 查询最近的开门记录 -->
    <select id="getRecentRecords" resultMap="DoorRecordResult">
        SELECT * 
        FROM t_door_record 
        WHERE user_id = #{userId}
        AND device_id = #{deviceId}
        ORDER BY open_time DESC
        LIMIT #{limit}
    </select>

    <!-- 更新门状态 -->
    <update id="updateDoorStatus">
        UPDATE t_door_record 
        SET door_status = #{doorStatus},
            close_time = #{closeTime},
            duration = TIMESTAMPDIFF(SECOND, open_time, #{closeTime}),
            update_time = NOW()
        WHERE activity_id = #{activityId}
    </update>

    <!-- 关联订单 ID -->
    <update id="linkOrderId">
        UPDATE t_door_record 
        SET order_id = #{orderId},
            update_time = NOW()
        WHERE activity_id = #{activityId}
    </update>

    <!-- 标记无消费记录 -->
    <update id="markNoConsume">
        UPDATE t_door_record 
        SET nobuy = 1,
            remark = '用户开门但未消费',
            update_time = NOW()
        WHERE activity_id = #{activityId}
    </update>

</mapper>
