package com.izouma.nineth.repo;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.security.Authority;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.lang.NonNull;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public interface UserRepo extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
    @Transactional
    @Modifying
    @Query("update User u set u.del = true where u.id = ?1")
    void softDelete(Long id);

    @CacheEvict(value = "user", key = "#user.username", allEntries = true)
    @NonNull
    User save(@NonNull User user);

    @Cacheable("user")
    User findByUsernameAndDelFalse(String username);

    User findByUsername(String username);

    List<User> findAllByAuthoritiesContainsAndDelFalse(Authority authoorderRepority);

    Optional<User> findByOpenIdAndDelFalse(String openId);

    Optional<User> findByPhoneAndDelFalse(String phone);

    Optional<User> findByIdAndDelFalse(Long userId);

    Optional<User> findByPhone(String phone);

    @Transactional
    @Modifying
    @Query("update User u set u.followers = u.followers + ?1 where u.id = ?1")
    void addFollow(Long userId, int num);

    @Query("select distinct u from User u join Follow f on u.id = f.followUserId " +
            "where f.userId = ?1 and u.del = false ")
    List<User> userFollows(Long userId);


    @Query("select distinct u from User u join Follow f on u.id = f.userId " +
            "where f.followUserId = ?1 and u.del = false ")
    List<User> userFollowers(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update user set follows = (select count(*) from follow " +
            "where follow.user_id = ?1) where user.id = ?1", nativeQuery = true)
    void updateFollows(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update user set followers = (select count(*) from follow " +
            "where follow.follow_user_id = ?1) where user.id = ?1", nativeQuery = true)
    void updateFollowers(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update collection_info join user on collection_info.minter_id = user.id " +
            "set collection_info.minter        = user.nickname, " +
            "    collection_info.minter_avatar = user.avatar " +
            "where user.id = ?1", nativeQuery = true)
    void updateMinterForCollection(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update collection_info join user on collection_info.owner_id = user.id " +
            "set collection_info.owner        = user.nickname, " +
            "    collection_info.owner_avatar = user.avatar " +
            "where user.id = ?1", nativeQuery = true)
    void updateOwnerForCollection(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update order_info join user on order_info.minter_id = user.id " +
            "set order_info.minter        = user.nickname, " +
            "    order_info.minter_avatar = user.avatar " +
            "where user.id = ?1", nativeQuery = true)
    void updateMinterForOrder(Long userId);

    @Transactional
    @Modifying
    @Query(value = "update asset join user on asset.minter_id = user.id " +
            "set asset.minter        = user.nickname, " +
            "    asset.minter_avatar = user.avatar " +
            "where user.id = ?1", nativeQuery = true)
    void updateMinterForAsset(Long userId);

    List<User> findByPhoneInAndDelFalse(Iterable<String> phone);

    List<User> findByIdInAndDelFalse(Iterable<Long> userId);

    @Query(value = "update asset join user on asset.minter_id = user.id " +
            "set asset.minter        = user.nickname, " +
            "    asset.minter_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateAssetMinter(Long userId);

    @Query(value = "update asset join user on asset.owner_id = user.id " +
            "set asset.owner        = user.nickname, " +
            "    asset.owner_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateAssetOwner(Long userId);

    @Query(value = "update collection_info join user on collection_info.minter_id = user.id " +
            "set collection_info.minter        = user.nickname, " +
            "    collection_info.minter_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateCollectionMinter(Long userId);

    @Query(value = "update collection_info join user on collection_info.owner_id = user.id " +
            "set collection_info.owner        = user.nickname, " +
            "    collection_info.owner_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateCollectionOwner(Long userId);

    @Query(value = "update order_info join user on order_info.minter_id = user.id " +
            "set order_info.minter        = user.nickname, " +
            "    order_info.minter_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateOrderMinter(Long userId);

    @Query(value = "update token_history join user on token_history.from_user_id = user.id " +
            "set token_history.from_user        = user.nickname, " +
            "    token_history.from_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateHistoryFromUser(Long userId);

    @Query(value = "update token_history join user on token_history.to_user_id = user.id " +
            "set token_history.to_user        = user.nickname, " +
            "    token_history.to_avatar = user.avatar " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateHistoryToUser(Long userId);

    @Transactional
    @Modifying
    @Query("update User u set u.sales = ?2 where u.id = ?1")
    void setSales(Long userId, int sales);

    List<User> findByAuthoritiesContains(Authority authority);

    List<User> findBySettleAccountIdIsNotNull();

    @Query("select u from User u where u.invitor = ?1 and u.createdAt > ?2")
    List<User> getUserInviteData(Long invitor, LocalDateTime time);

    @Query(nativeQuery = true ,value = "SELECT * FROM user WHERE invite_num > 0 and del = false  ORDER BY invite_num DESC  limit 30")
    List<User>  getUserInviteRanking();

    @Query("select u from User u where u.createdAt <= ?1 and u.del = false")
    List<User> getUserLocalDateTime(LocalDateTime time);




    @Query(nativeQuery = true ,value ="SELECT * FROM user u WHERE u.invitor IS not NULL and u.bank_card =0 and u.id  and u.created_at >= ?1 and ( " +
            "SELECT count(*) FROM user_bank_card c WHERE c.bank_no =(SELECT b.bank_no FROM user_bank_card b WHERE b.user_id = u.id )) =?2")
    List<User> userInvitedCard(LocalDateTime time,int count);


    @Query(nativeQuery = true ,value ="select u.invitor as  userid, count(*) as num from user u where u.invitor is not NULL  and u.created_at >=?1 and u.auth_status=?2  GROUP BY u.invitor ORDER BY num DESC LIMIT 30")
    List<Map<String,Object>> userIinvitor(LocalDateTime time,String status);

    @Query(nativeQuery = true ,value = "SELECT phone FROM user WHERE id = ?1")
    String findPhone(Long id);

    /**
     * 昨天注册数
     * @return 昨天注册数
     */
    @Query(nativeQuery = true ,value = "select count(*) from `user` u where date(u.created_at) = date_sub(curdate(),interval 1 day)")
    Integer lastDayRegisterNum();


    @Query(nativeQuery = true, value="update user set app_client_id = ?2 where user_id = ?1")
    @Modifying
    Integer updateAppClientId(Long userId, String appClientId);

}
