package com.izouma.nineth.repo;

import com.izouma.nineth.domain.AwardActivityCollectionInfo;
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;

/**
 * 可兑换活动收集列表
 * @author ZouYuHong
 */
public interface AwardActivityCollectionInfoRepo extends JpaRepository<AwardActivityCollectionInfo, Long>, JpaSpecificationExecutor<AwardActivityCollectionInfo> {

    /**
     * 获取 指定藏品库存
     * @param activityId 活动Id
     * @param collectionId 藏品Id
     * @return 数量
     */
    @Query("select c.stock from AwardActivityCollectionInfo c where c.activityId = ?1 and c.collectionId = ?2")
    Integer selectByActivityIdAndCollectionId(Long activityId, Long collectionId);

    /**
     * 更新库存
     * @param activityId 活动ID
     * @param collectionId 藏品ID
     * @param stock 库存
     * @return 更新数量
     */
    @Query("update AwardActivityCollectionInfo c set c.stock = ?3 where c.activityId = ?1 and c.collectionId = ?2")
    @Transactional
    @Modifying
    int updateStock(Long activityId, Long collectionId, int stock);

    /**
     *
     * @param collectionId
     * @return
     */
    @Query(value = "select t.activity_id from award_activity_collection_info t where t.collection_id = ?1 and del = 0 order by t.created_at desc limit 1" , nativeQuery = true)
    Long selectLastActivityIdByCollectionId(Long collectionId);

    @Query("update AwardActivityCollectionInfo t set t.del = true where t.activityId = ?1 ")
    @Modifying
    @Transactional
    void softDeleteByActivityId(Long activityId);
}
