<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.erp.inventory.repository.StockWarningRuleRepository">

    <!-- 分页查询预警规则列表 -->
    <select id="findByConditions" resultType="com.erp.inventory.entity.StockWarningRule">
        SELECT * FROM stock_warning_rules
        WHERE 1=1
        <if test="ruleType != null and ruleType != ''">
            AND rule_type = #{ruleType}
        </if>
        <if test="ruleName != null and ruleName != ''">
            AND rule_name LIKE CONCAT('%', #{ruleName}, '%')
        </if>
        <if test="enabled != null">
            AND enabled = #{enabled}
        </if>
        <if test="warehouseId != null">
            AND (warehouse_id = #{warehouseId} OR warehouse_id IS NULL)
        </if>
        ORDER BY updated_at DESC
    </select>

    <!-- 查询所有启用的规则 -->
    <select id="findAllEnabled" resultType="com.erp.inventory.entity.StockWarningRule">
        SELECT * FROM stock_warning_rules
        WHERE enabled = 1
        ORDER BY warehouse_id ASC, sku_code ASC
    </select>

    <!-- 根据规则类型查询启用的规则 -->
    <select id="findByRuleTypeAndEnabled" resultType="com.erp.inventory.entity.StockWarningRule">
        SELECT * FROM stock_warning_rules
        WHERE rule_type = #{ruleType}
        AND enabled = #{enabled}
        ORDER BY warehouse_id ASC, sku_code ASC
    </select>

    <!-- 根据SKU编码和仓库ID查询启用的规则 -->
    <select id="findBySkuCodeAndWarehouseIdAndEnabled" resultType="com.erp.inventory.entity.StockWarningRule">
        SELECT * FROM stock_warning_rules
        WHERE enabled = #{enabled}
        AND (sku_code IS NULL OR sku_code = '' OR sku_code = #{skuCode})
        AND (warehouse_id IS NULL OR warehouse_id = #{warehouseId})
        ORDER BY warehouse_id ASC, sku_code ASC
    </select>

</mapper>
