package com.microservices.system.service.impl;

import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.redis.service.RedisService;
import com.microservices.system.api.domain.SysRole;
import com.microservices.system.domain.SysRoleMenu;
import com.microservices.system.mapper.SysRoleMenuMapper;
import com.microservices.system.service.ISysRoleMenuService;
import com.microservices.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author otto
 */
@Service
public class SysRoleMenuServiceImpl implements ISysRoleMenuService {

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    @Lazy
    private ISysRoleService roleService;

    @Override
    public int checkMenuExistRole(Long menuId) {
        return roleMenuMapper.checkMenuExistRole(menuId);
    }

    @Override
    public void deleteRoleMenuByRoleId(Long roleId) {
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        deleteRoleMenusCacheByRoleId(roleId);
    }

    @Override
    public int batchRoleMenu(SysRole role, List<SysRoleMenu> list) {
        int success = roleMenuMapper.batchRoleMenu(list);
        deleteRoleMenusCacheByRoleId(role.getRoleId());
        return success;
    }

    @Override
    public void deleteRoleMenu(Long[] roleIds) {
        roleMenuMapper.deleteRoleMenu(roleIds);
        for (Long roleId : roleIds) {
            deleteRoleMenusCacheByRoleId(roleId);
        }
    }

    /**
     * 删除所有角色菜单权限缓存
     */
    @Override
    public void deleteRoleMenuCacheByMenuId() {
        List<SysRole> roleList = roleService.selectRoleAll();
        for (SysRole role : roleList) {
            redisService.deleteObject(CacheConstants.getRoleMenuPermissionsKey(role.getRoleKey()));
        }
    }

    /**
     * 删除角色菜单权限缓存
     *
     * @param roleId 角色Id
     */
    public void deleteRoleMenusCacheByRoleId(Long roleId) {
        SysRole role = roleService.selectRoleById(roleId);
        if (role != null) {
            redisService.deleteObject(CacheConstants.getRoleMenuPermissionsKey(role.getRoleKey()));
        }
    }
}
