package cn.ysk.cashier.repository.product;

import cn.ysk.cashier.pojo.product.TbProduct;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.data.domain.PageRequest;
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.math.BigDecimal;
import java.util.List;

/**
* @website https://eladmin.vip
* @author lyf
* @date 2023-12-11
**/
public interface TbProductRepository extends JpaRepository<TbProduct, Integer>, JpaSpecificationExecutor<TbProduct> {


    @Query("SELECT product from TbProduct product where product.id in :productIds order by product.sort")
    List<TbProduct> findByIds(List<Integer> productIds);

    @Query(value = "update tb_product set status = -1 and is_del = 1 where id in :productIds",nativeQuery = true)
    @Modifying
    void updateByStatus(List<Integer> productIds);

    @Modifying
    @Query("update FROM TbProduct pro set pro.stockNumber=:stockNumber WHERE pro.id =:productId")
    void updateProductStockNumber(@Param("productId") Integer productId,@Param("stockNumber") Integer stockNumber);

    @Modifying
    @Query("update FROM TbProduct pro set pro.stockNumber=pro.stockNumber+:number WHERE pro.id =:productId")
    void incrProductStockNumber(Integer productId, BigDecimal number);

    @Transactional
    @Modifying
    @Query("update FROM TbProduct pro set pro.stockNumber=:stocktakinNum where pro.id=:id and pro.stockNumber=:stockNumber")
    Integer updateStock(@Param("id") Integer id,@Param("stockNumber") Integer stockNumber,
                     @Param("stocktakinNum") Integer stocktakinNum);

    @Modifying
    @Query("update TbProduct set stockNumber=stockNumber+:num where id=:id")
    void incrStock(@Param("id") Integer id, @Param("num") BigDecimal num);


    @Query("select product from TbProduct product where product.shopId=:shopId")
    List<TbProduct> selectByShopId(String shopId);

    @Query(value = "select b.* from tb_product_sku as a left join tb_product as b on a.product_id=b.id  where a.id=:skuId", nativeQuery = true)
    TbProduct selectBySkuId(@Param("skuId") Integer skuId);

    @Modifying
    @Query("update TbProduct set isGrounding=0 where id=:id")
    void upGrounding(@Param("id") Integer id);

    @Modifying
    @Query("update TbProduct set lowPrice=:lowPrice where id=:id")
    void upLowPrice(@Param("id") Integer id, @Param("lowPrice") BigDecimal lowPrice);

    @Transactional
    @Modifying
    @Query("UPDATE TbProduct p SET p.warnLine = :warnLine WHERE p.shopId = :shopId")
    Integer updateWarnLineByShopId(@Param("warnLine")Integer warnLine, @Param("shopId")String shopId);

}
