package com.yunfeiyun.agmp.common.framework.manager;

import com.alibaba.fastjson2.JSONArray;
import com.yunfeiyun.agmp.common.framework.web.service.ISysMenuService;
import com.yunfeiyun.agmp.common.web.system.mapper.SysMenuMapper;
import com.yunfeiyun.agmp.common.annotation.ConditionalRun;
import com.yunfeiyun.agmp.common.core.domain.entity.SysMenu;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseMenu;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseRunParam;
import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;


@Component
public class RbacDictManager {

    private static final Logger logger = LoggerFactory.getLogger(RbacDictManager.class);

    public static final String PREMISSION_STRING = "perms";


    /**
     * 项目启动时，初始化字典到缓存
     */
    @ConditionalRun(name="角色缓存", key = {"SYS.RBAC"},value = {"1"})
    public void init(IBaseRunParam param)
    {
        logger.info("执行={} {}  输出消息=[{}]" , param.getLevel() , param.getName(),param.toString());
        resetMenuCache();
    }

    public static void refreshMenuCache(){
        SpringUtils.getBean(RbacDictManager.class).resetMenuCache();
    }

    /**
     * 加载字典缓存数据
     */
    public void loadingDictCache()
    {
        List<IBaseMenu> menuList =  SpringUtils.getBean(SysMenuMapper.class).selectMenuList(new SysMenu());
        RbacDictManager.setDictCache(PREMISSION_STRING, menuList.stream().collect(Collectors.toList()));
    }


    /**
     * 清空字典缓存数据
     */
    public void clearMenuCache()
    {
        RbacDictManager.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    public void resetMenuCache()
    {
        RbacDictManager.clearDictCache();
        loadingDictCache();
    }


    /**
     * 设置字典缓存
     *
     * @param key 参数键
     * @param dictData 字典数据列表
     */
    public static void setDictCache(String key, List<IBaseMenu> dictData)
    {
        SpringUtils.getBean(RedisCacheManager.class).setCacheObject(RedisCacheKey.SYS_MENU,key, dictData);
    }

    /**
     * 设置字典缓存
     *
     * @param key 参数键
     * @param dictData 字典数据列表
     */
    public static void setDictCache(String key, IBaseMenu dictData)
    {
        SpringUtils.getBean(RedisCacheManager.class).setCacheObject(RedisCacheKey.SYS_MENU,key, dictData);
    }

    /**
     * 获取字典缓存
     *
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public static List<IBaseMenu> getDictCache(String key)
    {
        JSONArray arrayCache = SpringUtils.getBean(RedisCacheManager.class).getCacheObject(RedisCacheKey.SYS_MENU,key);
        if (StringUtils.isNotNull(arrayCache))
        {
            return arrayCache.toList(IBaseMenu.class);
        }
        return null;
    }


    /**
     * 删除指定字典缓存
     *
     * @param key 字典键
     */
    public static void removeDictCache(String key)
    {
        SpringUtils.getBean(RedisCacheManager.class).deleteObject(RedisCacheKey.SYS_DICT,key);
    }


    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param permsTag 字典类型
     * @return 字典值
     */
    public static List<IBaseMenu> getMenuByPermsTag(String permsTag)
    {
        List<IBaseMenu> datas = getDictCache(PREMISSION_STRING);
        List<IBaseMenu> menuCol  = new ArrayList<>();
        if (StringUtils.isNotNull(datas)){
            for (IBaseMenu dict : datas){
               if(permsTag.equals(dict.getMenuPerms())){
                   String menuAncestorLabel = SpringUtils.getBean(ISysMenuService.class).getMenusAncestorLabel( dict );
                   dict.setMenuAncestorlabel(menuAncestorLabel);
                   menuCol.add( dict );
               }
            }
        }
        return menuCol;
    }



    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param permission 权限类型
     * @return 祖籍
     */
    public static String getMenuAncestorRemark(String permission)
    {
        String ancestorLabel = "";
        List<String> menuAncestorLabelList = Collections.synchronizedList(new ArrayList<>());
        List<IBaseMenu>  sysMenus =  RbacDictManager.getMenuByPermsTag(permission);
        if(sysMenus != null && sysMenus.size() > 0) {
            sysMenus.forEach(v -> {
                menuAncestorLabelList.add(v.getMenuAncestorlabel() == null ? "未找到" : v.getMenuAncestorlabel());
            });
        }
        ancestorLabel = sysMenus != null && sysMenus.size() == 0 ? "未找到配置项" : menuAncestorLabelList.toString();
        return ancestorLabel;
    }


    /**
     * 清空字典缓存
     */
    public static void clearDictCache()
    {
        Collection<String> keys = SpringUtils.getBean(RedisCacheManager.class).keys(RedisCacheKey.SYS_MENU + "*");
        Map<RedisCacheKey,Collection<String>> keyCollectionMap = new HashMap<>();
        keyCollectionMap.put(RedisCacheKey.SYS_MENU,keys);
        SpringUtils.getBean(RedisCacheManager.class).deleteObject(keyCollectionMap);
    }

}
