package com.izouma.nineth.repo;

import com.izouma.nineth.domain.User;
import com.izouma.nineth.dto.CollectionStockAndSale;
import com.izouma.nineth.dto.InvitedUserDTO;
import com.izouma.nineth.dto.InvitorDTO;
import com.izouma.nineth.enums.AuthStatus;
import com.izouma.nineth.security.Authority;
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 javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
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);

    @Transactional
    @Modifying
    @Query("update User u set u.del = true where u.del = false and u.id in ?1")
    void softDeleteIn(Collection<Long> id);

    Optional<User> findByUsernameAndDelFalse(String username);

    List<User> findAllByAuthoritiesContainsAndDelFalse(Authority authority);

    Optional<User> findByOpenIdAndDelFalse(String openId);

    Optional<User> findByPhoneAndDelFalse(String phone);

    @Cacheable(value = "user", key = "#userId")
    Optional<User> findByIdAndDelFalse(Long userId);

    @Cacheable(value = "user", key = "#userId")
    @Query("select u from User u where u.id = ?1 and u.del = false")
    Optional<User> jwtFindUserCache(Long userId);

    @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);

    @Transactional
    @Modifying
    @Query("update User u set u.sales = COALESCE(u.sales, 0) + ?2 where u.id = ?1")
    public void increaseSales(Long id, int num);

    @Query("select phone from User where id = ?1 and del = false")
    String findPhoneById(Long id);

    List<User> findAllByCollectionIdAndCollectionInvitor(Long collectionId, Long collectionInvitor);

    List<User> findAllByCollectionIdAndCollectionInvitorAndSettleAccountIdIsNotNull(Long collectionId, Long collectionInvitor);

    int countAllByCollectionIdAndCollectionInvitorAndSettleAccountIdIsNotNull(Long collectionId, Long collectionInvitor);

    long countAllByDelFalse();

    List<User> findAllByCreatedAtIsAfterAndAdminFalse(LocalDateTime createdAt);

    long countByCreatedAtBetween(LocalDateTime start, LocalDateTime end);

    List<User> findBySettleAccountIdIsNotNull();

    @Transactional
    @Modifying
    @Query("update User set vipPoint = vipPoint + ?2 where id = ?1")
    void addVipPoint(Long id, int num);

    @Transactional
    @Modifying
    @Query("update User set vipPoint = ?2 where id = ?1")
    void updateVipPoint(Long id, int num);

    @Transactional
    @Modifying
    @Query("update User set vipPoint = 0")
    void clearVipPoint();

    @Query("update User u set u.authStatus = ?2, u.authId = ?3 where u.id = ?1")
    @Transactional
    @Modifying
    void setAuthStatus(Long id, AuthStatus status, Long authId);

    @Query(nativeQuery = true, value = "select collection_invitor" +
            " from user" +
            " where collection_id = ?1" +
            " group by collection_invitor" +
            " having count(id) >= ?2")
    List<Long> findInvitorByCollectionId(Long collectionId, int size);

    @Transactional
    @Modifying
    @Query("update User set vipPoint = 1 where vipPoint = 0 and id in ?1")
    void updateAllByInvitor(Collection<Long> ids);

    List<User> findAllByCollectionId(Long collectionId);

    @Query(value = "update showroom join user on showroom.user_id = user.id " +
            "set showroom.nickname = user.nickname " +
            "where user.id = ?1 ", nativeQuery = true)
    @Modifying
    @Transactional
    void updateShowroomToUser(Long userId);

    @Modifying
    @Transactional
    @Query("update User set vipPurchase = ?2 where id = ?1")
    void updateVipPurchase(Long id, int vipPurchase);

    @Query("select u.tradeCode from User u where u.id = ?1")
    String findTradeCode(Long id);

    List<User> findAllByIdIn(List<Long> ids);

    @Query(nativeQuery = true, value = "select u.id, u.nickname, cid " +
            "from user u " +
            "         inner join (select collection_invitor, count(id) cid " +
            "                     from user ci1 " +
            "                     where collection_id = ?1 " +
            "                     group by collection_invitor) ci1 on ci1.collection_invitor = u.id " +
            "order by cid desc;")
    List<Object[]> customSearch(Long id);

    @Query("select new com.izouma.nineth.dto.InvitedUserDTO(u.phone,u.authStatus,u.avatar,u.createdAt) from  User u where u.collectionId = ?1 and u.collectionInvitor = ?2")
    List<InvitedUserDTO> findInvitedDTO(Long collectionId, Long collectionInvitor);

    @Query("select u.id from User u where u.del = false and u.level = 99")
    List<Long> findIdByLevel();

    @Query("select u.id from User u where u.del = false and u.phone in ?1")
    List<Long> findIdByPhones(Collection<String> phones);

    @Transactional
    @Modifying
    @Query("update User set destroyPoint = destroyPoint + ?2 where id = ?1")
    void addDestroyPoint(Long id, int num);
}
