package com.erp.task.repository;

import com.erp.task.entity.ScheduledTask;
import com.erp.task.enums.TaskStatus;
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.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 ScheduledTaskRepository extends JpaRepository<ScheduledTask, Long> {

    /**
     * 根据任务名称查询
     */
    Optional<ScheduledTask> findByTaskNameAndTaskGroup(String taskName, String taskGroup);

    /**
     * 根据任务分组查询
     */
    List<ScheduledTask> findByTaskGroup(String taskGroup);

    /**
     * 根据状态查询
     */
    List<ScheduledTask> findByStatus(TaskStatus status);

    /**
     * 根据状态和任务分组查询
     */
    List<ScheduledTask> findByStatusAndTaskGroup(TaskStatus status, String taskGroup);

    /**
     * 分页查询
     */
    @Query("SELECT t FROM ScheduledTask t WHERE t.status != 'DELETED' " +
           "AND (:taskName IS NULL OR t.taskName LIKE %:taskName%) " +
           "AND (:taskGroup IS NULL OR t.taskGroup = :taskGroup) " +
           "AND (:status IS NULL OR t.status = :status) " +
           "AND (:taskType IS NULL OR t.taskType = :taskType) " +
           "AND (:owner IS NULL OR t.owner = :owner)")
    Page<ScheduledTask> findByConditions(
            @Param("taskName") String taskName,
            @Param("taskGroup") String taskGroup,
            @Param("status") TaskStatus status,
            @Param("taskType") String taskType,
            @Param("owner") String owner,
            Pageable pageable);

    /**
     * 查询所有运行中的任务
     */
    @Query("SELECT t FROM ScheduledTask t WHERE t.status = 'RUNNING'")
    List<ScheduledTask> findAllRunning();

    /**
     * 更新任务状态
     */
    @Modifying
    @Query("UPDATE ScheduledTask t SET t.status = :status, t.updatedAt = :now WHERE t.id = :id")
    int updateStatus(@Param("id") Long id, @Param("status") TaskStatus status, @Param("now") LocalDateTime now);

    /**
     * 更新下次执行时间
     */
    @Modifying
    @Query("UPDATE ScheduledTask t SET t.nextFireTime = :nextFireTime WHERE t.id = :id")
    int updateNextFireTime(@Param("id") Long id, @Param("nextFireTime") LocalDateTime nextFireTime);

    /**
     * 增加执行次数
     */
    @Modifying
    @Query("UPDATE ScheduledTask t SET t.executeCount = t.executeCount + 1, t.prevFireTime = :prevFireTime WHERE t.id = :id")
    int incrementExecuteCount(@Param("id") Long id, @Param("prevFireTime") LocalDateTime prevFireTime);

    /**
     * 查询需要重试的任务
     */
    @Query("SELECT t FROM ScheduledTask t WHERE t.status = 'RUNNING' AND t.maxRetries > 0")
    List<ScheduledTask> findRetryableTasks();

    /**
     * 统计各状态任务数
     */
    @Query("SELECT t.status, COUNT(t) FROM ScheduledTask t WHERE t.status != 'DELETED' GROUP BY t.status")
    List<Object[]> countByStatus();

    /**
     * 统计各分组任务数
     */
    @Query("SELECT t.taskGroup, COUNT(t) FROM ScheduledTask t WHERE t.status != 'DELETED' GROUP BY t.taskGroup")
    List<Object[]> countByGroup();

    /**
     * 检查任务名称是否存在
     */
    boolean existsByTaskNameAndTaskGroupAndIdNot(String taskName, String taskGroup, Long id);
}
