 package org.sky.system.cache;

 import org.sky.core.cache.utils.CacheUtil;
 import org.sky.core.tool.utils.SpringUtil;
 import org.sky.core.tool.utils.StringPool;
 import org.sky.system.feign.IApiScopeClient;

 import java.util.List;

 import static org.sky.core.cache.constant.CacheConstant.SYS_CACHE;


 /**
 * 接口权限缓存
 *
  */
public class ApiScopeCache {

	private static final String SCOPE_CACHE_ROLE = "apiScope:role:";

	private static final String SCOPE_CACHE_CODE = "apiScope:code:";

	private static final String SCOPE_CACHE_MENU = "apiScope:menu:";

	private static IApiScopeClient apiScopeClient;

	private static IApiScopeClient getApiScopeClient() {
		if (apiScopeClient == null) {
			apiScopeClient = SpringUtil.getBean(IApiScopeClient.class);
		}
		return apiScopeClient;
	}

	/**
	 * 获取接口权限地址
	 *
	 * @param roleId 角色id
	 * @return permissions
	 */
	public static List<String> permissionPath(String roleId) {
		List<String> permissions = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_ROLE, roleId, List.class, Boolean.FALSE);
		if (permissions == null) {
			permissions = getApiScopeClient().permissionPath(roleId);
			CacheUtil.put(SYS_CACHE, SCOPE_CACHE_ROLE, roleId, permissions, Boolean.FALSE);
		}
		return permissions;
	}

	/**
	 * 获取接口权限信息
	 *
	 * @param permission 权限编号
	 * @param roleId     角色id
	 * @return permissions
	 */
	public static List<String> permissionCode(String permission, String roleId) {
		List<String> permissions = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_CODE, permission + StringPool.COLON + roleId, List.class, Boolean.FALSE);
		if (permissions == null) {
			permissions = getApiScopeClient().permissionCode(permission, roleId);
			CacheUtil.put(SYS_CACHE, SCOPE_CACHE_CODE, permission + StringPool.COLON + roleId, permissions, Boolean.FALSE);
		}
		return permissions;
	}

	/**
	 * 获取菜单权限信息
	 *
	 * @param permission 菜单编号
	 * @param roleId     角色id
	 * @return permissions
	 */
	public static List<String> permissionMenu(String permission, String roleId) {
		List<String> permissions = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_MENU, permission + StringPool.COLON + roleId, List.class, Boolean.FALSE);
		if (permissions == null) {
			permissions = getApiScopeClient().permissionMenu(permission, roleId);
			CacheUtil.put(SYS_CACHE, SCOPE_CACHE_MENU, permission + StringPool.COLON + roleId, permissions, Boolean.FALSE);
		}
		return permissions;
	}

}
