package com.erp.approval.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.approval.entity.OperationLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

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

/**
 * 操作日志Mapper
 */
@Mapper
public interface OperationLogRepository extends BaseMapper<OperationLog> {

    /**
     * 按模块统计
     */
    @Select("SELECT module, action, COUNT(*) as count FROM operation_logs " +
           "WHERE tenant_id = #{tenantId} AND created_at BETWEEN #{startDate} AND #{endDate} " +
           "GROUP BY module, action")
    List<Map<String, Object>> statsByModuleAndAction(@Param("tenantId") Long tenantId,
                                                      @Param("startDate") String startDate,
                                                      @Param("endDate") String endDate);

    /**
     * 按用户统计
     */
    @Select("SELECT user_name, COUNT(*) as count FROM operation_logs " +
           "WHERE tenant_id = #{tenantId} AND created_at BETWEEN #{startDate} AND #{endDate} " +
           "GROUP BY user_name ORDER BY count DESC LIMIT 10")
    List<Map<String, Object>> statsByUser(@Param("tenantId") Long tenantId,
                                          @Param("startDate") String startDate,
                                          @Param("endDate") String endDate);

    /**
     * 统计成功/失败数量
     */
    @Select("SELECT " +
           "SUM(CASE WHEN response_code < 400 THEN 1 ELSE 0 END) as success_count, " +
           "SUM(CASE WHEN response_code >= 400 THEN 1 ELSE 0 END) as error_count " +
           "FROM operation_logs WHERE tenant_id = #{tenantId} AND created_at BETWEEN #{startDate} AND #{endDate}")
    Map<String, Object> countSuccessAndError(@Param("tenantId") Long tenantId,
                                             @Param("startDate") String startDate,
                                             @Param("endDate") String endDate);
}
