package com.hotent.uc.manager.impl;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hotent.base.datasource.DatabaseContext;
import com.hotent.base.feign.PortalFeignService;
import com.hotent.base.manager.CommonManager;
import com.hotent.base.query.*;
import com.hotent.base.util.*;
import com.hotent.base.util.Base64;
import com.hotent.uc.exception.BaseException;
import com.hotent.uc.manager.*;
import com.hotent.uc.model.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import poi.util.ExcelUtil;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.cache.annotation.CacheEvict;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.constants.CacheKeyConst;
import com.hotent.uc.dao.RoleDao;
import com.hotent.uc.exception.RequiredException;
import com.hotent.uc.params.role.RoleVo;
import com.hotent.uc.params.user.UserVo;
import com.hotent.uc.util.OrgUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * <pre>
 * 描述：角色管理 处理实现类
 * 构建组：eip平台-bpmx-platform
 * 作者:ray
 * 邮箱:zhangyg@jee-soft.cn
 * 日期:2016-06-30 10:28:04
 * 版权：广州宏天软件有限公司
 * </pre>
 */
@Service
public class RoleManagerImpl extends BaseManagerImpl <RoleDao, Role> implements RoleManager {
	@Autowired
	UserRoleManager userRoleManager;
	@Autowired
	UserManager userService;
	@Autowired
	OrgManager orgService;
	@Autowired
	UserRoleManager userRoleService;
	@Resource
	OrgRoleManager orgRoleManager;
	@Autowired
	DatabaseContext databaseContext;
	@Autowired
	CommonManager commonManager;
    @Resource
    PortalFeignService portalFeignService;

	@Override
	public Role getByAlias(String code) {
		return baseMapper.getByCode(code);
	}

	@Override
	public List<Role> getListByUserId(String userId) {
		Set<String> roleIds = gatherParentOrgRoles("userId", userId);
		return baseMapper.getListByUserId(userId, roleIds);
	}

	@Override
	public List<Role> getListByAccount(String account) {
		List<Role> roles =  baseMapper.getListByAccount(account);
		Set<String> roleIds = gatherParentOrgRoles("account", account);
		List<Role> orgRoles = baseMapper.getByIds(roleIds);
		Set<String> byAccount = new HashSet<>();
		roles.parallelStream().forEach(role -> {
			byAccount.add(role.getId());
		});
		orgRoles.parallelStream().forEach(role -> {
			if (!byAccount.contains(role.getId())) {
				roles.add(role);
			}
		});
		return roles;
	}

	/**
	 * 返回当前组织和上级组织的角色列表
	 * @return 返回一个角色ID集合，表示用户所在的组织持有或者继承有这些角色
	 * */
	private Set<String> gatherParentOrgRoles(String field, String userCode){
		List<Org> orgs = null;
		if ("account".equals(field)) {
			try {
				orgs = orgService.getOrgListByAccount(userCode);
			} catch (Exception e) {
				return new HashSet<>();
			}
		}else if("userId".equals(field)){
			orgs = orgService.getOrgListByUserId(userCode);
		}
		if (BeanUtils.isEmpty(orgs)) {
			return new HashSet<>();
		}
		Set<String> roleIds = new HashSet<>();
		Set<String> orgGather = new HashSet<>();
		for (Org org : orgs) {
			if (orgGather.contains(org.getId())) {
				continue;
			}
			List<OrgRole> orgRoles = orgRoleManager.getByOrgId(org.getId());
			orgRoles.parallelStream().forEach(orgRole -> {
				roleIds.add(orgRole.getRoleId());
			});
			Org curOrg = org;
			while (StringUtil.isNotEmpty(curOrg.getParentId()) && !"0".equals(curOrg.getParentId()) && !orgGather.contains(curOrg.getParentId())){
				curOrg = orgService.get(curOrg.getParentId());
				List<OrgRole> parentRoles = orgRoleManager.getByOrgId(curOrg.getId());
				parentRoles.parallelStream().forEach(orgRole -> {
					if(orgRole.getIsInherit() == 1){
						roleIds.add(orgRole.getRoleId());
					}
				});
				orgGather.add(curOrg.getId());
			}
			//标记这个组织和它的上级已经被收集了
			orgGather.add(org.getId());
		}
		if (roleIds.isEmpty()) {
			return new HashSet<>();
		}
		return roleIds;
	}

