package org.jeecg.modules.system.service.impl;

import cn.com.ctop.common.module.entity.SysRole;
import cn.com.ctop.common.module.entity.SysUser;
import cn.com.ctop.common.module.entity.SysUserRole;
import cn.com.ctop.common.module.mapper.SysRoleExtMapper;
import cn.com.ctop.common.module.mapper.SysUserRoleMapper;
import cn.com.ctop.common.module.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @Author scott
 * @since 2018-12-21
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

	@Autowired
	private ISysUserService userService;
	@Autowired
	private ISysRoleService roleService;
	@Resource
	private SysUserRoleMapper roleMapper;
	@Resource
	private SysRoleExtMapper sysRoleExtMapper;
	/**
	 * 查询所有用户对应的角色信息
	 */
	@Override
	public Map<String,String> queryUserRole() {
		List<SysUserRole> uRoleList = this.list();
		List<SysUser> userList = userService.list();
		List<SysRole> roleList = roleService.list();
		Map<String,String> map = new IdentityHashMap<>();
		String userId = "";
		String roleId = "";
		String roleName = "";
		if(uRoleList != null && uRoleList.size() > 0) {
			for(SysUserRole uRole : uRoleList) {
				roleId = uRole.getRoleId();
				for(SysUser user : userList) {
					userId = user.getId();
					if(uRole.getUserId().equals(userId)) {
						roleName = this.searchByRoleId(roleList,roleId);
						map.put(userId, roleName);
					}
				}
			}
			return map;
		}
		return map;
	}

	@Override
	public SysUserRole getUserRoleByUserId(String userId) {
		QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", userId);
		return getOne(queryWrapper);
	}

	/**
	 * queryUserRole调用的方法
	 * @param roleList
	 * @param roleId
	 * @return
	 */
	private String searchByRoleId(List<SysRole> roleList, String roleId) {
		while(true) {
			for(SysRole role : roleList) {
				if(roleId.equals(role.getId())) {
					return role.getRoleName();
				}
			}
		}
	}

	@Override
	public String getLeaderId(String userId, String roleCode) {
		String roleCodeStr = sysRoleExtMapper.getRoleCodeByUserId(userId);
		if ("kuaishouOperationManager".equals(roleCodeStr) || "touTiaoOperationManager".equals(roleCodeStr)) {
			return null;
		}
		String leaderId = roleMapper.getLeaderIdByUser(userId, roleCode);
		return leaderId;
	}

}
