package com.reyun.saas.mob.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.reyun.saas.common.constants.MailEnumType;
import com.reyun.saas.common.constants.RoleEnumType;
import com.reyun.saas.common.restResult.RestResult;
import com.reyun.saas.common.restResult.ResultCode;
import com.reyun.saas.common.restResult.ResultGenerator;
import com.reyun.saas.common.util.PatternUtil;
import com.reyun.saas.mob.user.dao.AppAuthMapper;
import com.reyun.saas.mob.user.dao.ChannelMapper;
import com.reyun.saas.mob.user.dao.UserAndRoleMapper;
import com.reyun.saas.mob.user.dao.UserMapper;
import com.reyun.saas.mob.user.domain.App;
import com.reyun.saas.mob.user.domain.AppAuth;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.domain.UserAndRole;
import com.reyun.saas.mob.user.dto.user.UserOutpDTO;
import com.reyun.saas.mob.user.service.AuthService;
import com.reyun.saas.mob.user.service.MailService;
import com.reyun.saas.mob.user.service.SubUserService;
import com.reyun.saas.mob.util.RoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class SubUserServiceImpl implements SubUserService {

    /**
     * 管理员最大数量
     */
    private static final Long  MANAGERMAXCOUNT = 3L;

    /**
     * 子应用管理员最大数量
     */
    private static final Long  SUBAPPMANAGERMAXCOUNT = 50L;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MailService mailService;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private AppAuthMapper appAuthMapper;

    @Autowired
    private AuthService authService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ConsumerTokenServices tokenServices;
    /**
     * 创建子用户
     * 主账号最多创建3个管理员
     * 每一个主账号和管理员最多创建50个子应用管理员 一个主账号下最多有200个子应用管理员
     * @param user 当前登录用户id
     * @param user 子用户
     * @return
     */
    @Override
    public RestResult createSubUser(Long loginUserId, User user) {

        //校验参数
        if (user == null || StringUtils.isEmpty(user.getUsername())
                || StringUtils.isEmpty(user.getPhone())){
            return ResultGenerator.genResult(ResultCode.PARAMETER_ERROR);
        }

        String email = user.getUsername();

        //校验邮箱格式
        if (!PatternUtil.isEmail(email)){
            return ResultGenerator.genFailResult("邮箱格式错误");
        }

        String phone = null;
        //校验手机号
        if (!StringUtils.isEmpty(user.getPhone())
                && !StringUtils.isEmpty(user.getPhone().trim())) {
            //正则校验手机号
            if (PatternUtil.isMobileNo(user.getPhone())) {
                phone = user.getPhone();
            } else {
                return ResultGenerator.genResult(ResultCode.PHONE_FORMAT_ERROR);
            }
        }else{
            return ResultGenerator.genResult(ResultCode.PHONE_FORMAT_ERROR);
        }


        //校验用户是否存在
        Example example = new Example(User.class);
        example.and().andEqualTo("username",email);
        example.and().andEqualTo("delFlag",false);
        User dbUser = userMapper.selectOneByExample(example);
        if(dbUser != null){
            return ResultGenerator.genResult(ResultCode.EMAIL_ALREADY_EXISTED);
        }

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);


        //校验当前角色用户是否可以创建角色
        if (RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())) {
            //主账号 可以创建除了主账号之外的所有角色
            if (RoleEnumType.SUPER_USER.getKey().equals(user.getRoleCategory())) {
                return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
            }
        }else if(RoleEnumType.MANAGER.getKey().equals(loginUser.getRoleCategory())){
            //管理员 可以创建子应用管理员和普通账号
            if (RoleEnumType.SUPER_USER.getKey().equals(user.getRoleCategory())
                    || RoleEnumType.MANAGER.getKey().equals(user.getRoleCategory()) ) {
                return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
            }
        }else if(RoleEnumType.SUB_APP_MANAGER.getKey().equals(loginUser.getRoleCategory())){
            //子应用管理员  可以创建普通账号
            if (RoleEnumType.SUPER_USER.getKey().equals(user.getRoleCategory())
                    || RoleEnumType.MANAGER.getKey().equals(user.getRoleCategory())
                    || RoleEnumType.SUB_APP_MANAGER.getKey().equals(user.getRoleCategory())) {
                return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
            }
        }else{
            //其他 无法创建子账号
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        Long rootId = RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())?loginUser.getId():loginUser.getRootParent();

        Long roleCountMAX = 0L;
        Long roleCount = 0L;
         //校验角色数量
         //todo 后续角色数量如果需要改成动态的注意这里
        if(RoleEnumType.SUPER_USER.getKey().equals(user.getRoleCategory())){
            //创建主账号  无法在这个接口创建主账号
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }else if(RoleEnumType.MANAGER.getKey().equals(user.getRoleCategory())){
            //创建管理员
            roleCountMAX = MANAGERMAXCOUNT;
            roleCount = userMapper.findRoleCount(rootId,RoleEnumType.MANAGER.getKey(),null);
        }else if(RoleEnumType.SUB_APP_MANAGER.getKey().equals(user.getRoleCategory())){
            //创建子应用管理员
            roleCountMAX = SUBAPPMANAGERMAXCOUNT;
            roleCount = userMapper.findRoleCount(rootId,RoleEnumType.SUB_APP_MANAGER.getKey(),loginUser.getId());
        }
        if(roleCount >= roleCountMAX){
            return ResultGenerator.genResult(ResultCode.ROLE_REACH_MAX);
        }

        //创建用户
        User subUser = new User();
        subUser.setUsername(email);
        subUser.setStatus(-3);
        subUser.setCreateUser(loginUser.getId());
        subUser.setCreateTime(new Date());
        subUser.setOid(loginUser.getOid());
        subUser.setRootParent(rootId);
        subUser.setLeaderParent(loginUser.getId());
        subUser.setActualName(user.getActualName());
        subUser.setAuthConfig(false);
        subUser.setIsCreateApp(false);
        subUser.setRemark(user.getRemark());
        subUser.setRoleCategory(user.getRoleCategory());
        subUser.setSex(0);
        subUser.setPhone(phone);
        subUser.setHeadPortrait("avatar"+RandomUtil.randomInt(1,27));//随机生存头像  头像在数据库中格式: avater+ 1 ~ 26数字
        //设置用户来源
        User rootParent = authService.getRootParent(loginUser);
        subUser.setUserSource(rootParent.getUserSource());

        if(RoleUtil.isSuperUserOrManager(subUser)){
            subUser.setIsCreateApp(true);//如果是管理员将isCreateApp改为true
            subUser.setAuthConfig(true);//如果是管理员将AuthConfig改为true
        }

        //随机密码超时时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        String format = DateUtil.format(instance.getTime(), "yyyy-MM-dd HH:mm:ss");
        subUser.setRandomPwdPastTime(format);
        //生成10位的随机密码
        String randomPwd = RandomUtil.randomString(10);
        subUser.setPassword(passwordEncoder.encode(randomPwd));
        userMapper.insertSelective(subUser);


        //保存角色
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setUserId(subUser.getId());
        //用户角色表改为
        userAndRole.setRoleId((long)user.getRoleCategory());
        userAndRoleMapper.insert(userAndRole);

        //发送邮件
        try {
            mailService.sendNewPwd(subUser,randomPwd, MailEnumType.ACTIVATE);
            log.info("用户{}创建了一个子账号 角色:{} 子账号邮箱:{}",loginUser.getUsername(),RoleEnumType.CUSTOM_AUTH.getRoleName(subUser.getRoleCategory()),user.getUsername());
        } catch (Exception exception) {
            log.error("用户激活随机密码发送失败! 邮箱:{} ",email,exception);
        }

        UserOutpDTO userOutpDTO = new UserOutpDTO();
        BeanUtils.copyProperties(subUser,userOutpDTO);
        return ResultGenerator.genSuccessResult(userOutpDTO);
    }

    /**
     * 修改子账号信息
     * @param loginUserId 当前登录用户id
     * @param user 目标用户
     * @return
     */
    @Override
    public RestResult updateSubUser(Long loginUserId, User user) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);
        User targetUser = userMapper.selectByPrimaryKey(user.getId());

        //如果是目标用户是主账号无法通过该接口修改主账号信息
        if(RoleEnumType.SUPER_USER.getKey().equals(targetUser.getRoleCategory())){
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        User saveUser = new User();
        saveUser.setId(user.getId());
        saveUser.setActualName(user.getActualName());
        saveUser.setModifyUser(loginUser.getId());
        saveUser.setModifyTime(new Date());
        saveUser.setRemark(user.getRemark());


        //被修改用户当前手机号为空可以修改
        if(StringUtils.isEmpty(targetUser.getPhone())
                || StringUtils.isEmpty(targetUser.getPhone().trim())){
            //目标手机号不能为空
            if(PatternUtil.isMobileNo(user.getPhone())){
                saveUser.setPhone(user.getPhone());
            }else{
                return ResultGenerator.genResult(ResultCode.PHONE_FORMAT_ERROR);
            }
        }

        //判断角色是否修改
        if(!targetUser.getRoleCategory().equals(user.getRoleCategory())){

            if (!checkSubUserUpdateRole(loginUser, user)){
                return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
            }

            saveUser.setRoleCategory(user.getRoleCategory());

            //todo 如果改动角色则删除现有的权限  后续如果有其他权限 注意改这里
            appAuthMapper.deleteByUserId(targetUser.getId());

            //将用户状态改为未分配权限
            saveUser.setAuthConfig(false);

            //修改角色时同步修改用户角色表
            UserAndRole userAndRole = new UserAndRole();
            userAndRole.setRoleId((long)user.getRoleCategory());
            Example uarExample = new Example(UserAndRole.class);
            uarExample.and().andEqualTo("userId",targetUser.getId());
            userAndRoleMapper.updateByExampleSelective(userAndRole,uarExample);

        }
        userMapper.updateByPrimaryKeySelective(saveUser);

        return ResultGenerator.genSuccessResult();
    }

    /**
     * 校验被修改用户角色的合法性
     * @param loginUser 当前登录用户
     * @param targetUser 目标用户
     * @return 是否可以操作
     */
    private boolean checkSubUserUpdateRole(User loginUser,User targetUser) {
        //校验改动的角色
        if (RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())) {
            //主账号可以改管理员 子应用管理员 普通账号  如果被被修改的角色目标角色是主账号无法修改
            if (RoleEnumType.SUPER_USER.getKey().equals(targetUser.getRoleCategory())) {
                return false;
            }
        } else if (RoleEnumType.MANAGER.getKey().equals(loginUser.getRoleCategory())) {
            //管理员可以改 子应用管理员  普通账号   如果被被修改的角色目标角色是主账号或者管理员无法修改
            if (RoleEnumType.SUPER_USER.getKey().equals(targetUser.getRoleCategory())
                    || RoleEnumType.MANAGER.getKey().equals(targetUser.getRoleCategory())) {
                return false;
            }
        } else if (RoleEnumType.SUB_APP_MANAGER.getKey().equals(loginUser.getRoleCategory())) {
            //子应用管理员可以改 普通账号   如果被被修改的角色目标角色是主账号 管理员 子应用管理员无法修改
            if (RoleEnumType.SUPER_USER.getKey().equals(targetUser.getRoleCategory())
                    || RoleEnumType.MANAGER.getKey().equals(targetUser.getRoleCategory())
                    || RoleEnumType.SUB_APP_MANAGER.getKey().equals(targetUser.getRoleCategory())) {
                return false;
            }
        } else {
            //普通账号无法修改
            return false;
        }
        return true;
    }

    /**
     * 查询子账号信息
     * @param loginUserId 当前登陆账号id
     * @param userId 目标用户id
     * @return
     */
    @Override
    public RestResult findSubUser(Long loginUserId, Long userId) {
        User loginUser = userMapper.selectByPrimaryKey(loginUserId);
        User targetUser = userMapper.selectByPrimaryKey(userId);

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        UserOutpDTO userOutpDTO = new UserOutpDTO();
        BeanUtils.copyProperties(targetUser,userOutpDTO);

        return ResultGenerator.genSuccessResult(userOutpDTO);
    }

    /**
     * 用户列表
     * @param loginUserId 当前登录用户的id
     * @param status 状态
     * @param roleCategory 角色
     * @param desc 排序方式  默认按照创建时间倒序
     * @param search 搜索条件
     * @return
     */
    @Override
    public RestResult infos(Long loginUserId, String status,String roleCategory,String desc,String search) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);

        Long rootId = RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())?loginUser.getId():loginUser.getRootParent();
        Example example = new Example(User.class);

        //判断角色
        if (RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())) {
            //主账号
            example.and().andEqualTo("rootParent",rootId);
        }else if( RoleEnumType.MANAGER.getKey().equals(loginUser.getRoleCategory())){
            //管理员
            example.and().andEqualTo("rootParent",rootId);
            example.and().andNotEqualTo("id",loginUser.getId());
            example.and().andNotEqualTo("roleCategory",RoleEnumType.MANAGER.getKey());
        }else if(RoleEnumType.SUB_APP_MANAGER.getKey().equals(loginUser.getRoleCategory())){
            //子应用管理员
            example.and().andEqualTo("rootParent",rootId);
            example.and().andEqualTo("leaderParent",loginUser.getId());
            example.and().andNotEqualTo("id",loginUser.getId());
        }else{
            //其他
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }
        example.and().andEqualTo("delFlag",false);

        //状态
        if (!StringUtils.isEmpty(status)){
            example.and().andEqualTo("status",status);
        }

        //角色
        if(!StringUtils.isEmpty(roleCategory)){
            example.and().andEqualTo("roleCategory",roleCategory);
        }

        //搜索字段  根据邮箱和名称模糊搜索
        if(!StringUtils.isEmpty(search)){
            example.and().orLike("actualName","%"+search+"%").orLike("username","%"+search+"%");
        }

        //排序方式  默认按照创建时间倒序
        if(!StringUtils.isEmpty(desc)){
            if("asc".equals(desc)){
                example.orderBy("createTime").asc();
            }else{
                example.orderBy("createTime").desc();
            }
        }else{
            example.orderBy("createTime").desc();
        }

        List<User> users = userMapper.selectByExample(example);


        //过滤数据
        List<UserOutpDTO> userOutpDTOS = new LinkedList<>();
        users.forEach(v -> {
            //状态计数
            UserOutpDTO userOutpDTO = new UserOutpDTO();
            BeanUtils.copyProperties(v,userOutpDTO);
            //调用枚举的方法  根据角色的key获取角色名
            userOutpDTO.setRoleName(RoleEnumType.SUPER_USER.getRoleName(v.getRoleCategory()));
            userOutpDTOS.add(userOutpDTO);
        });

        //查询状态对应的子用户数量
        Map count = new HashMap<>();
        if (RoleEnumType.SUPER_USER.getKey().equals(loginUser.getRoleCategory())) {
            List<Map> statusCount = userMapper.findStatusCount(rootId);
            statusCount.forEach(v -> {
                count.put(v.get("status"),v.get("count"));
            });
        }else if (RoleEnumType.MANAGER.getKey().equals(loginUser.getRoleCategory())) {
            List<Map> statusCount = userMapper.findStatusCountByManager(loginUser.getId());
            statusCount.forEach(v -> {
                count.put(v.get("status"),v.get("count"));
            });
        }


        //补零
        count.putIfAbsent(1, 0); //启用
        count.putIfAbsent(-3, 0);//未激活
        count.putIfAbsent(0, 0); //禁用

        Map<String,Object> result = new HashMap<>();
        result.put("list",userOutpDTOS);
        result.put("count",count);

        return ResultGenerator.genSuccessResult(result);
    }

    /**
     *
     * @param loginUserId 当前登录的用户
     * @param userId 目标用户id
     * @param status 状态 启用:true  禁用:false
     * @return
     */
    @Override
    public RestResult updateUsingStatus(Long loginUserId, Long userId, Boolean status) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);
        User targetUser = userMapper.selectByPrimaryKey(userId);

        //状态为未激活禁止修改启用状态
        if(targetUser.getStatus() == -3){
            return ResultGenerator.genFailResult("用户未激活");
        }

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        if(!status){//禁用用户时删除redis登录token
            deleteCacheUserToken(targetUser.getId());
        }

        //修改用户状态
        targetUser.setStatus(status?1:0);
        targetUser.setModifyUser(loginUser.getId());
        targetUser.setModifyTime(new Date());
        userMapper.updateByPrimaryKeySelective(targetUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 功能描述:根据用户id删除redis的用户凭证
     */
    public void deleteCacheUserToken(Long userId){
        String userIdStr = String.valueOf(userId);
        String token = stringRedisTemplate.opsForValue().get(userIdStr);
        if(StrUtil.isNotEmpty(token)){
            stringRedisTemplate.delete(userIdStr);
            tokenServices.revokeToken(token);
        }
    }

    /**
     * 重新发送激活邮件
     * @param loginUserId 当前登录的用户
     * @param userId 目标用户id
     * @return
     */
    @Override
    public RestResult resendMail(Long loginUserId, Long userId) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);

        User targetUser = userMapper.selectByPrimaryKey(userId);
        if (!targetUser.getStatus().equals(-3)) {
            return ResultGenerator.genFailResult("该账号已激活");
        }

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        //简单的防刷
        if(!mailService.isRepetitionSend(targetUser.getUsername())){
            return ResultGenerator.genResult(ResultCode.SERVER_BUSY);
        }

        //随机密码过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        String format = DateUtil.format(instance.getTime(), "yyyy-MM-dd HH:mm:ss");
        targetUser.setRandomPwdPastTime(format);

        //生成随机密码
        String randomPwd = RandomUtil.randomString(10);
        targetUser.setPassword(passwordEncoder.encode(randomPwd));
        targetUser.setModifyTime(new Date());
        targetUser.setModifyUser(loginUser.getId());
        userMapper.updateByPrimaryKeySelective(targetUser);

        //发送邮件
        try {
            mailService.sendNewPwd(targetUser,randomPwd,MailEnumType.ACTIVATE);
            log.error("用户激活随机密码重发成功! 邮箱:{} ",targetUser.getUsername());

        } catch (Exception exception) {
            log.error("用户激活随机密码重发失败! 邮箱:{} 异常信息:{}",targetUser.getUsername(),exception.getMessage());
        }

        return ResultGenerator.genSuccessResult();
    }

    /**
     * 删除未激活子账号
     * @param loginUserId 当前登录用户id
     * @param userId 目标id
     * @return
     */
    @Override
    public RestResult deleteSubUser(Long loginUserId, Long userId) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);

        User targetUser = userMapper.selectByPrimaryKey(userId);

        if (!targetUser.getStatus().equals(-3)) {
            return ResultGenerator.genFailResult("该账号已激活，无法删除");
        }

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        //todo 删除该用户的权限  后续如果有其他权限 注意改这里
        appAuthMapper.deleteByUserId(userId);

        //逻辑删除用户
        targetUser.setDelFlag(true);
        targetUser.setModifyTime(new Date());
        targetUser.setModifyUser(loginUser.getId());
        userMapper.updateByPrimaryKeySelective(targetUser);


        return ResultGenerator.genSuccessResult();
    }


    /**
     * 添加权限
     * @param loginUserId 当前登录用户
     * @param user 目标用户id
     * @return
     */
    @Override
    public RestResult addAuth(Long loginUserId,User user) {

        User logInUser = userMapper.selectByPrimaryKey(loginUserId);
        User target = userMapper.selectByPrimaryKey(user.getId());

        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(logInUser, target)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        List<AppAuth> appAuths = user.getAppAuths();
        if (!CollectionUtils.isEmpty(appAuths)) {
            //校验app权限
            List<Long> collect = appAuths.stream().map(AppAuth::getAppId).collect(Collectors.toList());

            //校验前端传来的app  过滤掉非标情况下出现的app
            List<App> apps = authService.filterUserAppAuthByAppId(logInUser, collect);
            Set<Long> filterAppids = apps.stream().map(App::getId).collect(Collectors.toSet());

            //删除现有的权限
            appAuthMapper.deleteByUserId(target.getId());

            List<AppAuth> saveAppAuth = new LinkedList<>();
            for (AppAuth appAuth : appAuths) {

                //如果app不在过滤后的app集合内 无法分配权限
                if (filterAppids.contains(appAuth.getAppId())) {

                    AppAuth build = AppAuth.builder()
                            .appId(appAuth.getAppId())
                            .createUser(logInUser.getId())
                            .userId(target.getId())
                            .createTime(new Date())
                            .status(1)
                            .roleCategory(target.getRoleCategory())
//                        todo  后续添加其他权限注意该字段
//                        .controlAuth()
                            .build();

                    saveAppAuth.add(build);
                }
            }

            //分配权限
            appAuthMapper.insertList(saveAppAuth);

            //更改用户是否分配权限状态
            target.setAuthConfig(true);
        }else{
            //删除目标用户现有的权限
            appAuthMapper.deleteByUserId(target.getId());
            //更新用户状态
            target.setAuthConfig(false);
        }
        //更新用户状态
        Boolean isCteateApp= user.getIsCreateApp() == null?false:user.getIsCreateApp();
        target.setIsCreateApp(isCteateApp);
        target.setModifyUser(logInUser.getId());
        target.setModifyTime(new Date());
        userMapper.updateByPrimaryKeySelective(target);

        return ResultGenerator.genSuccessResult();
    }



    /**
     * 查询子用户的权限
     * @param loginUserId 当前登录用户
     * @param userId 目标用户
     * @return
     */
    @Override
    public RestResult findAuth(Long loginUserId, Long userId) {

        User loginUser = userMapper.selectByPrimaryKey(loginUserId);
        User targetUser = userMapper.selectByPrimaryKey(userId);

        List<App> apps = authService.getAppByUser(targetUser);


        //校验当前登录用户是否可以操作目标用户
        if (!authService.checkloginUserAuth(loginUser, targetUser)) {
            return ResultGenerator.genResult(ResultCode.FORBID_OPERATION);
        }

        List<AppAuth> ownedApp = new LinkedList<>();
        if(!CollectionUtils.isEmpty(apps)){
            apps.forEach(v -> {
                AppAuth build = AppAuth.builder().userId(targetUser.getId())
                        .appId(v.getId()).build();
                ownedApp.add(build);
            });
        }

        targetUser.setAppAuths(ownedApp);

        return ResultGenerator.genSuccessResult(targetUser);
    }
}
