package com.erp.permission.repository;

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

import java.util.List;

/**
 * 权限数据访问接口
 */
@Mapper
public interface PermissionRepository extends BaseMapper<Permission> {
    
    /**
     * 根据slug查找权限
     */
    @Select("SELECT * FROM permissions WHERE slug = #{slug} AND deleted_at IS NULL LIMIT 1")
    Permission findBySlug(@Param("slug") String slug);
    
    /**
     * 根据slug列表查找权限
     */
    @Select("<script>" +
            "SELECT * FROM permissions WHERE slug IN " +
            "<foreach item='item' index='index' collection='slugs' open='(' separator=',' close=')'>" +
            "#{item}" +
            "</foreach>" +
            " AND deleted_at IS NULL" +
            "</script>")
    List<Permission> findBySlugs(@Param("slugs") List<String> slugs);
    
    /**
     * 根据分组名称查找权限
     */
    @Select("SELECT * FROM permissions WHERE group_name = #{groupName} AND deleted_at IS NULL ORDER BY sort ASC")
    List<Permission> findByGroupName(@Param("groupName") String groupName);
    
    /**
     * 获取所有分组名称
     */
    @Select("SELECT DISTINCT group_name FROM permissions WHERE group_name IS NOT NULL AND deleted_at IS NULL ORDER BY group_name")
    List<String> findAllGroupNames();
    
    /**
     * 根据角色ID查找权限
     */
    @Select("SELECT p.* FROM permissions p " +
            "INNER JOIN role_permissions rp ON p.id = rp.permission_id " +
            "WHERE rp.role_id = #{roleId} AND p.deleted_at IS NULL " +
            "ORDER BY p.group_name, p.sort")
    List<Permission> findByRoleId(@Param("roleId") Long roleId);
    
    /**
     * 检查slug是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM permissions WHERE slug = #{slug} AND deleted_at IS NULL")
    boolean existsBySlug(@Param("slug") String slug);
}