    @Transactional
	public void remove(String roleId) {
		super.remove(roleId);
		// 删除角色跟用户的关系
		userRoleManager.removeByRoleId(roleId,LocalDateTime.now());
		delUserMenuCache();
	}

    private void delUserMenuCache() {
    	RoleManagerImpl bean = AppUtil.getBean(getClass());
    	bean.removeUserMenuCache();
    }

    @CacheEvict(value = CacheKeyConst.EIP_SYS_USERMENU, allEntries = true)
    protected void removeUserMenuCache() {}

    public void delUserMenuCacheByUserId(String userId) {
    	RoleManagerImpl bean = AppUtil.getBean(getClass());
    	bean.removeUserMenuCacheByUserIde(userId);
    	// 清空用户组缓存
    	userService.removeUserGroupsCache(userId);
    }

	/**
	 * 获取该组织下的角色
	 */
	@Override
	public PageList<Role> queryRoleByExtOrgPath(QueryFilter queryFilter, String path) {
		PageBean pageBean = queryFilter.getPageBean();
		IPage<Role> result = baseMapper.queryRoleByExtOrgPath(convert2IPage(pageBean), convert2Wrapper(queryFilter, currentModelClass()), path);
		return new PageList<Role>(result);
	}

	@Override
	public List<Role> getRoles(List<String> codes) {
		QueryWrapper<Role> wrapper = new QueryWrapper<>();
		wrapper.in("CODE_",codes);
		return this.list(wrapper);
	}

	@CacheEvict(value = CacheKeyConst.EIP_SYS_USERMENU, key = "#userId")
    protected void removeUserMenuCacheByUserIde(String userId) {}

	@Override
    @Transactional
	public CommonResult<String> addRole(RoleVo roleVo)
			throws Exception {
		if(StringUtil.isEmpty(roleVo.getName())){
			throw new RequiredException("添加角色失败，角色名称【name】必填！");
		}
		if(StringUtil.isEmpty(roleVo.getCode())){
			throw new RequiredException("添加角色失败，角色编码【code】必填！");
		}
		if(baseMapper.getCountByCode(roleVo.getCode())>0){
			return new CommonResult<String>(false, "添加角色失败，角色编码【"+roleVo.getCode()+"】在系统中已存在！", "");
		}
		Role role = RoleVo.parse(roleVo);
		role.setUpdateTime(LocalDateTime.now());
		role.setId(UniqueIdUtil.getSuid());
		create(role);
		return new CommonResult<String>(true, "添加角色成功！", "");
	}

	@Override
    @Transactional
	public CommonResult<String> deleteRole(String codes) throws Exception {
		String[] codeArray = codes.split(",");
		StringBuilder str = new StringBuilder();
		boolean isTrue = false;
		for (String code : codeArray) {
			Role role = getByAlias(code);
			if(BeanUtils.isNotEmpty(role)){
				if (OrgUtil.checkUserGruopIsUserRel("role", role.getId())) {
					str.append("编码为【"+code+"】的角色为汇报节点不能删除，");
					continue;
				}else{
					remove(role.getId());
                    portalFeignService.removeByRoleAlias(code);
					isTrue = true;
				}
			}else{
				str.append(code);
				str.append("，");
			}
		}
		String msg = StringUtil.isEmpty(str.toString())?"删除角色成功！":"部分删除失败，角色编码："+str.toString()+"不存在！";
		delUserMenuCache();
		return new CommonResult<String>(isTrue, msg, str.toString());
	}

	@Override
    @Transactional
	public CommonResult<String> deleteRoleByIds(String ids) throws Exception {
		String[] idArray = ids.split(",");
		StringBuilder str = new StringBuilder();
		boolean isTrue = false;
		for (String id : idArray) {
			Role role = get(id);
			if(BeanUtils.isNotEmpty(role)){
				remove(role.getId());
				portalFeignService.removeByRoleAlias(role.getCode());
				clearRoleCahceMenu(role.getCode());
				isTrue = true;
			}else{
				str.append(id);
				str.append("，");
			}
		}
		String msg = StringUtil.isEmpty(str.toString())?"删除角色成功！":"部分删除失败，角色编码："+str.toString()+"不存在！";
		return new CommonResult<String>(isTrue, msg, str.toString());
	}


