package com.izouma.nineth.repo;

import com.izouma.nineth.domain.Collection;
import com.izouma.nineth.dto.RecommendCollection;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.jpa.repository.*;

import javax.annotation.Nonnull;
import javax.persistence.LockModeType;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public interface CollectionRepo extends JpaRepository<Collection, Long>, JpaSpecificationExecutor<Collection> {

    @Query("update Collection t set t.del = true where t.id = ?1")
    @Modifying
    @Transactional
    @CacheEvict(value = {"collection", "recommend"}, allEntries = true)
    void softDelete(Long id);


    Optional<Collection> findByIdAndDelFalse(Long id);

    /**
     * 锁定记录，不能缓存
     * @param id
     * @return
     */
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select c from Collection c where c.id = ?1")
    Optional<Collection> findByIdForUpdate(Long id);



    @Query("update Collection t set t.likes = t.likes + ?2 where t.id = ?1")
    @Modifying
    @Transactional
    void addLike(Long id, int num);

    @Query(value = "select distinct c from Collection c join Like l on l.collectionId = c.id " +
            "where l.userId = ?1 and l.del = false and c.del = false")
    List<Collection> userLikes(Long userId);

    List<Collection> findByScheduleSaleTrueAndOnShelfFalseAndStartTimeBeforeAndDelFalse(LocalDateTime time);

    @Nonnull
    Collection save(@Nonnull Collection collection);

    @Query("select new com.izouma.nineth.dto.RecommendCollection(c,r) from Collection c join Recommend r on c.id = r.collectionId " +
            "where c.del = false and c.onShelf = true and r.type = ?1 and c.projectId = ?2 order by r.sort desc")
    List<RecommendCollection> recommend(String type, int projectId);

    @Transactional
    @Modifying
    @Query("update Collection c set c.scheduleSale = false, c.startTime = null, c.onShelf = true, c.salable = true where c.id = ?1")
    void scheduleOnShelf(Long id);

    @Transactional
    @Modifying
    @Query("update Collection c set c.currentNumber = COALESCE(c.currentNumber, 0) + ?2 where c.id = ?1")
    void increaseNumber(Long id, int d);

    @Transactional
    @Modifying
    @Query("update Collection c set c.sale = COALESCE(c.sale, 0) + ?2 where c.id = ?1")
    void increaseSale(Long id, int d);

    @Transactional
    @Modifying
    @Query("update Collection c set c.stock = COALESCE(c.stock, 0) + ?2 where c.id = ?1")
    void increaseStock(Long id, int d);

    @Transactional
    @Modifying
    @Query("update Collection c set c.total = COALESCE(c.total, 0) + ?2 where c.id = ?1")
    void increaseTotal(Long id, int d);

    @Transactional
    @Modifying
    @Query("update Collection c set c.onShelf = ?2 where c.id = ?1")
    void setOnShelf(Long id, boolean onShelf);

    @Query("select c.currentNumber from Collection c where c.id = ?1")
    Optional<Integer> getCurrentNumber(Long id);

    @Query("select c.id from Collection c where c.assetId in ?1")
    List<Long> findAllByDelFalseAndAssetIdIn(java.util.Collection<Long> assetId);

    @Query("select c.id from Collection c where c.assetId = ?1 and c.source = 'TRANSFER'")
    List<Long> findAllByAssetId(Long assetId);

    @Query("update Collection t set t.del = true where t.id in ?1")
    @Modifying
    @Transactional
    void softDeleteByIdIn(java.util.Collection<Long> id);

    @Modifying
    @Transactional
    void deleteAllByIdIn(java.util.Collection<Long> id);

    @Query("select c.stock from Collection c where c.id = ?1")
    Integer getStock(Long id);

    @Query("select c.sale from Collection c where c.id = ?1")
    Integer getSale(Long id);

    @Query("update Collection c set c.stock = c.stock - ?2, c.sale = c.sale + ?2 where c.id = ?1")
    @Modifying
    @Transactional
    void decreaseStockAndIncreaseSale(Long id, int num);

    @Transactional
    @Modifying
    int deleteByAssetId(Long assetId);

    @Query(value = "select c.id, c.pic, c.model3d, c.minter_avatar, c.owner_avatar, c.detail from collection_info c", nativeQuery = true)
    List<List<String>> selectResource();

    @Query(value = "select c.id, c.pic, c.model3d, c.minter_avatar, c.owner_avatar, c.detail from collection_info c where c.id = ?1", nativeQuery = true)
    List<List<String>> selectResource(Long id);

    @Modifying
    @Transactional
    @Query(value = "update collection_info c set c.pic = ?2, c.model3d = ?3, c.minter_avatar = ?4, " +
            "c.owner_avatar = ?5, c.detail = ?6 where c.id = ?1", nativeQuery = true)
    int updateCDN(Long id, String pic, String model3d, String minterAvatar,
                  String ownerAvatar, String detail);

    List<Collection> findAllByIdIn(java.util.Collection<Long> ids);

    @Modifying
    @Transactional
    @Query(value = "update collection_info  set collection_category_id = ?1 , categories = ?2 " +
            "where asset_id in (select id from asset a where a.collection_id = ?3 )", nativeQuery = true)
    void updateTransferCollection(Long categoryId, String categories, Long id);
}