package com.pj.project.re_role_menu;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.project.re_role_menu.dto.AssignPermissionsDto;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service: re_role_menu -- app用户菜单中间表
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ReRoleMenuService extends ServiceImpl<ReRoleMenuMapper, ReRoleMenu> implements IService<ReRoleMenu>{

	/** 底层 Mapper 对象 */
	@Autowired
	ReRoleMenuMapper reRoleMenuMapper;
	/** 方法抽取,优化代码 */
	@Autowired
	private MethodRoleMenuService methodRoleMenuService;

	/** 增 */
	void add(ReRoleMenu r){
		save(r);
	}

	/** 删 */
	void delete(Long id){
		removeById(id);
	}

	/** 改 */
	void update(ReRoleMenu r){
		updateById(r);

	}

	/** 查 */
	ReRoleMenu getById(Long id){
		return super.getById(id);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */
	List<ReRoleMenu> getList(SoMap so,Integer appRoleId) {
		so.set("app_role_id",appRoleId);
		return reRoleMenuMapper.getList(so);
	}


	/** 给app角色分配权限 */
	boolean assignPermissions(AssignPermissionsDto assignPermissionsDto){
		//取出数据
		Long roleId = assignPermissionsDto.getRoleId();
		//app_menu的主键进行去重
		List<Long> permissionsDtoList = assignPermissionsDto.getList().stream().distinct().collect(Collectors.toList());
		//情况1:传进来的集合为空,默认删除该职务下属的所有权限
		//if(permissionsDtoList.size() == 0){
			//删除所有权限
			//List<Long> perList = methodRoleMenuService.getPerList(roleId);
			//清除
			//int i = reRoleMenuMapper.deleteBatchIds(perList);
			//return i == perList.size();
			//int i = reRoleMenuMapper.delete(new LambdaQueryWrapper<ReRoleMenu>().eq(ReRoleMenu::getAppRoleId, roleId));
			//return true;
		//}
		//情况2: 传进来的集合不为空
		//2.1 先清除该职务的权限
		//List<Long> perList = methodRoleMenuService.getPerList(roleId);
		//执行清除
		//int i = reRoleMenuMapper.deleteBatchIds(perList);
		//if(i != perList.size())throw new RuntimeException("权限分配失败Ⅰ!");
		int i = reRoleMenuMapper.delete(new LambdaQueryWrapper<ReRoleMenu>().eq(ReRoleMenu::getAppRoleId, roleId));
		//2.2 再添加新的权限给到该职务
		//定义计数器
		int count = 0;
		for(Long item : permissionsDtoList){
			int insert = reRoleMenuMapper.insert(new ReRoleMenu(roleId, item));
			count += insert;
		}
		if(count != permissionsDtoList.size())throw new RuntimeException("权限分配失败Ⅱ!");

		return count == permissionsDtoList.size();
	}


}
