package com.CUST.brain.common.utils;

import com.CUST.brain.dao.mapper.SysUserRoleMapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

@Component
public class CacheCleanUtils {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private CacheManager cacheManager;

    /**
     * 清理角色相关缓存
     * key: cache:sys:role:detail:{roleId}
     *      cache:sys:role:select*
     */
    public void clearRoleCache(String roleId) {
        if (roleId != null) {
            redisUtils.delete("cache:sys:role:detail:" + roleId);
        }
        redisUtils.deleteByPattern("cache:sys:role:select*");
    }

    /**
     * 清理用户相关缓存
     * key: cache:sys:user:info:{userId}
     *      cache:user:roles:{userId}
     *      cache:user:permissions:{userId}
     */
    public void clearUserCache(String userId) {
        if (userId != null) {
            redisUtils.delete("cache:sys:user:info:" + userId);
            redisUtils.delete("cache:user:roles:" + userId);
            redisUtils.delete("cache:user:permissions:" + userId);
        }
    }

    /**
     * 清理用户信息缓存（通过用户名）
     * key: cache:sys:user:{username}
     */
    public void clearUserCacheByUserName(String username) {
        if (username != null) {
            redisUtils.delete("cache:sys:user:" + username);
        }
    }

    /**
     * 清理拥有某角色的所有用户的相关缓存
     */
    public void clearUsersByRole(String roleId) {
        if (roleId != null) {
            List<String> userIds = sysUserRoleMapper.selectUserIdsByRoleId(roleId);
            for (String userId : userIds) {
                clearUserCache(userId);
            }
        }
    }

    /**
     * 清理角色权限分配列表缓存
     * key: cache:permission:listForRole:{roleCode}
     */
    public void clearPermissionListCacheByRoleCode(String roleCode) {
        if (roleCode != null) {
            redisUtils.delete("cache:permission:listForRole:" + roleCode);
        }
    }

    /**
     * 清理所有角色权限分配列表缓存（如有需要）
     */
    public void clearAllPermissionListCache() {
        redisUtils.deleteByPattern("cache:permission:listForRole*");
    }

    /**
     * 清理参数缓存
     *
     * @param paramType 参数类型
     * @param paramName 参数名称，如果为null则清理该类型的所有参数缓存
     */
    public void clearParamCache(String paramType, String paramName) {
        if (paramType != null) {
            redisUtils.delete("sys:param:type:" + paramType);
            redisUtils.delete("sys:param:list:" + paramType);
        }
    }
}