package com.softwarebr.nunu.dao.train;

import com.softwarebr.nunu.entity.train.ActivityLog;
import com.brframework.commondb.core.CommonRepository;
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;

/**
 * @date 2020/03/11 15:30:46
 * @author lilin
 */

@Repository
public interface ActivityLogDao extends CommonRepository<Long, ActivityLog> {

    /**
     * 订单号查询入场码
     * @param orderNo
     * @return
     */
    ActivityLog findByOrderNo(String orderNo);

    /**
     * 更新报名信息入场码
     * @param orderNo 订单号
     * @param voucherCode 入场码
     * @param failureStatus 入场码有效状态
     */
    @Modifying
    @Query("update ActivityLog set voucherCode = :voucherCode, failureStatus = :failureStatus where orderNo = :orderNo")
    void updateVoucherCode(@Param("orderNo") String orderNo, @Param("voucherCode") String voucherCode, @Param("failureStatus") Integer failureStatus);

    /**
     * 更新入场码状态
     * @param orderNo 订单号
     * @param failureStatus 入场码有效状态
     */
    @Modifying
    @Query("update ActivityLog set failureStatus = :failureStatus where orderNo = :orderNo")
    void updateFailureStatus(@Param("orderNo") String orderNo, @Param("failureStatus") Integer failureStatus);


    /**
     * 更新报名人数
     * @param orderNo 订单号
     * @param enrolment 报名人数
     */
    @Modifying
    @Query("update ActivityLog set enrolment = :enrolment where orderNo = :orderNo")
    void updateEnrolment(@Param("orderNo") String orderNo, @Param("enrolment") Integer enrolment);


    /**
     * 根据活动ID查询报名信息
     * @param activityId 活动ID
     * @param failureStatus 入场码有效状态
     * @return
     */
    List<ActivityLog> findByActivityIdAndFailureStatus(Long activityId, Integer failureStatus);


    /**
     * 活动时间区间与活动类型统计报名数据
     * @param type 活动类型
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return
     */
    @Query(value = "SELECT COUNT(*) FROM train_activity_log WHERE activity_id IN (SELECT id FROM train_activity WHERE TYPE = :type " +
            "AND category = :category AND start_date >= :startDate AND end_date <= :endDate)", nativeQuery = true)
    Long countActivityLogByType(@Param("type") Integer type, @Param("category") Integer category ,
                                @Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate);


}