package org.jeecg.modules.oauth2_server.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.context.model.SaResponse;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.oauth2.SaOAuth2Manager;
import cn.dev33.satoken.oauth2.config.SaOAuth2Config;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Consts.Param;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Handle;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import cn.dev33.satoken.oauth2.model.CodeModel;
import cn.dev33.satoken.oauth2.model.RequestAuthModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ejlchina.okhttps.HttpCall;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.MD5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.encryption.EncryptedString;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oauth2_server.service.Oauth2Service;
import org.jeecg.modules.oauth2_server.util.AesUtil;
import org.jeecg.modules.oauth2_server.vo.Captcha;
import org.jeecg.modules.oauth2_server.vo.Ouath2User;
import org.jeecg.modules.system.constant.Oauth2RedisConstant;
import org.jeecg.modules.system.constant.UserRedisConstant;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.enums.UserEnum;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.model.SysPermissionTree;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Sa-OAuth2 Server端 控制器
 * @author liushuai
 * 
 */
@Slf4j
@Api(tags="oauth2_server")
@RestController
public class SaOAuth2ServerController {

	@Resource
	private Oauth2Service oauth2Service;
	@Resource
	private ISysUserDepartService sysUserDepartService;
	@Resource
	private ISysTenantService sysTenantService;
	@Resource
	private ISysUserService sysUserService;
	@Resource
    private ISysChangeMsgService sysChangeMsgService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private ISysDepartService sysDepartService;
	@Resource
	private ISysPermissionService sysPermissionService;
	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private ISysRoleService sysRoleService;
	@Resource
	private ISysUserRoleService sysUserRoleService;
	@Resource
	private RedisUtil redisUtil;
	@Resource
    private ISaOAuth2Service saOAuth2Service;


	// 处理所有OAuth相关请求 
	@RequestMapping("/oauth2/*")
	public Object request() {
		System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
		return SaOAuth2Handle.serverRequest();
	}

	@RequestMapping("/oauth2/doLogin")
	public Object doLogin(){
		SaRequest req = SaHolder.getRequest();
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		//String localAddr = request.getLocalAddr();
		String remoteAddr = request.getRemoteAddr();
		String ip = request.getHeader("X-Forwarded-For");
		log.info("X-Forwarded-For"+ip);
		if (oConvertUtils.isEmpty(ip)){
            ip =remoteAddr;
		}
		SaResponse res = SaHolder.getResponse();
		SaOAuth2Config cfg = SaOAuth2Manager.getConfig();
		Ouath2User ouath2User = new Ouath2User();
		String name = req.getParamNotNull(Param.name);
		String pwd = req.getParamNotNull("pwd");
		ouath2User.setName(name);
		ouath2User.setPwd(pwd);
		ouath2User.setIp(ip);
		String user = JSON.toJSONString(ouath2User);
		String captcha = req.getParamNotNull("captcha");
		String checkKey = req.getParamNotNull("checkKey");
		Captcha capt = new Captcha();
		capt.setCaptcha(captcha);
		capt.setCheckKey(checkKey);
		String captm = JSON.toJSONString(capt);
		return cfg.doLoginHandle.apply(user,captm);
	}

	@RequestMapping("/oauth2/isLogin")
	public Result<?> isLogin(HttpServletResponse resp){
        try {
            StpUtil.checkLogin();
            return Result.OK(StpUtil.getTokenValue());
        } catch (NotLoginException ex) {
			resp.setStatus(200);
            return Result.error(Integer.parseInt(NotLoginException.INVALID_TOKEN),UserEnum.USER_CODE11000.getMsg());
        } catch (Exception ex) {
            ex.printStackTrace();
            resp.setStatus(200);
            return Result.error(500,"用户未登录");
        }
	}





