package shop.alien.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import shop.alien.entity.store.StoreTrackEvent;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 埋点事件Mapper接口
 *
 * @author system
 * @since 2026-01-14
 */
@Mapper
public interface StoreTrackEventMapper extends BaseMapper<StoreTrackEvent> {
    
    /**
     * 统计访客数（去重userId）
     */
    @Select("SELECT COUNT(DISTINCT user_id) as visitorCount " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'TRAFFIC' " +
            "AND user_id IS NOT NULL")
    Long countDistinctVisitors(@Param("storeId") Integer storeId,
                               @Param("endDate") Date endDate);
    
    /**
     * 统计新增访客数（统计时间段内首次访问的用户）
     */
    @Select("SELECT COUNT(DISTINCT t1.user_id) as newVisitorCount " +
            "FROM store_track_event t1 " +
            "WHERE t1.store_id = #{storeId} " +
            "AND t1.event_time >= #{startDate} " +
            "AND t1.event_time < #{endDate} " +
            "AND t1.delete_flag = 0 " +
            "AND t1.event_category = 'TRAFFIC' " +
            "AND t1.user_id IS NOT NULL " +
            "AND NOT EXISTS (" +
            "    SELECT 1 FROM store_track_event t2 " +
            "    WHERE t2.store_id = #{storeId} " +
            "    AND t2.user_id = t1.user_id " +
            "    AND t2.event_time < #{startDate} " +
            "    AND t2.delete_flag = 0" +
            ")")
    Long countNewVisitors(@Param("storeId") Integer storeId,
                          @Param("startDate") Date startDate,
                          @Param("endDate") Date endDate);
    
    /**
     * 统计流量数据：搜索量、浏览量、访问时长
     */
    @Select("SELECT " +
            "    SUM(CASE WHEN event_type = 'SEARCH' THEN 1 ELSE 0 END) as searchCount, " +
            "    SUM(CASE WHEN event_type = 'VIEW' THEN 1 ELSE 0 END) as viewCount, " +
            "    COALESCE(SUM(CASE WHEN event_type = 'VIEW' AND duration IS NOT NULL THEN duration ELSE 0 END), 0) as totalDuration, " +
            "    COALESCE(AVG(CASE WHEN event_type = 'VIEW' AND duration IS NOT NULL THEN duration END), 0) as avgDuration " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'TRAFFIC'")
    Map<String, Object> calculateTrafficStatistics(@Param("storeId") Integer storeId,
                                                    @Param("endDate") Date endDate);
    
    /**
     * 按价目表ID统计浏览量、访客数、分享数
     */
    @Select("SELECT " +
            "    target_id as priceId, " +
            "    SUM(CASE WHEN event_type = 'PRICE_VIEW' THEN 1 ELSE 0 END) as viewCount, " +
            "    COUNT(DISTINCT CASE WHEN user_id IS NOT NULL THEN user_id END) as visitorCount, " +
            "    SUM(CASE WHEN event_type = 'PRICE_SHARE' THEN 1 ELSE 0 END) as shareCount " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'PRICE' " +
            "AND target_id IS NOT NULL " +
            "GROUP BY target_id " +
            "ORDER BY viewCount DESC")
    List<Map<String, Object>> calculatePriceRanking(@Param("storeId") Integer storeId,
                                                     @Param("endDate") Date endDate);
    
    /**
     * 统计互动数据（按事件类型统计数量）
     * 从埋点事件表store_track_event中统计互动相关事件
     */
    @Select("SELECT " +
            "    event_type, " +
            "    COUNT(*) as count " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND store_id IS NOT NULL " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'INTERACTION' " +
            "GROUP BY event_type")
    List<Map<String, Object>> calculateInteractionStatistics(@Param("storeId") Integer storeId,
                                                              @Param("endDate") Date endDate);
    
    /**
     * 统计代金券数据（按事件类型统计数量和金额）
     */
    @Select("SELECT " +
            "    event_type, " +
            "    COUNT(*) as count, " +
            "    COALESCE(SUM(amount), 0) as totalAmount " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'VOUCHER' " +
            "AND event_type IN ('VOUCHER_GIVE', 'VOUCHER_USE') " +
            "GROUP BY event_type")
    List<Map<String, Object>> calculateVoucherStatistics(@Param("storeId") Integer storeId,
                                                          @Param("endDate") Date endDate);
    
    /**
     * 统计服务质量数据（按事件类型统计数量）
     */
    @Select("SELECT " +
            "    event_type, " +
            "    COUNT(*) as count " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND event_time < #{endDate} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'SERVICE' " +
            "GROUP BY event_type")
    List<Map<String, Object>> calculateServiceStatistics(@Param("storeId") Integer storeId,
                                                          @Param("endDate") Date endDate);
    
    /**
     * 统计店铺当前总浏览量（所有历史数据）
     */
    @Select("SELECT COUNT(*) as viewCount " +
            "FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'TRAFFIC' " +
            "AND event_type = 'VIEW'")
    Long countStoreViewCount(@Param("storeId") Integer storeId);

    /**
     * 区间内店铺访问（浏览）次数，口径与 {@link #countStoreViewCount} 一致：TRAFFIC + VIEW
     *
     * @param startInclusive 含
     * @param endInclusive   含
     */
    @Select("SELECT COUNT(*) FROM store_track_event " +
            "WHERE store_id = #{storeId} " +
            "AND delete_flag = 0 " +
            "AND event_category = 'TRAFFIC' " +
            "AND event_type = 'VIEW' " +
            "AND event_time >= #{startInclusive} " +
            "AND event_time <= #{endInclusive}")
    Long countStoreViewCountBetweenInclusive(@Param("storeId") Integer storeId,
                                             @Param("startInclusive") Date startInclusive,
                                             @Param("endInclusive") Date endInclusive);
}