package com.jsc.oscm.dao;

import com.jsc.oscm.entity.Log;
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.transaction.annotation.Transactional;

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

public interface LogRepository extends JpaRepository<Log, Integer> {
    List<Log> findByTaskIdInAndCreateTimeBetweenOrderByCreateTimeDesc(
            List<Integer> taskIdList, Date startDate, Date endDate, Pageable pageable);

    Long countAllByTaskIdInAndCreateTimeBetween(List<Integer> taskIdList, Date startDate, Date endDate);

    @Query(value =
            "SELECT DATE_FORMAT(create_time,'%Y-%m-%d'), COALESCE(SUM(items_count),0) as items_count " +
                    "FROM log WHERE create_time > ?1 and task_id in (?2) GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d')"
            , nativeQuery = true)
    List<Object[]> queryItemCountGroupByDate(Date createDate, List<String> taskIds);


    @Query(value =
            "SELECT task_id,COALESCE(SUM(items_count),0) as items_count FROM log " +
                    "WHERE create_time > ?1 and create_time < ?2 " +
                    "GROUP BY task_id order by items_count desc"
            , nativeQuery = true)
    List<Object[]> queryItemCountGroupByAllTask(Date createTime, Date endTime);

    Log findByJobId(String jobId);

    @Transactional
    @Modifying
    void deleteByCreateTimeBefore(Date date);

}
