package com.reyun.repository;

import com.reyun.model.EventStats;
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.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * Created by sunhao on 17/4/10.
 */
@Transactional
public interface EventStatsRepository extends JpaRepository<EventStats, Long> {

    @Query(value = "select * from event_stats where app = ?1 and complicated_events = ?2 and valid is true order by ifnull(modify_time,create_time) desc", nativeQuery = true)
    List<EventStats> findAll(Long appId, Boolean complicatedEvents);

    @Query(value = "select * from event_stats where id = ?1 and valid is true ", nativeQuery = true)
    EventStats findEventStats(Long eventStatsId);

    @Query(value = "select * from event_stats where name = ?1 and app = ?2 and valid is true ", nativeQuery = true)
    EventStats findEventStatsByName(String eventStatsName, Long appId);

    @Query(value = "select count(*) from event_stats where name like  ?3% and create_account = ?1 and app = ?2 ", nativeQuery = true)
    BigInteger findCountLikeName(Long accountId, Long appId, String name);

    @Query(value = "select * from event_stats where create_account in (select id from account where root_parent  = ?1) and valid is true and complicated_events is not true ", nativeQuery = true)
    List<EventStats> findEventStatsByABTest(Long rootParent);

    @Query(value = "select * from event_stats where create_account in (select id from account where root_parent  = ?1) and complicated_events is true", nativeQuery = true)
    List<EventStats> findComplicatedRecord(Long rootParent);

    @Query(value = "select * from event_stats where complicated_events is not true and valid is true", nativeQuery = true)
    List<EventStats> findAllEsay();

    @Transactional
    @Modifying
    @Query(value = "update event_stats set modify_account = ?1,valid = false, modify_time = ?3 where id = ?2 ", nativeQuery = true)
    int deleteEventStats(Long accountId, Long eventStatsId, Date modifyDate);

    @Transactional
    @Modifying
    @Query(value = "update event_stats set event_name = ?1, event_condition = ?2,query_sql = ?3,modify_account = ?4,modify_time = ?6  where id = ?5 ", nativeQuery = true)
    int updateEventStats(String eventName, String eventCondition, String querySql, Long modifyAccount, Long eventStatsId, Date modifyDate);

    @Transactional
    @Modifying
    @Query(value = "update event_stats set event_name = ?1, event_condition = ?2,modify_account = ?3,modify_time = ?5,name = ?6  where id = ?4 ", nativeQuery = true)
    int updateEventStats(String eventName, String eventCondition, Long modifyAccount, Long eventStatsId, Date modifyDate,String name);
}