	@Override
    @Transactional
	public CommonResult<String> updateRole(RoleVo roleVo)
			throws Exception {
		if(StringUtil.isEmpty(roleVo.getCode())){
			throw new RequiredException("更新角色失败，角色编码【code】必填！");
		}
		Role role = baseMapper.getByCode(roleVo.getCode());
		if(BeanUtils.isEmpty(role)){
			return new CommonResult<String>(false, "更新角色失败，角色编码【"+roleVo.getCode()+"】不存在！", "");
		}
		if(StringUtil.isNotEmpty(roleVo.getName())){
			role.setName(roleVo.getName());
		}
		if(roleVo.getDescription()!=null){
			role.setDescription(roleVo.getDescription());
		}
		if(roleVo.getEnabled()!=null){
			//如果角色的禁用状态发生了变化，则删除该角色下所有用户的菜单缓存
			if (!roleVo.getEnabled().equals(role.getEnabled())) {
				clearRoleCahceMenu(role.getCode());
			}
			role.setEnabled(roleVo.getEnabled());
		}
		this.update(role);
		return new CommonResult<String>(true, "更新角色成功！", "");
	}

	/**
	 * 根据角色编码查找角色里面的用户，清除其缓存的菜单资源
	 * @param roleCode
	 * @throws Exception
	 */
    @Transactional
	private void clearRoleCahceMenu(String roleCode) throws Exception{
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.addFilter("r.CODE_",roleCode, QueryOP.EQUAL, FieldRelation.AND, "group_code");
		Page<User> list = (Page<User>)userService.getRoleUserQuery(filter);
		for (User userRole : list.getRecords()) {
			delUserMenuCacheByUserId(userRole.getUserId());
		}
	}

	@Override
	public Role getRole(String code) throws Exception {
		Role role = baseMapper.getByCode(code);
		if(BeanUtils.isEmpty(role)){
			throw new RequiredException("角色编码【"+code+"】不存在！");
		}
		return role;
	}

	@Override
    @Transactional
	public CommonResult<String> saveUserRole(String code, String accounts)
			throws Exception {
		Role role = baseMapper.getByCode(code);
		if(BeanUtils.isEmpty(role)){
			throw new RequiredException("角色编码【"+code+"】不存在！");
		}
		String[] accountArray = accounts.split(",");
		StringBuilder values = new StringBuilder();
		boolean isFirst = true;
		int size = 0;
		String msg = "分配用户成功！";
		for (String account : accountArray) {
			User user = userService.getByAccount(account);
			if(BeanUtils.isNotEmpty(user)){
				addUserRole(user.getUserId(), role.getId());
				size++;
			}else{
				if(isFirst){
					isFirst = false;
				}else{
					values.append("，");
				}
				values.append(account);
			}
		}
		if(size==0){
			msg = "未分配任何用户！";
		}else if(size>0&&size<accountArray.length){
			msg = "部分分配成功！";
		}
		return new CommonResult<String>(true, msg, StringUtil.isNotEmpty(values.toString())?"账号：【"+values.toString()+"】不存在！":"");
	}

	@Override
	@Transactional
	public CommonResult<String> saveUserRoles(String codes, String account) {
		if(StringUtil.isEmpty(codes)){
			throw new RequiredException("角色编码【"+codes+"】必填！");
		}
		String[] codeArr = codes.split(",");
		for (String code : codeArr) {
			Role role = baseMapper.getByCode(code);
			if(BeanUtils.isEmpty(role)){
				throw new RequiredException("角色编码【"+code+"】不存在！");
			}
			StringBuilder values = new StringBuilder();
			boolean isFirst = true;
			User user = null;
			try {
				user = userService.getByAccount(account);
			} catch (Exception e) {
				throw new RequiredException("账号【"+account+"】无效！");
			}
			if(BeanUtils.isNotEmpty(user)){
				addUserRole(user.getUserId(), role.getId());
			}else{
				if(isFirst){
					isFirst = false;
				}else{
					values.append("，");
				}
				values.append(account);
			}
		}

		return new CommonResult<String>(true, "分配角色成功");
	}
	@Override
    @Transactional
	public CommonResult<String> addUserRoleByOrg(String code,
			String orgCodes) throws Exception {
		Role role = baseMapper.getByCode(code);
		if(BeanUtils.isEmpty(role)){
			throw new RequiredException("角色编码【"+code+"】不存在！");
		}
		String[] orgCodesArray = orgCodes.split(",");
		StringBuilder values = new StringBuilder();
		boolean isFirst = true;
		int size = 0;
		String msg = "分配用户成功！";
		for (String orgCode : orgCodesArray) {
			Org org = orgService.getByCode(orgCode);
			if(BeanUtils.isNotEmpty(org)){
				List<User> users = userService.getUserListByOrgId(org.getId());
				for (User user : users) {
					addUserRole(user.getUserId(), role.getId());
				}
				size++;
			}else{
				if(isFirst){
					isFirst = false;
				}else{
					values.append("，");
				}
				values.append(orgCode);
			}

		}
		if(size==0){
			msg = "未分配任何用户！";
		}else if(size>0&&size<orgCodesArray.length){
			msg = "部分分配成功！";
		}
		return new CommonResult<String>(true, msg, StringUtil.isNotEmpty(values.toString())?"组织编码：【"+values.toString()+"】不存在！":"");
	}