	// 根据Code码进行登录，获取 Access-Token 和 openid
	@RequestMapping("/index/codeLogin")
	public Object codeLogin(String code) throws Exception {
		Result<JSONObject> result = new Result<JSONObject>();
		// 调用Server端接口，获取 Access-Token 以及其他信息
		AccessTokenModel oAuth2Token = sysUserService.getOAuth2Token(code, "1002", "aaaa-bbbb-cccc-dddd-eeee-ffff", "http://localhost:8081");
		if (oConvertUtils.isEmpty(oAuth2Token)){
			 return SaResult.error("Token获取失败");
		}

		try {
			//效验用户是否登录成功
			SysUser sysUser = sysUserService.getUserById(oAuth2Token.loginId.toString());
			result = sysUserService.checkUserIsEffective(sysUser);
			if(!result.isSuccess()) {
				return result;
			}
			if (oConvertUtils.isNotEmpty(sysUser.getOpePassword())){
				String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getOpePassword());
				// 设置超时时间
				redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
				redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, 60* 60 * 1000 );
			}
			String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());
			// 设置超时时间
			redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
			redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2/1000 );

			//获取用户部门信息
			JSONObject obj = new JSONObject();
			List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
			obj.put("departs", departs);
			if (departs == null || departs.isEmpty()) {
				obj.put("multi_depart", 0);
			} else if (departs.size() == 1) {
				sysUserService.updateUserDepart(oAuth2Token.loginId.toString(), departs.get(0).getOrgCode());
				obj.put("multi_depart", 1);
			} else {
				obj.put("multi_depart", 2);
			}
			obj.put("token", token);
			obj.put("userInfo", sysUser);
			result.setResult(obj);
			result.success("登录成功");
		} catch (Exception e) {
			result.error500(e.getMessage());
		}
		return new HttpEntity<>(result);
	}


	@RequestMapping("/oauth2/send")
	public synchronized Object PushInformationEveryDay(){
		List<SysChangeMsg> list = sysChangeMsgService.list(new QueryWrapper<SysChangeMsg>().eq("del_flag",0).isNotNull("url").eq("flag",0));
		Map<String, List<SysChangeMsg>> integerListMap = list.stream().collect(Collectors.groupingBy(SysChangeMsg::getUrl));
		for (Map.Entry<String, List<SysChangeMsg>> listEntry : integerListMap.entrySet()) {
			String url = listEntry.getKey();
			List<SysChangeMsg> value = listEntry.getValue();
				for (SysChangeMsg sysChangeMsg : value) {
					Object failNumber = redisUtil.get(Oauth2RedisConstant.SEND_CACHE_PREFIX + sysChangeMsg.getId());
					if (oConvertUtils.isEmpty(failNumber) || Integer.parseInt(String.valueOf(failNumber)) < 5) {
						HashMap<String, Object> map = new HashMap<>();
						String data = sysChangeMsg.getData();
						JSONObject jsonObject = JSON.parseObject(data);
						Integer type = sysChangeMsg.getType();
						String oprateType = sysChangeMsg.getOprateType();
						map.put("data", jsonObject);
						map.put("type", type.toString());
						map.put("oprateType", oprateType);
						try {
							HttpCall json1 = OkHttps.async(url)
									.setBodyPara(map)
									.bodyType("json")
									.setOnResponse((HttpResult res) -> {
										// 响应回调
										// 状态码
										int status = res.getStatus();
										if (status == 200) {
											sysChangeMsgService.update(new UpdateWrapper<SysChangeMsg>().eq("id", sysChangeMsg.getId()).set("flag", 1));
										}else {
											redisUtil.incr(Oauth2RedisConstant.SEND_CACHE_PREFIX + sysChangeMsg.getId(), 1);
										}
										System.out.println("status：" + status);
									})
									.setOnException((IOException e) -> {
										System.out.println("异常");
										redisUtil.incr(Oauth2RedisConstant.SEND_CACHE_PREFIX + sysChangeMsg.getId(), 1);
									})
									.post();
							//return map;
						}catch (Exception e){
							sysChangeMsgService.update(new UpdateWrapper<SysChangeMsg>().eq("url", url).set("flag", 3));
							e.printStackTrace();
						}
					} else {
						sysChangeMsgService.update(new UpdateWrapper<SysChangeMsg>().eq("id", sysChangeMsg.getId()).set("flag", 2));
						redisUtil.del(Oauth2RedisConstant.SEND_CACHE_PREFIX + sysChangeMsg.getId());
						return Result.error(400,"此数据异常次数过多,已不传递");
					}
				}
		}
		return null;
	}

    /**
     * 获取单点登录监管菜单
     * @return
     */
	@RequestMapping("/oauth2/RegulatorySupport")
    public Object RegulatorySupport(){
		ArrayList<HashMap<String, String>>  regulatorySupport= oauth2Service.getRegulatorySupport();
		return SaResult.data(regulatorySupport);
	}

	/**
	 * 获取单点登录横幅菜单
	 * @return
	 */
	@RequestMapping("/oauth2/getBannerMenus")
	public Object BannerMenus(){
		Object bannerMenus = oauth2Service.getBannerMenus();
		return SaResult.data(bannerMenus);
	}

	@RequestMapping("/oauth2/getToken")
	public Object oauth2Token(){
		SaRequest req = SaHolder.getRequest();
		// 获取参数
		String code = req.getParamNotNull(Param.code);
		String clientId = req.getParamNotNull(Param.client_id);
		String clientSecret = req.getParamNotNull(Param.client_secret);
		String redirectUri = req.getParam(Param.redirect_uri);

		AccessTokenModel token =sysUserService.getOAuth2Token(code, clientId, clientSecret, redirectUri);
		// 返回
		return SaResult.data(token.toLineMap());
	}

    @RequestMapping("/oauth2/refresh")
    public Object refreshOauth2Token(){
        SaRequest req = SaHolder.getRequest();
        // 获取参数
        String refresh_token = req.getParamNotNull(Param.refresh_token);
        String clientId = req.getParamNotNull(Param.client_id);
        String clientSecret = req.getParamNotNull(Param.client_secret);
//        String redirectUri = req.getParam(Param.redirect_uri);
        String grant_type = req.getParam(Param.grant_type);

        AccessTokenModel token =sysUserService.refreshOAuth2Token(clientId,clientSecret,refresh_token);
        // 返回
        return SaResult.data(token.toLineMap());
    }

	@RequestMapping("/oauth2/getCode")
	public Object oauth2Code() {
		System.out.println("获取Code");
		HashMap<Object, Object> hashMap = new HashMap<>();
		String code = sysUserService.getOAuth2Code(StpUtil.getLoginId(), "1001");
		hashMap.put("Code",code);
		return SaResult.data(hashMap);
	}


	// Sa-OAuth2 定制化配置
	// --用户登录操作
	@Autowired
	public void setSaOAuth2Config(SaOAuth2Config cfg) {
		System.out.println(cfg);
		cfg.
			// 未登录的视图 
			setNotLoginView(()-> new ModelAndView("login.html")).
			// 登录处理函数
			setDoLoginHandle((user, captm) -> {
				Ouath2User ouath2User = JSON.parseObject(user, Ouath2User.class);
				Captcha captM = JSON.parseObject(captm, Captcha.class);
				String name = ouath2User.getName();
				String pwd = ouath2User.getPwd();
				String ip = ouath2User.getIp();
				String captcha = captM.getCaptcha();
				String checkKey = captM.getCheckKey();
				if(captcha==null){
					return SaResult.error("验证码无效");
				}
				String lowerCaseCaptcha = captcha.toLowerCase();
				String realKey = MD5Util.MD5Encode(lowerCaseCaptcha+checkKey, "utf-8");
				Object checkCode = redisUtil.get(realKey);
				//当进入登录页时，有一定几率出现验证码错误 #1714
				if(checkCode==null || !checkCode.toString().equals(lowerCaseCaptcha)) {
					return SaResult.error("验证码错误");
				}
				//String realKey ="1";
				//解密密码
				try {
                    String decodePwd = Base64.decodeStr(pwd);
                    pwd = AesUtil.decryptPwd(decodePwd, EncryptedString.pwdKey, EncryptedString.pwdIv);
				} catch (Exception e) {
					e.printStackTrace();
				}

				SysUser sysUser = sysUserMapper.getSysUser(name);
				Object ipNumber = redisUtil.get(UserRedisConstant.LOGIN_FAIL_PREFIX + ip);
				if (sysUser == null) {
					if (oConvertUtils.isEmpty(ipNumber) || Integer.parseInt(String.valueOf(ipNumber)) < 5) {
						redisUtil.incr(UserRedisConstant.LOGIN_FAIL_PREFIX + ip, 1);
						if (oConvertUtils.isEmpty(ipNumber)){
							redisUtil.expire(UserRedisConstant.LOGIN_FAIL_PREFIX + ip,60);
						}
						if (oConvertUtils.isNotEmpty(ipNumber)&&Integer.parseInt(String.valueOf(ipNumber))==4){
							redisUtil.set(UserRedisConstant.LOGIN_TIME_PREFIX + ip,ip,300);
						}
						return SaResult.error("账号名或密码错误");
					}else {
						return SaResult.error("账号名或密码错误次数过多，请五分钟后在重试");
					}
				}
				Object time = redisUtil.get(UserRedisConstant.LOGIN_TIME_PREFIX + sysUser.getId());
				if (oConvertUtils.isNotEmpty(time)){
					return SaResult.error("密码错误次数过多，请五分钟后在重试");
				}
				String password = PasswordUtil.encrypt(name, pwd, sysUser.getSalt());
                if (oConvertUtils.isNotEmpty(sysUser.getOpePassword())){
					if(sysUser.getUsername().equals(name) && (sysUser.getPassword().equals(password)||sysUser.getOpePassword().equals(password))&&sysUser.getStatus()==1) {
						SysUser loginTime = sysUser.setLoginTime(new Date());
						int i = sysUserMapper.updateById(loginTime);
						return saOAuth2Service.userLogin(sysUser,pwd,realKey);
					}
					Object failNumber = redisUtil.get(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId());
					if (oConvertUtils.isEmpty(failNumber) || Integer.parseInt(String.valueOf(failNumber)) < 5) {
						redisUtil.incr(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId(), 1);
						if (oConvertUtils.isEmpty(failNumber)){
							redisUtil.expire(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId(),60);
						}
						if (oConvertUtils.isNotEmpty(failNumber)&&Integer.parseInt(String.valueOf(failNumber))==4){
							redisUtil.set(UserRedisConstant.LOGIN_TIME_PREFIX + sysUser.getId(),sysUser.getId(),300);
						}
						return SaResult.error("账号名或密码错误");
					}else {
						return SaResult.error("密码错误次数过多，请五分钟后在重试");
					}
				}else {
					if(sysUser.getUsername().equals(name) && sysUser.getPassword().equals(password)&&sysUser.getStatus()==1) {
						SysUser loginTime = sysUser.setLoginTime(new Date());
						int i = sysUserMapper.updateById(loginTime);
						return saOAuth2Service.userLogin(sysUser,pwd,realKey);
					}
					Object failNumber = redisUtil.get(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId());
					if (oConvertUtils.isEmpty(failNumber) || Integer.parseInt(String.valueOf(failNumber)) < 5) {
						redisUtil.incr(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId(), 1);
						if (oConvertUtils.isEmpty(failNumber)){
							redisUtil.expire(UserRedisConstant.LOGIN_FAIL_PREFIX + sysUser.getId(),60);
						}
						if (oConvertUtils.isNotEmpty(failNumber)&&Integer.parseInt(String.valueOf(failNumber))==4){
							redisUtil.set(UserRedisConstant.LOGIN_TIME_PREFIX + sysUser.getId(),sysUser.getId(),300);
						}
						return SaResult.error("账号名或密码错误");
					}else {
						return SaResult.error("密码错误次数过多，请五分钟后在重试");
					}
				}
			}).
			// 授权确认视图 
			setConfirmView((clientId, scope)->{
				Map<String, Object> map = new HashMap<>();
				map.put("clientId", clientId);
				map.put("scope", scope);
				return new ModelAndView("confirm.html", map); 
			});
	}

	// 全局异常拦截  
	@ExceptionHandler
	public SaResult handlerException(Exception e) {
		e.printStackTrace(); 
		return SaResult.error(e.getMessage());
	}

	// ---------- 开放相关资源接口： Client端根据 Access-Token ，置换相关资源 ------------
	// 获取Userinfo信息：昵称、头像、性别等等
	@RequestMapping("/oauth2/userinfo")
	public SaResult userinfo() throws Exception {
		// 获取 Access-Token 对应的账号id 
		String accessToken = SaHolder.getRequest().getParamNotNull("access_token");
		Object loginId =  SaOAuth2Util.getLoginIdByAccessToken(accessToken);
		log.info("-------- 此Access-Token对应的账号id: " + loginId);
		// 校验 Access-Token 是否具有权限: userinfo
		SaOAuth2Util.checkScope(accessToken, "userinfo");
		SysUser sysUser = sysUserMapper.selectByLId(loginId.toString());
		SysDeptUserVo sysDeptUserVo = new SysDeptUserVo();
		SysDepart depart = sysDepartService.getDeptByUserId(sysUser.getId());
		BeanUtils.copyProperties(sysUser,sysDeptUserVo);
        if (oConvertUtils.isNotEmpty(depart)){
			sysDeptUserVo.setDepartId(depart.getId());
			sysDeptUserVo.setDepartCode(depart.getDepartCode());
			sysDeptUserVo.setDepartName(depart.getDepartName());
		}
//		//把实体转化成json数据
		String s = JSON.toJSONString(sysDeptUserVo);
		String encrypt = AesUtil.encrypt(s, EncryptedString.key,EncryptedString.iv);
		return SaResult.data(encrypt);
	}

	@ApiOperation(value="sys_user-通过id查询user", notes="sys_user-通过id查询user")
	@RequestMapping(value = "/oauth2/queryById", method = RequestMethod.GET)
	public Result<SysUserOVo> queryById(@RequestParam(name = "userId") String id,
										@RequestParam(name="clientId") String client_id,
										@RequestParam(name="clientSecret") String client_secret) {
		Result<SysUserOVo> result = new Result<SysUserOVo>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		SysUser sysUser = sysUserService.getById(id);
		if (oConvertUtils.isEmpty(sysUser)) {
			result.error500("未找到对应实体");
		} else {
			SysUserOVo sysUserVo = new SysUserOVo();
			SysDepart depart = sysDepartService.getDeptByUserId(id);
			BeanUtils.copyProperties(sysUser,sysUserVo);
			if (oConvertUtils.isNotEmpty(depart)){
				sysUserVo.setDepartName(depart.getDepartName());
				sysUserVo.setDepartCode(depart.getDepartCode());
			}
			result.setResult(sysUserVo);
			result.setSuccess(true);
		}
		return result;
	}



	@ApiOperation(value="sys_user-查询全部user", notes="sys_user-查询全部user")
	@RequestMapping(value = "/oauth2/queryUserAll", method = RequestMethod.GET)
	public Result<IPage<SysUserOVo>> queryUserAll(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			                                      @RequestParam(name="clientId") String client_id,
											      @RequestParam(name="clientSecret") String client_secret){

		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			Result<IPage<SysUserOVo>> result = new Result<>();
			result.error400("client_id或者client_secret错误");
			return result;
		}

		Page<SysUser> page = new Page<>(pageNo, pageSize);
		IPage<SysUser> pageList = sysUserService.page(page,new QueryWrapper<>());
		List<SysUser> records = pageList.getRecords();
		List<SysUserOVo> collect = records.stream().map((sysUser) -> {
			SysUserOVo sysUserOVo = new SysUserOVo();
			BeanUtils.copyProperties(sysUser, sysUserOVo);
			SysDepart depart = sysDepartService.getDeptByUserId(sysUser.getId());
			if (oConvertUtils.isNotEmpty(depart)){
				sysUserOVo.setDepartId(depart.getId());
				sysUserOVo.setDepartName(depart.getDepartName());
				sysUserOVo.setDepartCode(depart.getDepartCode());
			}
			return sysUserOVo;
		}).collect(Collectors.toList());
		IPage<SysUserOVo> result = new Page<>(pageList.getCurrent(),pageList.getPages(),pageList.getTotal());
		result.setRecords(collect);
		return Result.OK(result);
	}

	@ApiOperation(value="sys_role-通过rolecode查询", notes="sys_role-通过通过rolecode查询查询")
	@RequestMapping(value = "/oauth2/queryRoleByCode", method = RequestMethod.GET)
	public Result<SysRoleOVo> queryRoleByCode(@RequestParam(name="roleCode") String roleCode,
										      @RequestParam(name="clientId") String client_id,
										      @RequestParam(name="clientSecret") String client_secret) {
		Result<SysRoleOVo> result = new Result<>();
		SysRoleOVo sysRoleOVo = new SysRoleOVo();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		SysRole sysrole = sysRoleService.getByRoleCode(roleCode);
		if(sysrole==null) {
			result.error500("未找到对应实体");
		}else {
			BeanUtils.copyProperties(sysrole,sysRoleOVo);
			result.setResult(sysRoleOVo);
			result.setSuccess(true);
		}
		return result;
	}

	@ApiOperation(value="sys_role-list查询", notes="sys_role-list查询")
	@RequestMapping(value = "/oauth2/queryRoleByPage", method = RequestMethod.GET)
	public Result<IPage<SysRoleVo>> queryRoleList(
												@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												@RequestParam(name="clientId") String client_id,
												@RequestParam(name="clientSecret") String client_secret
												) {
		Result<IPage<SysRoleVo>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		//QueryWrapper<SysRoleVo> queryWrapper = QueryGenerator.initQueryWrapper();
		Page<SysRole> page = new Page<>(pageNo, pageSize);
		IPage<SysRole> pageList = sysRoleService.page(page,null);
		List<SysRole> records = pageList.getRecords();
		List<SysRoleVo> collect = records.stream().map((SysRole) -> {
			SysRoleVo sysRoleVo  = new SysRoleVo();
			BeanUtils.copyProperties(SysRole, sysRoleVo);
			return sysRoleVo;
		}).collect(Collectors.toList());
		IPage<SysRoleVo> rolePage = new Page<>(pageList.getCurrent(),pageList.getPages(),pageList.getTotal());
		rolePage.setRecords(collect);
		return Result.OK(rolePage);
	}

	@ApiOperation(value="sys_user-userid查询角色", notes="sys_role-userid查询角色")
	@RequestMapping(value = "/oauth2/queryUserRole", method = RequestMethod.GET)
	public Object queryUserRole(@RequestParam(name = "userId", required = true) String userId,
											  @RequestParam(name="clientId") String clientId,
											  @RequestParam(name="clientSecret") String clientSecret) {
		Result<HashMap<String, String>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().lambda().eq(SysTenant::getClientId, clientId).eq(SysTenant::getClientSecret, clientSecret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		HashMap<String, String> map = new HashMap<>();
		String roleIdByUesrId = sysUserRoleService.getRoleIdByUesrId(userId);
		if (oConvertUtils.isNotEmpty(roleIdByUesrId)){
			map.put("userId",userId);
			map.put("roleId",roleIdByUesrId);
		}
		return Result.OK(map);
	}
	@ApiOperation(value="sys_role查询全部角色", notes="sys_role-查询全部角色")
	@RequestMapping(value = "/oauth2/queryAllUserRole", method = RequestMethod.GET)
	public Result<IPage<SysUserRole>> queryAllUserRole( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														@RequestParam(name="clientId") String client_id,
														@RequestParam(name="clientSecret") String client_secret) {
		Result<IPage<SysUserRole>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		Page<SysUserRole> page = new Page<>(pageNo, pageSize);
		IPage<SysUserRole> pageList = sysUserRoleService.page(page,new QueryWrapper<>());
		if (oConvertUtils.isEmpty(pageList)) {
			result.error500("未找到用户相关角色信息");
		}
		return Result.OK(pageList);
	}

	@ApiOperation(value="sys-menus-查询角色授权", notes="sys-menus-查询角色授权")
	@RequestMapping(value = "/oauth2/queryRolePermission", method = RequestMethod.GET)
	public Result<List<String>> queryRolePermission(@RequestParam(name = "roleId") String roleId,
													@RequestParam(name="clientId") String client_id,
													@RequestParam(name="clientSecret") String client_secret) {
		Result<List<String>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
			//long l = System.currentTimeMillis();
			List<String> permissionList=sysPermissionService.getPermissionByRoleAndTenant(tenant.getId(),roleId);
//			long l1 = System.currentTimeMillis();
//			long l2 = l1 - l;
//			System.out.println("l2"+l2);
			//log.info(JSON.toJSONString(permissionList));
			//long l3 = System.currentTimeMillis();
			//List<String> permissionId =sysRolePermissionService.getPermissionId(roleId);
			//String strip1 = StringUtils.strip(permissionId.toString(), "[]");
			//String strip = JSON.toJSONString(permissionId);
			//log.info(JSON.toJSONString(permissionId));
			//List<String> permissionIds = sysPermissionService.getPermissionIds(tenant.getId());
//			List<String> permissionIdsss = sysPermissionService.getPermissionIdsss(tenant.getId(),permissionId);
//			long l4 = System.currentTimeMillis();
//			long l5 =l4-l3;
//			System.out.println("l5"+l5);
//			long l6 = System.currentTimeMillis();
//			List<String> permissionIdss = sysPermissionService.getPermissionIdss(tenant.getId(),roleId);
//			long l7 = System.currentTimeMillis();
//			long l8=l7-l6;
//			System.out.println("l8"+l8);
			//log.info(JSON.toJSONString(permissionIds));

			//List<SysPermission> lsId = sysPermissionService.list(new QueryWrapper<SysPermission>().eq("tenant_id", tenant.getId()));
			//List<SysRolePermission> list = sysRolePermissionService.list(new QueryWrapper<SysRolePermission>().eq("role_id", roleId));
//			List<String> arrayList = new ArrayList<>();
//			lsId.forEach(ls->{
//				list.forEach(lt -> {
//					if (lt.getPermissionId().equals(ls.getId())) {
//						arrayList.add(ls.getId());
//					}
//				});
//			});
//
//			log.info(JSON.toJSONString(arrayList));
			//List<String> collect = lsId.stream().map(SysPermission::getId).collect(Collectors.toList());
			//List<String> collect1 = list.stream().map(SysRolePermission::getPermissionId).collect(Collectors.toList());
			//List<String> collect2 = collect.stream().filter(it -> collect1.contains(it)).collect(Collectors.toList());
			//collect.retainAll(collect1);

		return Result.OK(permissionList);
	}

    @ApiOperation(value="【菜单】通过USERID串获取菜单信息", notes="sys-menus-查询菜单信息")
    @RequestMapping(value = "/oauth2/getMenuByUserId", method = RequestMethod.GET)
    public Result<List<SysMenusOVo>> getMenuByUserId(@RequestParam(name="userId", defaultValue="userId") String userId,
													 @RequestParam(name="clientId") String client_id,
													 @RequestParam(name="clientSecret") String client_secret){

        Result<List<SysMenusOVo>> result = new Result<>();
        SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
        if (oConvertUtils.isEmpty(tenant)){
            result.error400("client_id或者client_secret错误");
            return result;
        }

        //通过UserId查询用户信息
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null || sysUser.getUsername() == null) {
            result.error400("用户信息为空");
            return result;
        }
        List<SysPermission> sysPermissions = sysPermissionService.queryByUser(sysUser.getUsername(),tenant.getId());
        List<SysMenusOVo> collect = sysPermissions.stream().map(sysPermission -> {
            SysMenusOVo sysMenusOVo = new SysMenusOVo();
            BeanUtils.copyProperties(sysPermission, sysMenusOVo);
            return sysMenusOVo;
        }).collect(Collectors.toList());
        return Result.OK(collect);
    }


    @ApiOperation(value="【菜单】通过ID串获取菜单信息", notes="sys-menus-查询菜单信息")
    @RequestMapping(value = "/oauth2/getMenuByIds", method = RequestMethod.GET)
    public Result<List<SysMenusOVo>> getMenuByIds(@RequestParam(name="ids", defaultValue="") String ids,
                                                  @RequestParam(name="clientId") String client_id,
                                                  @RequestParam(name="clientSecret") String client_secret){
        Result<List<SysMenusOVo>> result = new Result<>();
        long start = System.currentTimeMillis();
        SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
        if (oConvertUtils.isEmpty(tenant)){
            result.error400("client_id或者client_secret错误");
            return result;
        }

        List<SysPermission> sysPermissions = sysPermissionService.list(new QueryWrapper<SysPermission>().in("id", ids.split(",")));

        List<SysMenusOVo> collect = sysPermissions.stream().map(sysPermission -> {
            SysMenusOVo sysMenusOVo = new SysMenusOVo();
            BeanUtils.copyProperties(sysPermission, sysMenusOVo);
            return sysMenusOVo;
        }).collect(Collectors.toList());
        return Result.OK(collect);
    }

	@ApiOperation(value="sys-menus-查询子系统所有菜单信息", notes="sys-menus-查询子系统所有菜单信息")
	@RequestMapping(value = "/oauth2/queryRoleMenuInfoByPage", method = RequestMethod.GET)
	public Result<List<SysMenusOVo>> list(@RequestParam(name="clientId") String client_id,
										  @RequestParam(name="clientSecret") String client_secret) {
		Result<List<SysMenusOVo>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		try {
			List<SysPermission> list = sysPermissionService.list(new QueryWrapper<SysPermission>().eq("status","1"));
			List<SysMenusOVo> collect = list.stream().map(sysPermission -> {
				SysMenusOVo sysMenusOVo = new SysMenusOVo();
				BeanUtils.copyProperties(sysPermission, sysMenusOVo);
				return sysMenusOVo;
			}).collect(Collectors.toList());
//			result.setResult(collect);
//			result.setSuccess(true);
			return Result.OK(collect);
//			log.info("======获取全部菜单数据=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	private void getTreeList(List<SysPermissionTree> treeList, List<SysPermission> metaList, SysPermissionTree temp) {
		for (SysPermission permission : metaList) {
			String tempPid = permission.getParentId();
			SysPermissionTree tree = new SysPermissionTree(permission);
			if (temp == null && oConvertUtils.isEmpty(tempPid)) {
				treeList.add(tree);
				if (!tree.getIsLeaf()) {
					getTreeList(treeList, metaList, tree);
				}
			} else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
				temp.getChildren().add(tree);
				if (!tree.getIsLeaf()) {
					getTreeList(treeList, metaList, tree);
				}
			}

		}
	}

    @ApiOperation(value="【部门】通过部门ID获取部门信息", notes="通过部门ID获取部门信息")
    @RequestMapping(value = "/oauth2/queryDeptInfoById", method = RequestMethod.GET)
    public Result<SysDepartOVo> queryDeptInfoById(@RequestParam("deptId") String deptId,
												  @RequestParam(name="clientId") String client_id,
												  @RequestParam(name="clientSecret") String client_secret){
        Result<SysDepartOVo> result = new Result<>();
        SysDepart sysDepart = sysDepartService.getOne(new QueryWrapper<SysDepart>().eq("id", deptId));

        SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
        if (oConvertUtils.isEmpty(tenant)){
            result.error400("client_id或者client_secret错误");
            return result;
        }

        SysDepartOVo vo = new SysDepartOVo();
        BeanUtils.copyProperties(sysDepart,vo);
        return Result.OK(vo);
    }

	@AutoLog(value = "根据部门id查询用户信息")
	@ApiOperation(value="根据部门id查询用户信息", notes="根据部门id查询用户信息")
	@RequestMapping(value = "/oauth2/queryListUserByDepId", method = RequestMethod.GET)
	public Result<Page<SysUser>> queryListUserByDepId(
			                                        @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
		                                         	@RequestParam(name = "depId", required = true) String id,
			                                        @RequestParam(name="realname",required=false) String realname) {
		Result<Page<SysUser>> result = new Result<>();
		Page<SysUser> sysUserPage = sysUserDepartService.queryUserByDepCode1(id, realname, pageNo, pageSize);
		//批量查询用户的所属部门
		//step.1 先拿到全部的 useids
		//step.2 通过 useids，一次性查询用户的所属部门名字
//		List<String> userIds = sysUserPage.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
//		if(userIds!=null && userIds.size()>0){
//			Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(userIds);
//			sysUserPage.getRecords().forEach(item->{
//				//TODO 临时借用这个字段用于页面展示
//				item.setOrgCodeTxt(useDepNames.get(item.getId()));
//			});
//		}

		sysUserPage.getRecords().forEach(item->{
				item.setClearCard("");
		});
		try {
			result.setSuccess(true);
			result.setResult(sysUserPage);
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.setSuccess(false);
			return result;
		}
	}

	@ApiOperation(value="gt_sys_depart-areaId查询", notes="gt_sys_depart-areaId查询")
	@RequestMapping(value = "/oauth2/queryTreeListByAreaId", method = RequestMethod.GET)
	public Result<List<SysDepartOVo>> queryTreeListByAreaId(@RequestParam("areaId") String areaId,
																  @RequestParam(name="clientId") String client_id,
																  @RequestParam(name="clientSecret") String client_secret) {
		Result<List<SysDepartOVo>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		List<SysDepart> list = sysDepartService.list(new QueryWrapper<SysDepart>().eq("area_id", areaId));
		List<SysDepartOVo> collect = list.stream().map(sysDepart -> {
			SysDepartOVo sysDepartOVo = new SysDepartOVo();
			BeanUtils.copyProperties(sysDepart, sysDepartOVo);
			return sysDepartOVo;
		}).collect(Collectors.toList());
		return Result.OK(collect);
	}

	@AutoLog(value = "gt_sys_depart-通过参数查询")
	@ApiOperation(value="gt_sys_depart-通过参数查询", notes="gt_sys_depart-通过参数查询")
	@GetMapping(value = "/oauth2/queryByNameAndCode")
	public Result<?> queryByname( @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								  @RequestParam(name="clientId") String client_id,
								  @RequestParam(name="clientSecret") String client_secret,
								  String departName,String socialCreditCode,String areaId) {
		Result<?> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		List<SysDepart> list1 = sysDepartService.list(new QueryWrapper<SysDepart>().eq("depart_name", departName)
				.eq("SOCIAL_CREDIT_CODE", socialCreditCode)
				.eq("area_id", areaId));
		List<SysDepartOVo> collect = list1.stream().map(sysDepart -> {
			SysDepartOVo sysDepartOVo = new SysDepartOVo();
			BeanUtils.copyProperties(sysDepart, sysDepartOVo);
			return sysDepartOVo;
		}).collect(Collectors.toList());
		return Result.OK(collect);
	}

	@ApiOperation(value="gt_sys_depart-树结构查询", notes="gt_sys_depart-树结构查询")
	@RequestMapping(value = "/oauth2/queryTreeList", method = RequestMethod.GET)
	public Result<IPage<SysDepartOVo>> queryTreeList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			                                        @RequestParam(name="clientId") String client_id,
													@RequestParam(name="clientSecret") String client_secret) {

		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			Result<IPage<SysDepartOVo>> result = new Result<>();
			result.error400("client_id或者client_secret错误");
			return result;
		}
		Page<SysDepart> page = new Page<>(pageNo, pageSize);
		IPage<SysDepart> pageList = sysDepartService.page(page,new QueryWrapper<>());
        List<SysDepart> records = pageList.getRecords();
        List<SysDepartOVo> collect = records.stream().map(sysArea -> {
            SysDepartOVo sysDepartOVo = new SysDepartOVo();
            BeanUtils.copyProperties(sysArea, sysDepartOVo);
            return sysDepartOVo;
        }).collect(Collectors.toList());
        IPage<SysDepartOVo> result = new Page<>(pageList.getCurrent(), pageList.getPages(), pageList.getTotal());
        result.setRecords(collect);
        return Result.OK(result);
    }

    @AutoLog(value = "sys_area-全部查询")
    @ApiOperation(value = "sys_area-全部查询", notes = "sys_area-全部查询")
    @GetMapping(value = "/oauth2/allList")
    public Result<IPage<SysAreaOVo>> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   @RequestParam(name = "clientId") String client_id,
                                                   @RequestParam(name = "clientSecret") String client_secret) {

        SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
        if (oConvertUtils.isEmpty(tenant)) {
            Result<IPage<SysAreaOVo>> result = new Result<>();
            result.error400("client_id或者client_secret错误");
            return result;
        }
        Page<SysArea> page = new Page<>(pageNo, pageSize);
        IPage<SysArea> pageList = sysAreaService.page(page, new QueryWrapper<>());
        List<SysArea> records = pageList.getRecords();
        List<SysAreaOVo> collect = records.stream().map(sysArea -> {
            SysAreaOVo sysAreaOVo = new SysAreaOVo();
            BeanUtils.copyProperties(sysArea, sysAreaOVo);
            if (!sysArea.getParentId().equals("0")) {
                SysArea byId = sysAreaService.getById(sysArea.getParentId());
                sysAreaOVo.setParentAreaCode(byId.getAreaCode());
            } else {
                sysAreaOVo.setParentAreaCode("0");
            }
            return sysAreaOVo;
        }).collect(Collectors.toList());
        IPage<SysAreaOVo> result = new Page<>(pageList.getCurrent(), pageList.getPages(), pageList.getTotal());
        result.setRecords(collect);
        return Result.OK(result);
    }

    @AutoLog(value = "sys_area-通过地区编码查询")
    @ApiOperation(value = "sys_area-通过地区编码查询", notes = "sys_area-通过地区编码查询")
    @GetMapping(value = "/oauth2/queryAreaByAreaCode")
    public Result<?> queryPageListByAreaCode(@RequestParam(name = "clientId") String client_id,
                                             @RequestParam(name = "clientSecret") String client_secret,
                                             String areaCode) {
        Result<?> result = new Result<>();
        SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
        if (oConvertUtils.isEmpty(tenant)) {
            result.error400("client_id或者client_secret错误");
            return result;
        }
        List<SysArea> area_code = sysAreaService.list(new QueryWrapper<SysArea>().eq("area_code", areaCode));
        List<SysAreaOVo> collect = area_code.stream().map(sysArea -> {

            SysAreaOVo sysAreaOVo = new SysAreaOVo();
            BeanUtils.copyProperties(sysArea, sysAreaOVo);
            if (!sysArea.getParentId().equals("0")) {
                SysArea byId = sysAreaService.getById(sysArea.getParentId());
                sysAreaOVo.setParentAreaCode(byId.getAreaCode());
            } else {
                sysAreaOVo.setParentAreaCode("0");
            }
            return sysAreaOVo;
        }).collect(Collectors.toList());
		return Result.OK(collect);
	}

	@ApiOperation(value="sys-menus-查询子菜单", notes="sys-menus-查询子菜单")
	@RequestMapping(value = "/oauth2/getSystemSubmenu", method = RequestMethod.GET)
	public Result<List<SysPermissionTree>> getSystemSubmenu(@RequestParam("parentId") String parentId,
															@RequestParam(name="clientId") String client_id,
															@RequestParam(name="clientSecret") String client_secret){
		Result<List<SysPermissionTree>> result = new Result<>();
		SysTenant tenant = sysTenantService.getOne(new QueryWrapper<SysTenant>().eq("client_id", client_id).eq("client_secret", client_secret));
		if (oConvertUtils.isEmpty(tenant)){
			result.error400("client_id或者client_secret错误");
			return result;
		}
		try{
			LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<>();
			query.eq(SysPermission::getParentId,parentId);
			query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
			query.orderByAsc(SysPermission::getSortNo);
			List<SysPermission> list = sysPermissionService.list(query);
			List<SysPermissionTree> sysPermissionTreeList = new ArrayList<>();
			for(SysPermission sysPermission : list){
				SysPermissionTree sysPermissionTree = new SysPermissionTree(sysPermission);
				sysPermissionTreeList.add(sysPermissionTree);
			}
			result.setResult(sysPermissionTreeList);
			result.setSuccess(true);
		}catch (Exception e){
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@ApiOperation(value="sys-msg-获取未解决的信息", notes="sys-msg-获取未解决的信息")
	@GetMapping(value = "/oauth2/getChangeMsg")
	public Result<List<SysChangeMsg>> getChangeMsg(){
		Result<List<SysChangeMsg>> result = new Result<>();
		List<SysChangeMsg> flag = sysChangeMsgService.list(new QueryWrapper<SysChangeMsg>().eq("flag", 0));
		result.setResult(flag);
		return result;
	}


	/**
	 * 通过用户信息获取应用列表
     */
	@GetMapping("/oauth2/getMenu")
	public List<SysTenantVO> getMenu(){
		Object loginId =StpUtil.getLoginId();

		//通过loginId查询用户权限菜单

		List<SysTenant> tenants = sysUserMapper.queryUserTenant(loginId.toString());
		List<SysTenantVO> rsTenantList = new ArrayList<>();

		for (SysTenant tenant : tenants) {
			if (StringUtils.isEmpty(tenant.getClientId())) {
				continue;
			}
			SysTenantVO vo = new SysTenantVO();
			BeanUtils.copyProperties(tenant,vo);

			RequestAuthModel ra = generateRequestAuth2(loginId,tenant.getClientId());
			CodeModel codeModel = SaOAuth2Util.generateCode(ra);
			vo.setCode(codeModel.getCode());

			rsTenantList.add(vo);
		}

		return rsTenantList;
	}
	public RequestAuthModel generateRequestAuth2(Object loginId,String clientId) {
		RequestAuthModel ra = new RequestAuthModel();
		ra.clientId = clientId;
		ra.responseType = "code";
		ra.redirectUri = "http://localhost:8081";
		ra.state = "";
		ra.scope = "userinfo";
		ra.loginId = loginId;
		return ra;
	}
}
