package com.reyun.repository;

import com.reyun.model.CustomMenuShare;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by sunhao on 17/4/21.
 * desc:分享看单(即行业看单模板)
 */
public interface CustomMenuShareRepository extends JpaRepository<CustomMenuShare,Long>{

    @Query(value = "select * from custom_menu_share where category = ?1 and del_flag is false order by share_date desc ",nativeQuery = true)
    List<CustomMenuShare> listAllSharedByCategory(Long categoryId);

    @Query(value = "select * from custom_menu_share where del_flag is false order by share_date desc ",nativeQuery = true)
    List<CustomMenuShare> listAllShared();

    @Query(value = "select * from custom_menu_share where original_menu = ?1 and del_flag is false ",nativeQuery = true)
    CustomMenuShare findShareByOriginalMenu(Long menuId);

    @Query(value = "SELECT * from custom_menu_share where del_flag is FALSE GROUP BY (category)", nativeQuery = true)
    List<CustomMenuShare> findIndustry();

    @Query(value = "select * from custom_menu_share where id = ?1 ", nativeQuery = true)
    CustomMenuShare findShareById(Long shareId);

    @Query(value = "select * from custom_menu_share where reyun_menu is true and category = ?1", nativeQuery = true)
    List<CustomMenuShare> findReyunMenu(Long categoryId);

    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set use_number = use_number + 1 where id = ?1 ",nativeQuery = true)
    int addUserNumber(Long menuId);

    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set use_number = (CASE WHEN use_number - 1 < 0 THEN 0 ELSE use_number - 1 END) where id = ?1 ",nativeQuery = true)
    int minusUserNumber(Long menuId);

    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set favorite_number = favorite_number + 1 where id = ?1 ",nativeQuery = true)
    int addFavoriteNumber(Long menuId);

    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set favorite_number = (CASE WHEN favorite_number - 1 < 0 THEN 0 ELSE favorite_number - 1 END) where id = ?1 ",nativeQuery = true)
    int minusFavoriteNumber(Long menuId);

    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set del_flag = true where id = ?1 and del_flag is false", nativeQuery = true)
    int deleteShareMenu(Long menuId);


    @Transactional
    @Modifying
    @Query(value = "update custom_menu_share set account_name = ?2 where account_id = ?1  ", nativeQuery = true)
    int updateAccountName(Long accountId, String accountName);
}
