<?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.dora.mapper.VideoViewStatMapper">

    <select id="countViewsByOwnerId" resultType="java.lang.Integer">
        SELECT COUNT(*) FROM video_view_stat 
        WHERE owner_id = #{ownerId} AND is_deleted = 0
    </select>

    <select id="countViewsByVideoId" resultType="java.lang.Integer">
        SELECT COUNT(*) FROM video_view_stat 
        WHERE video_id = #{videoId} AND is_deleted = 0
    </select>

    <!-- 统计今日视频观看次数 -->
    <select id="countTodayViews" resultType="long">
        SELECT COUNT(*) FROM video_view_stat 
        WHERE DATE(view_time) = DATE(#{today}) AND is_deleted = 0
    </select>

    <!-- 插入观看记录 -->
    <insert id="insertViewRecord" parameterType="map" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO video_view_stat (video_id, owner_id, view_user_id, view_time, view_duration, is_deleted)
        VALUES (#{videoId}, #{ownerId}, #{viewUserId}, NOW(), #{viewDuration}, 0)
    </insert>

    <!-- 更新视频播放次数 -->
    <update id="updateVideoViewCount" parameterType="long">
        UPDATE video 
        SET view_count = view_count + 1, update_time = NOW()
        WHERE id = #{videoId} AND is_deleted = 0
    </update>

    <!-- 检查用户是否已观看过该视频 -->
    <select id="checkUserViewedVideo" resultType="java.lang.Integer">
        SELECT COUNT(*) FROM video_view_stat 
        WHERE video_id = #{videoId} AND view_user_id = #{userId} AND is_deleted = 0
    </select>

    <!-- 更新已有观看记录的观看时间 -->
    <update id="updateViewTime">
        UPDATE video_view_stat 
        SET view_time = NOW(), view_duration = 0
        WHERE video_id = #{videoId} AND view_user_id = #{userId} AND is_deleted = 0
        LIMIT 1
    </update>

</mapper> 