package com.erp.task.repository;

import com.erp.task.entity.TaskExecutionLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

/**
 * 任务执行记录Repository
 */
@Repository
public interface TaskExecutionLogRepository extends JpaRepository<TaskExecutionLog, Long>, JpaSpecificationExecutor<TaskExecutionLog> {

    /**
     * 根据任务ID查询最近执行记录
     */
    Page<TaskExecutionLog> findByTaskIdOrderByTriggerTimeDesc(Long taskId, Pageable pageable);

    /**
     * 根据任务ID和状态查询
     */
    List<TaskExecutionLog> findByTaskIdAndStatus(Long taskId, String status);

    /**
     * 根据批次号查询
     */
    Optional<TaskExecutionLog> findByBatchNo(String batchNo);

    /**
     * 查询最近执行记录
     */
    Page<TaskExecutionLog> findAllByOrderByTriggerTimeDesc(Pageable pageable);

    /**
     * 根据时间范围查询
     */
    @Query("SELECT l FROM TaskExecutionLog l WHERE l.triggerTime BETWEEN :startTime AND :endTime ORDER BY l.triggerTime DESC")
    Page<TaskExecutionLog> findByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime, Pageable pageable);

    /**
     * 统计今日执行次数
     */
    @Query("SELECT COUNT(l) FROM TaskExecutionLog l WHERE l.triggerTime >= :today")
    Long countTodayExecutions(@Param("today") LocalDateTime today);

    /**
     * 统计今日成功次数
     */
    @Query("SELECT COUNT(l) FROM TaskExecutionLog l WHERE l.triggerTime >= :today AND l.status = 'SUCCESS'")
    Long countTodaySuccess(@Param("today") LocalDateTime today);

    /**
     * 统计今日失败次数
     */
    @Query("SELECT COUNT(l) FROM TaskExecutionLog l WHERE l.triggerTime >= :today AND l.status = 'FAILED'")
    Long countTodayFailed(@Param("today") LocalDateTime today);

    /**
     * 统计今日平均耗时
     */
    @Query("SELECT AVG(l.duration) FROM TaskExecutionLog l WHERE l.triggerTime >= :today AND l.duration IS NOT NULL")
    Long avgTodayDuration(@Param("today") LocalDateTime today);

    /**
     * 统计本周执行次数
     */
    @Query(value = "SELECT DATE(l.trigger_time) as date, COUNT(*) FROM task_execution_log l " +
                   "WHERE l.trigger_time >= :weekStart GROUP BY DATE(l.trigger_time) ORDER BY date", nativeQuery = true)
    List<Object[]> countWeeklyExecutions(@Param("weekStart") LocalDateTime weekStart);

    /**
     * 查询失败且未超过最大重试次数的记录
     */
    @Query("SELECT l FROM TaskExecutionLog l WHERE l.status = 'FAILED' AND l.retryCount < :maxRetries ORDER BY l.triggerTime ASC")
    List<TaskExecutionLog> findRetryableFailures(@Param("maxRetries") Integer maxRetries);

    /**
     * 根据执行状态统计
     */
    @Query("SELECT l.status, COUNT(l) FROM TaskExecutionLog l WHERE l.triggerTime >= :today GROUP BY l.status")
    List<Object[]> countByStatusToday(@Param("today") LocalDateTime today);

    /**
     * 删除旧记录
     */
    @Modifying
    @Query("DELETE FROM TaskExecutionLog l WHERE l.createdAt < :before")
    int deleteOldLogs(@Param("before") LocalDateTime before);
}