	@Override
    @Transactional
	public CommonResult<String> removeUserRole(String code,
			String accounts) throws Exception {

		Role role = baseMapper.getByCode(code);
		if(BeanUtils.isEmpty(role)){
			throw new RequiredException("角色编码【"+code+"】不存在！");
		}
		String[] accountArray = accounts.split(",");
		int size = 0;
		String msg = "移除用户成功！";
		for (String account : accountArray) {
			User user = userService.getByAccount(account);
			if(BeanUtils.isNotEmpty(user)){
				UserRole userRole = userRoleManager.getByRoleIdUserId(role.getId(), user.getId());
				if(BeanUtils.isNotEmpty(userRole)){
					userRoleManager.remove(userRole.getId());
					size++;
					delUserMenuCacheByUserId(userRole.getUserId());
				}
			}
		}
		if(size==0){
			msg = "未移除任何用户！";
		}else if(size>0&&size<accountArray.length){
			msg = "部分移除成功！";
		}
		return new CommonResult<String>(true, msg, "");
	}

	@Override
	public List<UserVo> getUsersByRoleCode(String codes) throws Exception {
		if(StringUtil.isEmpty(codes)){
			throw new RequiredException("角色编码不能为空！");
		}
		List<User> list = new ArrayList<User>();
		String[] codeArray = codes.split(",");
		for (String code : codeArray) {
			List<User> users =userService.getUserListByRoleCode(code);
			if(BeanUtils.isNotEmpty(users)){
				list.addAll(users);
			}
			//赋予某个组织角色
			List<OrgRole> orgRoles = orgRoleManager.getByRoleCode(code);
			if (BeanUtils.isNotEmpty(orgRoles)) {
				Set<String> orgIds = new HashSet<>();
				for (OrgRole orgRole : orgRoles) {
					orgIds.add(orgRole.getOrgId());
				}
				List<User> orgUsers = orgService.getUsersByOrgIds(orgIds, false);
				if (BeanUtils.isNotEmpty(orgUsers)) {
					list.addAll(orgUsers);
				}
			}
		}
		if(BeanUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		OrgUtil.removeDuplicate(list);
		return OrgUtil.convertToUserVoList(list);
	}

	/**
	 * 获取角色ids（多个）中的角色
	 * @param roleIds
	 */
	@Override
	public List<Role> getRoleByIds(List<String> roleIds) throws Exception {
		List<Role> orgRoles = baseMapper.getByIds(roleIds);
		return orgRoles;
	}

	@Override
	public List<Map<String, Object>> getRoleByIdsAndExtOrgId(List<String> roleIds, String orgPath) throws Exception {
		List<Map<String, Object>> orgRoles = baseMapper.getRoleByIdsAndExtOrgId(roleIds, orgPath);
		return orgRoles;
	}

    @Transactional
	private void addUserRole(String userId,String roleId){
		if (userRoleService.getByRoleIdUserId(roleId, userId) != null) return;

		UserRole userRole = new UserRole();
		userRole.setId(UniqueIdUtil.getSuid());
		userRole.setUserId(userId);
		userRole.setRoleId(roleId);
		userRoleService.create(userRole);
		delUserMenuCacheByUserId(userRole.getUserId());
	}

	@Override
	public List<Role> getOrgRoleList(Map<String, Object> params) {
		return baseMapper.getOrgRoleList(params);
	}

	@Override
    @Transactional
	public CommonResult<String> forbiddenRoles(String codes) throws Exception {
		String str = forbOrActiveRole(codes, 0);
		String msg = StringUtil.isEmpty(str)?"禁用角色成功！":"部分禁用失败，角色编码："+str+"不存在！";
		return new CommonResult<String>(true, msg, str);
	}

	@Override
    @Transactional
	public CommonResult<String> activateRoles(String codes) throws Exception {
		String str = forbOrActiveRole(codes, 1);
		String msg = StringUtil.isEmpty(str)?"激活角色成功！":"部分激活失败，角色编码："+str+"不存在！";
		return new CommonResult<String>(true, msg, str);
	}

    @Transactional
	private String forbOrActiveRole(String codes,Integer enabled) throws SQLException{
		String[] codeArray = codes.split(",");
		StringBuilder str = new StringBuilder();
		for (String code : codeArray) {
			Role role = getByAlias(code);
			if(BeanUtils.isNotEmpty(role)){
				role.setEnabled(enabled);
				this.update(role);
			}else{
				str.append(code);
				str.append("，");
			}
		}
		return str.toString();
	}

	@Override
	public List<Role> getRoleByTime(String btime, String etime)
			throws Exception {
		QueryFilter queryFilter = OrgUtil.getDataByTimeFilter(btime, etime);
		return this.queryNoPage(queryFilter);
	}

	@Override
    @Transactional
	public Integer removeUserRolePhysical() throws Exception {
		return userRoleManager.removePhysical();
	}

	@Override
	public CommonResult<Boolean> isCodeExist(String code) throws Exception {
		Role role = baseMapper.getByCode(code);
		boolean isExist = BeanUtils.isNotEmpty(role);
		return new CommonResult<Boolean>(isExist, isExist?"该角色编码已存在！":"", isExist);
	}

	/**
	 * 根据角色别名获取除这个角色之外的所有角色
	 * @param code
	 * @return
	 */
	@Override
	public List<Role> getOrgRoleListNotCode(String code){
		return baseMapper.getOrgRoleListNotCode(code);
	}


	@Override
    @Transactional
	public Integer removePhysical() {
		return baseMapper.removePhysical();
	}

	@Transactional
	public Boolean importRoleFile(MultipartFile file){
		List<RoleVo> list = ExcelUtil.readExcel(RoleVo.class,file);
		List<RoleVo> roleVoList = new ArrayList<>();
		List<RoleVo> checkList = new ArrayList<>();
		if(BeanUtils.isNotEmpty(list)){
			if (!validateAllRole(list)) {
				String message = "校验失败，请检查excel数据是否正确。";
				throw new BaseException(message);
			}
			for (RoleVo roleVo : list) {
				roleVoList.add(roleVo);
				Role role = baseMapper.getAllByCode(roleVo.getCode());
				if(BeanUtils.isNotEmpty(role)){
					checkList.add(roleVo);
				}
			}
			if(checkList.size() > 0){return false;}
			for (RoleVo roleVo : roleVoList) {
				Role nrole = RoleVo.parse(roleVo);
				nrole.setId(UniqueIdUtil.getSuid());
				this.create(nrole);
			}
		}
		return true;
	}

	@Override
	public CommonResult<String> importRole(MultipartHttpServletRequest request) throws Exception {
		MultipartFile file = request.getFile("file");
		Boolean isRepeat = importRoleFile(file);
		if(!isRepeat){
			return new CommonResult<>(true,"confirmUpload");
		}
		return new CommonResult<>(true,"导入成功");
	}

	@Override
	public CommonResult<String> importRoleData(MultipartHttpServletRequest request,String status) throws Exception {
		MultipartFile file = request.getFile("file");
		List<RoleVo> list = ExcelUtil.readExcel(RoleVo.class,file);
		if(BeanUtils.isNotEmpty(list)){
			if (!validateAllRole(list)) {
				String message = "校验失败，请检查excel数据是否正确。";
				throw new BaseException(message);
			}
			for (RoleVo roleVo : list) {
				Role role = baseMapper.getAllByCode(roleVo.getCode());
				Role nrole = RoleVo.parse(roleVo);
				if(BeanUtils.isEmpty(role)){
					nrole.setId(UniqueIdUtil.getSuid());
					this.create(nrole);
				}else {
					if ("update".equals(status)) {
						nrole.setId(role.getId());
						nrole.setIsDelete("0");
						baseMapper.updateRole(nrole);
					}else if("recover".equals(status)){
						role.setIsDelete("0");
						baseMapper.updateRole(role);
					}
					//else jump
				}
			}
		}
		return new CommonResult<>(true, "导入成功");
	}

	@Override
	public CommonResult<Role> getRoleByCode(String code) throws Exception {
		if(StringUtil.isEmpty(code)){
			return new CommonResult<Role>(false, "角色编码必填！", null);
		}
		Role r = this.getByAlias(code);
		if(BeanUtils.isEmpty(r)){
			r = this.get(code);
		}
		if(BeanUtils.isEmpty(r)){
			return new CommonResult<Role>(false, "根据输入的编码没有找到对应的角色", null);
		}
		return new CommonResult<Role>(true, "", r);
	}

    @Override
    public void export(HttpServletResponse response, String ids) throws Exception{
		QueryFilter filter = QueryFilter.build().withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
		filter.addFilter("id", ids.split(","), QueryOP.IN);
		PageList<Role> roles = query(filter);
		List<Map<String,Object>> list = new ArrayList<>();
		if(BeanUtils.isNotEmpty(roles.getRows())){
			for (Role role : roles.getRows()) {
				list.add(JsonUtil.toMap(JsonUtil.toJson(role)));
			}
		}
		Map<String,String> exportMap = new LinkedHashMap<>();
		exportMap.put("name","角色名称");
		exportMap.put("code","角色编码");
		exportMap.put("enabled","状态");
		exportMap.put("description","描述");
		HSSFWorkbook exportFile = ExcelUtil.exportExcel("角色列表", 22, exportMap, list);
		ExcelUtil.downloadExcel(exportFile,"角色导出",response);
    }

    private boolean validateAllRole(List<RoleVo> list){
		for (RoleVo roleVo : list) {
			if(StringUtil.isEmpty(roleVo.getName()) || StringUtil.isEmpty(roleVo.getCode())
					|| BeanUtils.isEmpty(roleVo.getEnabled())){
				return false;
			}
			if(!roleVo.getName().matches("^[\\s\\S]{1,30}$")
					|| !roleVo.getCode().matches("^[-0-9a-zA-Z_]{1,30}$")){
				return false;
			}
			if(!(roleVo.getEnabled() == 0 || roleVo.getEnabled() == 1)){
				return false;
			}
		}
		return true;
	}

	@Override
	@Transactional
	public CommonResult<String> operatingUserRoles(Map<String,Object> map) throws Exception{
		List<String> accounts = (List<String>)map.get("accounts");//要转移或复制的用户
		List<String> codes = (List<String>)map.get("codes");//要转移或复制的角色
		String type = map.get("type").toString();//1、转移，2、复制
		for (String account : accounts) {
			for (String code : codes) {
				Role role = baseMapper.getByCode(code);
				if (BeanUtils.isEmpty(role)) {
					throw new RequiredException("角色编码【" + code + "】不存在！");
				}
				StringBuilder values = new StringBuilder();
				boolean isFirst = true;
				User user = null;
				try {
					user = userService.getByAccount(account);
				} catch (Exception e) {
					throw new RequiredException("账号【" + account + "】无效！");
				}
				if (BeanUtils.isNotEmpty(user)) {
					addUserRole(user.getUserId(), role.getId());
				} else {
					if (isFirst) {
						isFirst = false;
					} else {
						values.append("，");
					}
					values.append(account);
				}
			}
		}
		String msg = "角色转移成功";
		if("2".equals(type)) {
			msg = "角色复制成功";
		}else{
			String account = map.get("account").toString();//原用户
			//如果是转移操作则删除原用户的角色
			for (String code : codes) {
				User user = userService.getByAccount(account);
				Role role = baseMapper.getByCode(code);
				if(BeanUtils.isNotEmpty(user) && BeanUtils.isNotEmpty(role)){
					UserRole userRole = userRoleManager.getByRoleIdUserId(role.getId(), user.getId());
					if(BeanUtils.isNotEmpty(userRole)){
						userRoleManager.remove(userRole.getId());
						delUserMenuCacheByUserId(userRole.getUserId());
					}
				}
			}
		}
		return new CommonResult<String>(true, msg);
	}
}
