package com.njcn.rdms.module.system.service.permission;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.njcn.rdms.framework.common.enums.CommonStatusEnum;
import com.njcn.rdms.framework.common.util.json.JsonUtils;
import com.njcn.rdms.framework.common.util.object.BeanUtils;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuListReqVO;
import com.njcn.rdms.module.system.controller.admin.permission.vo.menu.MenuSaveVO;
import com.njcn.rdms.module.system.dal.dataobject.permission.MenuDO;
import com.njcn.rdms.module.system.dal.mysql.permission.MenuMapper;
import com.njcn.rdms.module.system.dal.redis.RedisKeyConstants;
import com.njcn.rdms.module.system.enums.permission.MenuRouteKindEnum;
import com.njcn.rdms.module.system.enums.permission.MenuTypeEnum;
import com.njcn.rdms.module.system.enums.permission.PermissionScopeTypeEnum;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.Objects;

import static com.njcn.rdms.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.njcn.rdms.framework.common.util.collection.CollectionUtils.convertList;
import static com.njcn.rdms.framework.common.util.collection.CollectionUtils.convertMap;
import static com.njcn.rdms.module.system.dal.dataobject.permission.MenuDO.ID_ROOT;
import static com.njcn.rdms.module.system.enums.ErrorCodeConstants.*;

