package com.elephant.framework.galaxy.aroad.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.elephant.framework.galaxy.aroad.module.system.entity.Menu;
import com.elephant.framework.galaxy.aroad.module.system.entity.RoleMenu;
import com.elephant.framework.galaxy.aroad.module.system.mapper.MenuMapper;
import com.elephant.framework.galaxy.aroad.module.system.mapper.RoleMenuMapper;
import com.elephant.framework.galaxy.aroad.module.system.service.MenuService;
import com.elephant.framework.galaxy.aroad.module.system.vo.MenuVO;
import com.elephant.framework.galaxy.aroad.exception.GlobalExceptionEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elephant.framework.galaxy.aroad.response.R;
import lombok.AllArgsConstructor;
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.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author wangjian
 * @since 2019-02-21
 */
@Service
@AllArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    private final RoleMenuMapper roleMenuMapper;

    @Override
    @Cacheable(value = "menu_details", key = "#roleId  + '_menu'")
    public List<MenuVO> findMenuByRoleId(Integer roleId) {
        return baseMapper.listMenusByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "menu_details", allEntries = true)
    public R removeMenuById(Integer id) {
        // 查询父节点为当前节点的节点
        List<Menu> menuList = this.list(Wrappers.<Menu>query()
                .lambda().eq(Menu::getParentId, id));
        if (CollUtil.isNotEmpty(menuList)) {
            return new R(GlobalExceptionEnum.MENU_HAS_CHILD);
        }

        roleMenuMapper
                .delete(Wrappers.<RoleMenu>query()
                        .lambda().eq(RoleMenu::getMenuId, id));

        //删除当前菜单及其子菜单
        return new R(this.removeById(id));
    }

    @Override
    @CacheEvict(value = "menu_details", allEntries = true)
    public Boolean updateMenuById(Menu sysMenu) {
        return this.updateById(sysMenu);
    }
}
