package com.erp.approval.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.approval.entity.AuditRule;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 审核规则Mapper
 */
@Mapper
public interface AuditRuleRepository extends BaseMapper<AuditRule> {
    
    /**
     * 查询租户规则（按优先级排序）
     */
    @Select("SELECT * FROM audit_rules WHERE tenant_id = #{tenantId} AND deleted_at IS NULL ORDER BY priority ASC")
    List<AuditRule> findByTenantIdOrderByPriority(@Param("tenantId") Long tenantId);
    
    /**
     * 查询租户指定类型规则（按优先级排序）
     */
    @Select("SELECT * FROM audit_rules WHERE tenant_id = #{tenantId} AND type = #{type} AND deleted_at IS NULL ORDER BY priority ASC")
    List<AuditRule> findByTenantIdAndTypeOrderByPriority(@Param("tenantId") Long tenantId, @Param("type") String type);
    
    /**
     * 查询租户活跃规则（按优先级排序）
     */
    @Select("SELECT * FROM audit_rules WHERE tenant_id = #{tenantId} AND is_active = 1 AND deleted_at IS NULL ORDER BY priority ASC")
    List<AuditRule> findActiveByTenantIdOrderByPriority(@Param("tenantId") Long tenantId);
    
    /**
     * 查询租户指定类型活跃规则（按优先级排序）
     */
    @Select("SELECT * FROM audit_rules WHERE tenant_id = #{tenantId} AND type = #{type} AND is_active = 1 AND deleted_at IS NULL ORDER BY priority ASC")
    List<AuditRule> findActiveByTenantIdAndTypeOrderByPriority(@Param("tenantId") Long tenantId, @Param("type") String type);
    
    /**
     * 检查规则名称是否存在
     */
    @Select("SELECT COUNT(*) FROM audit_rules WHERE tenant_id = #{tenantId} AND name = #{name} AND deleted_at IS NULL")
    int countByTenantIdAndName(@Param("tenantId") Long tenantId, @Param("name") String name);
    
    /**
     * 检查规则名称是否存在（排除指定ID）
     */
    @Select("SELECT COUNT(*) FROM audit_rules WHERE tenant_id = #{tenantId} AND name = #{name} AND id != #{excludeId} AND deleted_at IS NULL")
    int countByTenantIdAndNameExcludeId(@Param("tenantId") Long tenantId, @Param("name") String name, @Param("excludeId") Long excludeId);
    
    /**
     * 获取同类型最大优先级
     */
    @Select("SELECT MAX(priority) FROM audit_rules WHERE tenant_id = #{tenantId} AND type = #{type} AND deleted_at IS NULL")
    Integer findMaxPriorityByTenantIdAndType(@Param("tenantId") Long tenantId, @Param("type") String type);
}
