package com.dora.mapper;

import com.dora.entity.ToolUsageLog;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 工具调用记录Mapper
 */
@Mapper
public interface ToolUsageLogMapper {

    /**
     * 插入调用记录
     */
    @Insert("INSERT INTO tool_usage_log (usage_no, user_id, tool_id, tool_code, tool_name, points_cost, " +
            "request_params, status, response_data, error_message, request_duration, client_ip, create_time, is_deleted) " +
            "VALUES (#{usageNo}, #{userId}, #{toolId}, #{toolCode}, #{toolName}, #{pointsCost}, " +
            "#{requestParams}, #{status}, #{responseData}, #{errorMessage}, #{requestDuration}, #{clientIp}, NOW(), 0)")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(ToolUsageLog log);

    /**
     * 根据流水号查询
     */
    @Select("SELECT * FROM tool_usage_log WHERE usage_no = #{usageNo} AND is_deleted = 0")
    ToolUsageLog selectByUsageNo(@Param("usageNo") String usageNo);

    /**
     * 查询用户的调用记录（分页）
     */
    @Select("SELECT * FROM tool_usage_log WHERE user_id = #{userId} AND is_deleted = 0 " +
            "ORDER BY create_time DESC LIMIT #{offset}, #{limit}")
    List<ToolUsageLog> selectByUserId(@Param("userId") Long userId, 
                                       @Param("offset") int offset, 
                                       @Param("limit") int limit);

    /**
     * 统计用户的调用记录数
     */
    @Select("SELECT COUNT(*) FROM tool_usage_log WHERE user_id = #{userId} AND is_deleted = 0")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 按工具查询用户的调用记录
     */
    @Select("SELECT * FROM tool_usage_log WHERE user_id = #{userId} AND tool_code = #{toolCode} AND is_deleted = 0 " +
            "ORDER BY create_time DESC LIMIT #{offset}, #{limit}")
    List<ToolUsageLog> selectByUserIdAndToolCode(@Param("userId") Long userId,
                                                  @Param("toolCode") String toolCode,
                                                  @Param("offset") int offset,
                                                  @Param("limit") int limit);

    /**
     * 查询时间范围内的调用记录（用于统计）
     */
    @Select("SELECT * FROM tool_usage_log WHERE create_time >= #{startTime} AND create_time < #{endTime} AND is_deleted = 0")
    List<ToolUsageLog> selectByTimeRange(@Param("startTime") LocalDateTime startTime,
                                          @Param("endTime") LocalDateTime endTime);

    /**
     * 统计时间范围内的调用次数
     */
    @Select("SELECT COUNT(*) FROM tool_usage_log WHERE create_time >= #{startTime} AND create_time < #{endTime} AND is_deleted = 0")
    Long countByTimeRange(@Param("startTime") LocalDateTime startTime,
                          @Param("endTime") LocalDateTime endTime);

    /**
     * 统计时间范围内按工具分组的调用次数
     */
    @Select("SELECT tool_code, tool_name, COUNT(*) as total_calls, " +
            "SUM(CASE WHEN status = 'success' THEN 1 ELSE 0 END) as success_calls, " +
            "SUM(points_cost) as total_points_cost " +
            "FROM tool_usage_log " +
            "WHERE create_time >= #{startTime} AND create_time < #{endTime} AND is_deleted = 0 " +
            "GROUP BY tool_code, tool_name")
    @Results({
            @Result(property = "toolCode", column = "tool_code"),
            @Result(property = "toolName", column = "tool_name"),
            @Result(property = "totalCalls", column = "total_calls"),
            @Result(property = "successCalls", column = "success_calls"),
            @Result(property = "totalPointsCost", column = "total_points_cost")
    })
    List<ToolUsageStats> selectStatsByTimeRange(@Param("startTime") LocalDateTime startTime,
                                                 @Param("endTime") LocalDateTime endTime);

    /**
     * 统计时间范围内的独立用户数
     */
    @Select("SELECT COUNT(DISTINCT user_id) FROM tool_usage_log " +
            "WHERE create_time >= #{startTime} AND create_time < #{endTime} AND is_deleted = 0")
    Long countUniqueUsersByTimeRange(@Param("startTime") LocalDateTime startTime,
                                      @Param("endTime") LocalDateTime endTime);

    /**
     * 工具使用统计内部类
     */
    class ToolUsageStats {
        private String toolCode;
        private String toolName;
        private Long totalCalls;
        private Long successCalls;
        private Long totalPointsCost;

        public String getToolCode() { return toolCode; }
        public void setToolCode(String toolCode) { this.toolCode = toolCode; }
        public String getToolName() { return toolName; }
        public void setToolName(String toolName) { this.toolName = toolName; }
        public Long getTotalCalls() { return totalCalls; }
        public void setTotalCalls(Long totalCalls) { this.totalCalls = totalCalls; }
        public Long getSuccessCalls() { return successCalls; }
        public void setSuccessCalls(Long successCalls) { this.successCalls = successCalls; }
        public Long getTotalPointsCost() { return totalPointsCost; }
        public void setTotalPointsCost(Long totalPointsCost) { this.totalPointsCost = totalPointsCost; }
    }
}
