/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.SysCache;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.modules.system.entity.Menu;
import org.springblade.modules.system.entity.RoleMenu;
import org.springblade.modules.system.mapper.RoleMenuMapper;
import org.springblade.modules.system.service.IMenuService;
import org.springblade.modules.system.service.IRoleMenuService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

	@Override
	public RoleMenu getByRoleIdMenuId(String roleId, Long menuId) {
		return getOne(new QueryWrapper<>(new RoleMenu()).lambda().eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMenuId, menuId));
	}

	@Override
	public boolean checkMenuByMenuCodeAndRoles(String code, IMenuService menuService) {
		if ("administrator,admin".contains(AuthUtil.getUserRole())){
			return true;
		}
		boolean hasMenu = false;
		Menu menu = menuService.getMenuByCode(code + "_view");
		String[] roles = AuthUtil.getUser().getRoleId().split(",");
		if (roles.length == 1){
			RoleMenu roleMenu = this.getByRoleIdMenuId(roles[0], menu.getId());
			hasMenu = roleMenu != null;
		}else{
			for (int i = 0; i < roles.length; i++) {
				RoleMenu roleMenu = this.getByRoleIdMenuId(roles[i], menu.getId());
				hasMenu = hasMenu || roleMenu != null;
			}
		}

		return hasMenu;
	}


}
