package com.izouma.nineth.repo;

import com.izouma.nineth.domain.Showroom;
import com.izouma.nineth.dto.oasis.OasisContactShowroomDto;
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 javax.annotation.Nonnull;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

    @Query("update Showroom t set t.likes = t.likes + ?2 where t.id = ?1")
    @Modifying
    @Transactional
    @CacheEvict(value = "showroom", key = "#id")
    void addLike(Long id, int num);

    Optional<Showroom> findByUserIdAndType(Long userId, String type);

    Optional<Showroom> findByAssetId(Long assetId);

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

    @Cacheable(value = "showroom", key = "#id")
    Optional<Showroom> findById(@Nonnull Long id);

//    @Query("update Showroom t set t.views = t.views + ?2 where t.id = ?1")
//    @Modifying
//    @Transactional
//    void addView(Long id, int num);

    @Query("update Showroom t set t.heats = t.heats + ?2 where t.id = ?1")
    @Modifying
    @Transactional
    @CacheEvict(value = "showroom", key = "#id")
    void addHeat(Long id, int num);

    @Query("update Showroom t set t.heats = t.heats + ?2, t.likes = t.likes + ?3 where t.id = ?1")
    @Modifying
    @Transactional
    @CacheEvict(value = "showroom", key = "#id")
    void addHeatAndLike(Long id, int heatNum, int likeNum);

    @Query("update Showroom t set t.heats = t.heats + ?2, t.registers = t.registers + ?3 where t.id = ?1")
    @Modifying
    @Transactional
    @CacheEvict(value = "showroom", key = "#id")
    void addHeatAndRegister(Long id, int heatNum, int registerNum);

    @Query(nativeQuery = true, value = "select user_id, count(id) num from showroom where type = ?1 group by user_id")
    List<Map<String, Object>> countNum(String type);

    Optional<Showroom> findByOasisId(Long oasisId);

    /**
     * 关联展厅
     *
     * @param id      展厅id
     * @param oasisId 绿洲平台商品id
     */
    @Query("update Showroom t set t.oasisId = ?2 where t.id = ?1")
    @Modifying
    @Transactional
    void contactShowroomByOasisId(Long id, Long oasisId);
}