package com.reyun.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.reyun.model.App;

public interface AppRepository extends JpaRepository<App, Long> {

	@Query(value = "select * from app where account in (select id from account where parent = ?1 or id = ?1) and del_flag is not true", nativeQuery = true)
	List<App> listAppByRootAccount(Long account);
	
	@Query(value="select appkey from app where id = ?1",nativeQuery=true)
	String findAppkeyById(Long id);
	
	List<App> findByAccount(Long account);

	@Query(value = "select * from app where account =?1 and bundleid = ?2 and del_flag is not true", nativeQuery = true)
	App findByBundleidInNotDel(Long account, String bundleid);
	
	@Query(value = "select * from app where account =?1 and name = ?2 and del_flag is not true", nativeQuery = true)
	App findByNameNotDel(Long account, String name);

    @Query(value = "select * from app where token = ?1 limit 1", nativeQuery = true)
    App findOneByAppToken(String token);

	@Query(value = "select * from app where id in ?1", nativeQuery = true)
	List<App> findByIds(List<Long> ids);

	@Query(value = "select * from app where appkey in ?1", nativeQuery = true)
	List<App> findByAppkeys(List<String> appkeys);

    @Query(value = "select * from app a join auth b on a.id = b.app where b.account = ?1 and b.create_account in (select id from account where root_parent = ?2) ", nativeQuery = true)
    List<App> findAuthAppByRootParent(Long subAccountId, Long rootParent);

    @Query(value = "select * from app a join auth b on a.id = b.app where b.account = ?1 ", nativeQuery = true)
    List<App> findAuthApp(Long subAccountId);

	@Query(value="select platform from app where id = ?1",nativeQuery=true)
	String findPlatformByAppId(Long appId);

	@Query(value="select categoryname from category where categoryid=(select game_genre from app where id=?1);",nativeQuery=true)
	String findGameCategoryByAppID(Long appId);

	@Query(value="select categoryname from category where categoryid=(select app_genre from app where id=?1);",nativeQuery=true)
	String findAppGenreNameByAppID(Long id);

	@Query(value = "select DISTINCT a.* from app a right join data_auth d on a.id = d.app where d.account = ?1 and d.app in ?2 and d.channel = ?3 and (d.all_campaign is true or d.channel_permit is true)", nativeQuery = true)
	List<App> listTotalAuthorizedApp(Long accountId, List<Long> appIdList, Long channelId);

	@Query(value = "select create_account from app where appkey=?1", nativeQuery = true)
	String  findCreateAccountByAppkey(String appKey);

}