/**
 * 菜单 Service 实现
 *
 * @author hongawen
 */
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {

    private static final String GLOBAL_SCOPE_TYPE = PermissionScopeTypeEnum.GLOBAL.getScopeType();
    private static final String OBJECT_SCOPE_TYPE = PermissionScopeTypeEnum.OBJECT.getScopeType();
    private static final String GLOBAL_OBJECT_TYPE = PermissionScopeTypeEnum.GLOBAL_OBJECT_TYPE;

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private PermissionService permissionService;


    @Override
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, allEntries = true)
    public Long createMenu(MenuSaveVO createReqVO) {
        String scopeType = StrUtil.blankToDefault(StrUtil.trim(createReqVO.getScopeType()), GLOBAL_SCOPE_TYPE);
        String objectType = OBJECT_SCOPE_TYPE.equals(scopeType) ? StrUtil.trim(createReqVO.getObjectType()) : GLOBAL_OBJECT_TYPE;
        // 校验父菜单存在
        validateParentMenu(createReqVO.getParentId(), null, scopeType, objectType);
        // 校验菜单（自己）
        validateMenuName(createReqVO.getParentId(), createReqVO.getName(), null,
                scopeType, objectType);
        validateMenuComponentName(createReqVO.getComponentName(), null,
                scopeType, objectType);
        validateMenuRoute(createReqVO);

        // 插入数据库
        MenuDO menu = BeanUtils.toBean(createReqVO, MenuDO.class);
        menu.setScopeType(scopeType);
        menu.setObjectType(objectType);
        initMenuProperty(menu);
        menuMapper.insert(menu);
        // 返回
        return menu.getId();
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            allEntries = true) // allEntries 清空所有缓存，因为 permission 如果变更，涉及到新老两个 permission。直接清理，简单有效
    public void updateMenu(MenuSaveVO updateReqVO) {
        // 校验更新的菜单是否存在
        MenuDO menu = menuMapper.selectById(updateReqVO.getId());
        if (menu == null) {
            throw exception(MENU_NOT_EXISTS);
        }
        // 校验父菜单存在
        validateParentMenu(updateReqVO.getParentId(), updateReqVO.getId(),
                menu.getScopeType(), menu.getObjectType());
        // 校验菜单（自己）
        validateMenuName(updateReqVO.getParentId(), updateReqVO.getName(), updateReqVO.getId(),
                menu.getScopeType(), menu.getObjectType());
        validateMenuComponentName(updateReqVO.getComponentName(), updateReqVO.getId(),
                menu.getScopeType(), menu.getObjectType());
        validateMenuRoute(updateReqVO);

        // 更新到数据库
        MenuDO updateObj = BeanUtils.toBean(updateReqVO, MenuDO.class);
        updateObj.setScopeType(menu.getScopeType());
        updateObj.setObjectType(menu.getObjectType());
        initMenuProperty(updateObj);
        menuMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            allEntries = true) // allEntries 清空所有缓存，因为此时不知道 id 对应的 permission 是多少。直接清理，简单有效
    public void deleteMenu(Long id) {
        // 校验是否还有子菜单
        if (menuMapper.selectCountByParentId(id) > 0) {
            throw exception(MENU_EXISTS_CHILDREN);
        }
        // 校验删除的菜单是否存在
        if (menuMapper.selectById(id) == null) {
            throw exception(MENU_NOT_EXISTS);
        }
        // 标记删除
        menuMapper.deleteById(id);
        // 删除授予给角色的权限
        permissionService.processMenuDeleted(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            allEntries = true) // allEntries 清空所有缓存，因为 Spring Cache 不支持按照 ids 批量删除
    public void deleteMenuList(List<Long> ids) {
        // 校验是否还有子菜单
        ids.forEach(id -> {
            if (menuMapper.selectById(id) == null) {
                throw exception(MENU_NOT_EXISTS);
            }
            if (menuMapper.selectCountByParentId(id) > 0) {
                throw exception(MENU_EXISTS_CHILDREN);
            }
        });

        // 标记删除
        menuMapper.deleteByIds(ids);
        // 删除授予给角色的权限
        ids.forEach(id -> permissionService.processMenuDeleted(id));
    }

    @Override
    public List<MenuDO> getMenuList() {
        return getMenuList(new MenuListReqVO(), GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public List<MenuDO> filterDisableMenus(List<MenuDO> menuList) {
        if (CollUtil.isEmpty(menuList)){
            return Collections.emptyList();
        }
        Map<Long, MenuDO> menuMap = convertMap(menuList, MenuDO::getId);

        // 遍历 menu 菜单，查找不是禁用的菜单，添加到 enabledMenus 结果
        List<MenuDO> enabledMenus = new ArrayList<>();
        Set<Long> disabledMenuCache = new HashSet<>(); // 存下递归搜索过被禁用的菜单，防止重复的搜索
        for (MenuDO menu : menuList) {
            if (isMenuDisabled(menu, menuMap, disabledMenuCache)) {
                continue;
            }
            enabledMenus.add(menu);
        }
        return enabledMenus;
    }

    private boolean isMenuDisabled(MenuDO node, Map<Long, MenuDO> menuMap, Set<Long> disabledMenuCache) {
        // 如果已经判定是禁用的节点，直接结束
        if (disabledMenuCache.contains(node.getId())) {
            return true;
        }

        // 1. 先判断自身是否禁用
        if (CommonStatusEnum.isDisable(node.getStatus())) {
            disabledMenuCache.add(node.getId());
            return true;
        }

        // 2. 遍历到 parentId 为根节点，则无需判断
        Long parentId = node.getParentId();
        if (ObjUtil.equal(parentId, ID_ROOT)) {
            return false;
        }

        // 3. 继续遍历 parent 节点
        MenuDO parent = menuMap.get(parentId);
        if (parent == null || isMenuDisabled(parent, menuMap, disabledMenuCache)) {
            disabledMenuCache.add(node.getId());
            return true;
        }
        return false;
    }

    @Override
    public List<MenuDO> getMenuList(MenuListReqVO reqVO) {
        return getMenuList(reqVO, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public List<MenuDO> getMenuList(MenuListReqVO reqVO, String scopeType, String objectType) {
        return menuMapper.selectList(reqVO, scopeType, objectType);
    }

    @Override
    @Cacheable(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST, key = "#permission")
    public List<Long> getMenuIdListByPermissionFromCache(String permission) {
        return getMenuIdListByPermissionFromCache(permission, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    @Cacheable(value = RedisKeyConstants.PERMISSION_MENU_ID_LIST,
            key = "#permission + ':' + #scopeType + ':' + #objectType")
    public List<Long> getMenuIdListByPermissionFromCache(String permission, String scopeType, String objectType) {
        List<MenuDO> menus = menuMapper.selectListByPermission(permission, scopeType, objectType);
        return convertList(menus, MenuDO::getId);
    }

    @Override
    public MenuDO getMenu(Long id) {
        return menuMapper.selectById(id);
    }

    @Override
    public List<MenuDO> getMenuList(Collection<Long> ids) {
        // 当 ids 为空时，返回一个空的实例对象
        if (CollUtil.isEmpty(ids)) {
            return Lists.newArrayList();
        }
        List<MenuDO> menus = menuMapper.selectByIds(ids);
        menus.removeIf(menu -> !matchesScope(menu, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE));
        return menus;
    }

    @Override
    public List<MenuDO> getMenuList(Collection<Long> ids, String scopeType, String objectType) {
        if (CollUtil.isEmpty(ids)) {
            return Lists.newArrayList();
        }
        List<MenuDO> menus = menuMapper.selectByIds(ids);
        menus.removeIf(menu -> !matchesScope(menu, scopeType, objectType));
        return menus;
    }

    @Override
    public void validateMenuList(Collection<Long> ids) {
        validateMenuList(ids, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @Override
    public void validateMenuList(Collection<Long> ids, String scopeType, String objectType) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        List<MenuDO> menus = menuMapper.selectByIds(ids);
        Map<Long, MenuDO> menuMap = convertMap(menus, MenuDO::getId);
        ids.forEach(id -> {
            MenuDO menu = menuMap.get(id);
            if (menu == null) {
                throw exception(MENU_NOT_EXISTS);
            }
            if (!matchesScope(menu, scopeType, objectType)) {
                throw exception(MENU_SCOPE_NOT_MATCH, menu.getName());
            }
            if (CommonStatusEnum.isDisable(menu.getStatus())) {
                throw exception(MENU_NOT_ENABLE, menu.getName());
            }
        });
    }

    /**
     * 校验父菜单是否合法
     * <p>
     * 1. 不能设置自己为父菜单
     * 2. 父菜单不存在
     * 3. 父菜单必须是 {@link MenuTypeEnum#MENU} 菜单类型
     *
     * @param parentId 父菜单编号
     * @param childId  当前菜单编号
     */
    @VisibleForTesting
    void validateParentMenu(Long parentId, Long childId) {
        validateParentMenu(parentId, childId, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @VisibleForTesting
    void validateParentMenu(Long parentId, Long childId, String scopeType, String objectType) {
        if (parentId == null || ID_ROOT.equals(parentId)) {
            return;
        }
        // 不能设置自己为父菜单
        if (parentId.equals(childId)) {
            throw exception(MENU_PARENT_ERROR);
        }
        MenuDO menu = menuMapper.selectById(parentId);
        // 父菜单不存在
        if (menu == null) {
            throw exception(MENU_PARENT_NOT_EXISTS);
        }
        if (!matchesScope(menu, scopeType, objectType)) {
            throw exception(MENU_SCOPE_NOT_MATCH, menu.getName());
        }
        // 父菜单必须是目录或者菜单类型
        if (!MenuTypeEnum.DIR.getType().equals(menu.getType())
                && !MenuTypeEnum.MENU.getType().equals(menu.getType())) {
            throw exception(MENU_PARENT_NOT_DIR_OR_MENU);
        }
    }

    /**
     * 校验菜单是否合法
     * <p>
     * 1. 校验相同父菜单编号下，是否存在相同的菜单名
     *
     * @param name     菜单名字
     * @param parentId 父菜单编号
     * @param id       菜单编号
     */
    @VisibleForTesting
    void validateMenuName(Long parentId, String name, Long id) {
        validateMenuName(parentId, name, id, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @VisibleForTesting
    void validateMenuName(Long parentId, String name, Long id, String scopeType, String objectType) {
        MenuDO menu = menuMapper.selectByParentIdAndName(parentId, name, scopeType, objectType);
        if (menu == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的菜单
        if (id == null) {
            throw exception(MENU_NAME_DUPLICATE);
        }
        if (!menu.getId().equals(id)) {
            throw exception(MENU_NAME_DUPLICATE);
        }
    }

    /**
     * 校验菜单组件名是否合法
     *
     * @param componentName 组件名
     * @param id            菜单编号
     */
    @VisibleForTesting
    void validateMenuComponentName(String componentName, Long id) {
        validateMenuComponentName(componentName, id, GLOBAL_SCOPE_TYPE, GLOBAL_OBJECT_TYPE);
    }

    @VisibleForTesting
    void validateMenuComponentName(String componentName, Long id, String scopeType, String objectType) {
        if (StrUtil.isBlank(componentName)) {
            return;
        }
        MenuDO menu = menuMapper.selectByComponentName(componentName, scopeType, objectType);
        if (menu == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的菜单
        if (id == null) {
            throw exception(MENU_COMPONENT_NAME_DUPLICATE);
        }
        if (!menu.getId().equals(id)) {
            throw exception(MENU_COMPONENT_NAME_DUPLICATE);
        }
    }

    @VisibleForTesting
    void validateMenuRoute(MenuSaveVO reqVO) {
        if (reqVO == null || MenuTypeEnum.BUTTON.getType().equals(reqVO.getType())) {
            return;
        }

        MenuRouteKindEnum routeKind = MenuRouteKindEnum.valueOfKind(reqVO.getRouteKind());
        if (StrUtil.isNotBlank(reqVO.getRouteKind()) && routeKind == null) {
            throw exception(MENU_ROUTE_KIND_INVALID);
        }

        String routePropsJson = StrUtil.trim(reqVO.getRoutePropsJson());
        if (StrUtil.isBlank(routePropsJson)) {
            if (MenuRouteKindEnum.IFRAME.equals(routeKind)) {
                throw exception(MENU_ROUTE_IFRAME_URL_REQUIRED);
            }
            return;
        }

        Object routeProps = JsonUtils.parseObjectQuietly(routePropsJson, new TypeReference<Object>() {
        });
        if (routeProps == null) {
            throw exception(MENU_ROUTE_PROPS_JSON_INVALID);
        }
        if (!MenuRouteKindEnum.IFRAME.equals(routeKind)) {
            return;
        }

        if (!(routeProps instanceof Map<?, ?> routePropsMap)) {
            throw exception(MENU_ROUTE_PROPS_JSON_INVALID);
        }
        Object url = routePropsMap.get("url");
        if (!(url instanceof String urlString) || StrUtil.isBlank(urlString)) {
            throw exception(MENU_ROUTE_IFRAME_URL_REQUIRED);
        }
    }

    /**
     * 初始化菜单的通用属性。
     * <p>
     * 例如说，只有目录或者菜单类型的菜单，才设置 icon
     *
     * @param menu 菜单
     */
    private void initMenuProperty(MenuDO menu) {
        menu.setRouteKind(normalizeRouteKind(menu.getRouteKind()));
        menu.setRoutePropsJson(StrUtil.blankToDefault(StrUtil.trim(menu.getRoutePropsJson()), null));
        // 菜单为按钮类型时，无需 component、icon、path 属性，进行置空
        if (MenuTypeEnum.BUTTON.getType().equals(menu.getType())) {
            menu.setComponent("");
            menu.setComponentName("");
            menu.setIcon("");
            menu.setPath("");
            menu.setRouteKind(null);
            menu.setRoutePropsJson(null);
        }
    }

    private String normalizeRouteKind(String routeKind) {
        MenuRouteKindEnum routeKindEnum = MenuRouteKindEnum.valueOfKind(routeKind);
        return routeKindEnum != null ? routeKindEnum.getKind() : null;
    }

    private boolean matchesScope(MenuDO menu, String scopeType, String objectType) {
        return menu != null
                && (scopeType == null || Objects.equals(scopeType, menu.getScopeType()))
                && (objectType == null || Objects.equals(objectType, menu.getObjectType()));
    }

}
