package com.erp.permission.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.permission.entity.Role;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 角色数据访问接口
 */
@Mapper
public interface RoleRepository extends BaseMapper<Role> {
    
    /**
     * 根据slug查找角色
     */
    @Select("SELECT * FROM roles WHERE slug = #{slug} AND deleted_at IS NULL LIMIT 1")
    Role findBySlug(@Param("slug") String slug);
    
    /**
     * 检查slug是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM roles WHERE slug = #{slug} AND deleted_at IS NULL")
    boolean existsBySlug(@Param("slug") String slug);
    
    /**
     * 根据slug列表查找角色
     */
    @Select("<script>" +
            "SELECT * FROM roles WHERE slug IN " +
            "<foreach item='item' index='index' collection='slugs' open='(' separator=',' close=')'>" +
            "#{item}" +
            "</foreach>" +
            " AND deleted_at IS NULL" +
            "</script>")
    List<Role> findBySlugs(@Param("slugs") List<String> slugs);
    
    /**
     * 根据角色ID查找角色（包含权限）
     */
    @Select("SELECT * FROM roles WHERE id = #{id} AND deleted_at IS NULL LIMIT 1")
    Role findById(@Param("id") Long id);
    
    /**
     * 获取所有角色（按level降序）
     */
    @Select("SELECT * FROM roles WHERE deleted_at IS NULL ORDER BY level DESC")
    List<Role> findAllOrderByLevelDesc();
    
    /**
     * 统计角色下的用户数量
     */
    @Select("SELECT COUNT(*) FROM user_roles WHERE role_id = #{roleId}")
    Long countUsersByRoleId(@Param("roleId") Long roleId);
    
    /**
     * 检查角色下是否有用户
     */
    @Select("SELECT COUNT(*) > 0 FROM user_roles WHERE role_id = #{roleId}")
    boolean hasUsers(@Param("roleId") Long roleId);
    
    /**
     * 检查slug是否存在（排除指定ID）
     */
    @Select("SELECT COUNT(*) > 0 FROM roles WHERE slug = #{slug} AND id != #{excludeId} AND deleted_at IS NULL")
    boolean existsBySlugAndIdNot(@Param("slug") String slug, @Param("excludeId") Long excludeId);
    
    /**
     * 根据角色ID列表查找角色
     */
    @Select("<script>" +
            "SELECT r.* FROM roles r " +
            "INNER JOIN user_roles ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.deleted_at IS NULL" +
            "</script>")
    List<Role> findByUserId(@Param("userId") Long userId);
    
    /**
     * 根据角色ID获取权限ID列表
     */
    @Select("SELECT p.id 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")
    List<Long> findPermissionIdsByRoleId(@Param("roleId") Long roleId);
    
    /**
     * 清除角色所有权限
     */
    @Select("DELETE FROM role_permissions WHERE role_id = #{roleId}")
    void clearRolePermissions(@Param("roleId") Long roleId);
    
    /**
     * 插入角色权限关联
     */
    @Insert("<script>" +
            "INSERT INTO role_permissions (role_id, permission_id) VALUES " +
            "<foreach item='permId' index='index' collection='permissionIds' separator=','>" +
            "(#{roleId}, #{permId})" +
            "</foreach>" +
            "</script>")
    void insertRolePermissions(@Param("roleId") Long roleId, @Param("permissionIds") List<Long> permissionIds);
}
