package org.dromara.web.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.dromara.web.domain.FoodIngredientStock;
import org.dromara.web.domain.vo.FoodIngredientStockVo;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
import org.dromara.web.domain.vo.FoodStockBalanceVo;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 食材出入库Mapper接口
 *
 * @author Lion Li
 * @date 2025-08-18
 */
@Repository
public interface FoodIngredientStockMapper extends BaseMapperPlus<FoodIngredientStock, FoodIngredientStockVo> {

@Select(" <script> SELECT fis.food_id AS foodId, fis.food_name as foodName, fis.main_class as mainClass, fis.main_class_name as mainClassName, fis.sub_class as subClass, fis.sub_class_name as subClassName, " +
    "fis.stock_unit as stockUnit, " +
    " SUM( CASE WHEN fis.type = '0' THEN num ELSE 0 END ) -  SUM( CASE WHEN fis.type IN ( '1', '2', '3' ) THEN fis.num ELSE 0 END ) AS stockNum " +
    " FROM food_ingredient_stock fis where 1 =1 " +
    "<if test='mainClass != null'> and (fis.main_class = #{mainClass} or fis.sub_class = #{mainClass}) </if> " +
    "<if test='searchValue != null and searchValue != \"\"'> and (fis.food_name like concat('%', #{searchValue}, '%')) </if>" +
    "GROUP BY fis.food_id, fis.main_class, fis.sub_class, fis.stock_unit, fis.food_name, fis.main_class_name, fis.sub_class_name " +
    "<if test='offset != null and rows != null'>LIMIT #{offset}, #{rows}</if>" +
    "</script>" )
List<FoodStockBalanceVo> queryStockBalance(@Param("mainClass") Long mainClass, @Param("searchValue") String searchValue, @Param("offset") Integer offset, @Param("rows") Integer rows);

    @Select(" <script> SELECT COUNT(*)  FROM ( SELECT 1  FROM food_ingredient_stock fis WHERE 1 = 1 " +
        "    <if test='mainClass != null'> AND(fis.main_class = #{mainClass} or fis.sub_class = #{mainClass}) </if> " +
        "    <if test='searchValue != null and searchValue != \"\"'> " +
        "        AND (fis.food_name LIKE CONCAT('%', #{searchValue}, '%') ) </if> " +
        "    GROUP BY fis.food_id, fis.main_class, fis.sub_class, fis.stock_unit " +
        ") AS grouped_data " +
        "</script>" )
    Integer queryStockBalanceCount(@Param("mainClass") Long mainClass, @Param("searchValue") String searchValue);
}
