package com.qmth.paper.library.common.service.impl;

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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.paper.library.common.bean.auth.AuthBean;
import com.qmth.paper.library.common.bean.dto.UserDto;
import com.qmth.paper.library.common.bean.dto.VerifyCodeCheckDto;
import com.qmth.paper.library.common.bean.dto.excel.DescribeImportDto;
import com.qmth.paper.library.common.bean.dto.excel.SysUserImportDto;
import com.qmth.paper.library.common.bean.params.ApproveUserResult;
import com.qmth.paper.library.common.bean.params.UserSaveParams;
import com.qmth.paper.library.common.bean.result.LoginResult;
import com.qmth.paper.library.common.bean.result.RoleResult;
import com.qmth.paper.library.common.bean.result.SysUserResult;
import com.qmth.paper.library.common.bean.result.UserRoleNameResult;
import com.qmth.paper.library.common.config.DictionaryConfig;
import com.qmth.paper.library.common.contant.SpringContextHolder;
import com.qmth.paper.library.common.contant.SysSettingConstant;
import com.qmth.paper.library.common.contant.SystemConstant;
import com.qmth.paper.library.common.entity.*;
import com.qmth.paper.library.common.enums.AppSourceEnum;
import com.qmth.paper.library.common.enums.ExceptionResultEnum;
import com.qmth.paper.library.common.enums.FieldUniqueEnum;
import com.qmth.paper.library.common.enums.RoleTypeEnum;
import com.qmth.paper.library.common.mapper.SysUserMapper;
import com.qmth.paper.library.common.service.*;
import com.qmth.paper.library.common.util.Base64Util;
import com.qmth.paper.library.common.util.ResultUtil;
import com.qmth.paper.library.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xf
 * @since 2021-03-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRolePrivilegeService sysRolePrivilegeService;

    @Resource
    private LibraryCommonService commonService;

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    SysUserService sysUserService;

    @Resource
    SysOrgService sysOrgService;

    @Resource
    DictionaryConfig dictionaryConfig;

    @Resource
    BasicSchoolService basicSchoolService;

    @Resource
    LibraryCommonService libraryCommonService;

    @Resource
    SysRoleGroupMemberService sysRoleGroupMemberService;

    @Resource
    CommonCacheService commonCacheService;


    @Override
    public IPage<UserDto> listForPrintSystem(String userInfo, Long orgId, String roleId, Boolean enable, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());

        Page<UserDto> page = new Page<>(pageNumber, pageSize);
        IPage<UserDto> userDtoIPage = this.baseMapper.listForPrintSystem(page, schoolId, SystemConstant.translateSpecificSign(userInfo), orgId, roleId, enable);
        if (userDtoIPage.getRecords().size() > 0) {
            userDtoIPage.getRecords().forEach(m -> {
                //角色
                List<SysRole> roles = sysRoleService.listRolesByUserId(Long.valueOf(m.getId()));
                m.setRoles(roles);
            });
        }
        return userDtoIPage;
    }

    @Transactional
    @Override
    public Map<String, Object> executeSysUserImportLogic(List<LinkedMultiValueMap<Integer, Object>> finalList, Map<String, Object> map) {
        SysUser requestUser = (SysUser) map.get(SystemConstant.SYS_USER);
        Long schoolId = requestUser.getSchoolId();
        List<Long> userIdList = new ArrayList<>();
        for (int i = 0; i < finalList.size(); i++) {
            LinkedMultiValueMap<Integer, Object> excelMap = finalList.get(i);
            List<Object> sysUserImportDtoList = excelMap.get(i);
            assert sysUserImportDtoList != null;
            if (sysUserImportDtoList.get(0) instanceof DescribeImportDto) {
                continue;
            }

            //  处理机构
            if (sysUserImportDtoList.get(0) instanceof SysUserImportDto) {
                List<SysUserImportDto> datasource = sysUserImportDtoList.stream().map(e -> {
                    SysUserImportDto sysUserImportDto = new SysUserImportDto();
                    BeanUtils.copyProperties(e, sysUserImportDto);
                    return sysUserImportDto;
                }).collect(Collectors.toList());
                // 机构信息
                List<String> orgInfoList = datasource.stream().map(SysUserImportDto::getOrgName).distinct().collect(Collectors.toList());
                // 提前创建或获取机构信息并存入map
                Map<String, Long> orgInfoMap = sysOrgService.createOrGetOrgByOrgInfo(orgInfoList, requestUser);
                for (SysUserImportDto sysUserImportDto : datasource) {
                    String name = sysUserImportDto.getName();
                    String loginName = sysUserImportDto.getLoginName();
//                    String phoneNumber = sysUserImportDto.getPhoneNumber();
                    String orgName = sysUserImportDto.getOrgName();
                    if (!orgInfoMap.containsKey(orgName)) {
                        throw ExceptionResultEnum.ERROR.exception("在解析的机构map集合中，没有找到excel数据中的用户机构名称【" + orgName + "】");
                    }
                    // 直接解析机构id
                    Long orgId = orgInfoMap.get(orgName);
                    String roleName = sysUserImportDto.getRoleName();

                    UserSaveParams userSaveParams = new UserSaveParams();

                    LinkedHashSet<Long> roleIdList = this.analyzeRoleName(schoolId, roleName);

                    SysUser oldUser = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getLoginName, loginName).eq(SysUser::getSchoolId, schoolId));
                    Long oldUserId = null;
                    Set<Long> oldRoleIdSet = new HashSet<>();
                    if (Objects.nonNull(oldUser)) {
                        oldUserId = oldUser.getId();
                        oldRoleIdSet = new HashSet<>(sysRoleService.getUserRoles(oldUserId));
                    }
                    String code = loginName;
                    if (SystemConstant.longNotNull(oldUserId)) {
                        // 编辑
                        userSaveParams.setId(oldUserId);
                        loginName = oldUser.getLoginName();
                    }
                    userSaveParams.setOrgId(orgId);
                    userSaveParams.setRealName(name);
                    userSaveParams.setLoginName(loginName);
                    userSaveParams.setRoleIds(roleIdList.toArray(new Long[0]));
//                    if (SystemConstant.strNotNull(phoneNumber)) {
//                        userSaveParams.setMobileNumber(phoneNumber);
//                    }
                    userSaveParams.setCode(code);
                    userSaveParams.setSchoolId(schoolId);
                    Long upUserId = this.saveUserCommon(userSaveParams, requestUser.getId());
                    userIdList.add(upUserId);
                }
            }
        }
        map.put("userIdList", userIdList);
        return map;
    }

    @Transactional
    @Override
    public Long saveUser(UserSaveParams userSaveParams) {
        return saveUserCommon(userSaveParams, null);
    }

    @Transactional
    @Override
    public boolean enable(SysUser user) throws NoSuchAlgorithmException, IllegalAccessException {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysUser::getEnable, user.getEnable()).eq(SysUser::getId, user.getId());
        boolean success = this.update(updateWrapper);
        //如果状态为禁用，需要踢下线重新登录
        if (!user.getEnable()) {
            commonService.removeUserInfo(user.getId(), true);
        }
        return success;
    }

    @Override
    public boolean resetPassword(Long id) throws NoSuchAlgorithmException {
        String initPassword = commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_INIT_PASSWORD);
        String md5Password = Base64Util.encode(StringUtils.isNoneBlank(initPassword) ? initPassword.getBytes() : "123456".getBytes());

        SysUser user = this.getById(id);
        String oldPassword = user.getPassword();
        user.setPassword(md5Password);

        //如果原密码和旧密码不一致，需要重新登录
        if (!Objects.equals(user.getPassword(), oldPassword)) {
            commonService.removeUserInfo(user.getId(), false);
        }
        return this.updateById(user);
    }

    @Transactional
    @Override
    public LoginResult updatePassword(SysUser user) throws NoSuchAlgorithmException {
        SysUser sysUser = this.getById(user.getId());
        if (sysUser == null) {
            throw ExceptionResultEnum.ERROR.exception("用户不存在");
        }
        if (!StringUtils.equals(sysUser.getPassword(), user.getOldPassword())) {
            throw ExceptionResultEnum.ERROR.exception("原密码不正确");
        }
        String newPwd = user.getPassword();
        String mobileNumber = user.getMobileNumber();
        String verifyCode = user.getVerifyCode();
        String oldPassword = user.getOldPassword();
        if (SystemConstant.strNotNull(newPwd)) {
            // 参数中存在密码 -》 更新密码
            if (SystemConstant.strNotNull(oldPassword) && oldPassword.equals(newPwd)) {
                throw ExceptionResultEnum.ERROR.exception("新密码和旧密码一致请重新输入");
            }
            sysUser.setPwdCount(sysUser.getPwdCount() == null ? 1 : sysUser.getPwdCount() + 1);
            sysUser.setPwdUpdateTime(System.currentTimeMillis());
            sysUser.setPassword(newPwd);
        }
        if (SystemConstant.strNotNull(mobileNumber)) {
            // 参数中存在手机号 -》 更新手机号
            if (!SystemConstant.strNotNull(verifyCode)) {
                throw ExceptionResultEnum.ERROR.exception("验证码不存在");
            }
            this.checkSmsCode(user.getId(), mobileNumber, verifyCode);
            // 更新电话

            SysUser checkMobileNumber = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, sysUser.getSchoolId()).eq(SysUser::getEnable, true).eq(SysUser::getMobileNumber, mobileNumber));
            if (Objects.nonNull(checkMobileNumber)) {
                if (!checkMobileNumber.getId().equals(sysUser.getId())) {
                    throw ExceptionResultEnum.ERROR.exception("用户手机号【" + mobileNumber + "】重复");
                }
            }

            sysUser.setMobileNumber(mobileNumber);
        }
        boolean success = this.updateById(sysUser);
        if (!success) {
            throw ExceptionResultEnum.ERROR.exception("用户更新失败");
        }

        //如果原密码和旧密码不一致，且用户已经登陆，需要重新登录
        Object object = ServletUtil.getRequest().getAttribute(SystemConstant.SESSION);
        if (Objects.nonNull(object)) {
            if (SystemConstant.strNotNull(newPwd)) {
                if (!Objects.equals(user.getOldPassword(), sysUser.getPassword())) {
                    commonService.removeUserInfo(sysUser.getId(), false);
                }
            } else if (SystemConstant.strNotNull(mobileNumber)) {
                if (!Objects.equals(mobileNumber, sysUser.getMobileNumber())) {
                    commonService.removeUserInfo(sysUser.getId(), false);
                }
            }
        }
        // 如果不是共用验证码 再过期
        if (Objects.nonNull(verifyCode) && !dictionaryConfig.smsDomain().getSmsNormalCode().equals(verifyCode)) {
            sysUserService.expiredVerifyCode(sysUser.getId(), sysUser.getMobileNumber());
        }

        // 登录
        BasicSchool basicSchool;
        String schoolCode = null;
        basicSchool = basicSchoolService.getById(sysUser.getSchoolId());
        if (Objects.isNull(basicSchool)) {
            List<Long> userRoles = sysRoleService.getUserRoles(sysUser.getId());
            List<SysRole> sysRoleList = sysRoleService.list(new QueryWrapper<SysRole>().lambda().in(SysRole::getId, userRoles));
            Set<RoleTypeEnum> roleType = sysRoleList.stream().map(SysRole::getType).collect(Collectors.toSet());
            if (roleType.contains(RoleTypeEnum.ADMIN)) {
                schoolCode = SystemConstant.ADMIN_CODE;
            }
        } else {
            schoolCode = basicSchool.getCode();
        }
        if (!schoolCode.equalsIgnoreCase(SystemConstant.ADMIN_CODE)) {
            basicSchool = basicSchoolService.getBySchoolCode(schoolCode);
            if (Objects.isNull(basicSchool)) {
                throw ExceptionResultEnum.SCHOOL_NO_DATA.exception();
            }
            if (Objects.nonNull(basicSchool.getEnable()) && !basicSchool.getEnable()) {
                throw ExceptionResultEnum.SCHOOL_ENABLE.exception();
            }
        }
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysUser::getLoginName, sysUser.getLoginName());
        if (!schoolCode.equalsIgnoreCase(SystemConstant.ADMIN_CODE)) {
            wrapper.lambda().eq(SysUser::getSchoolId, basicSchool.getId());
        }
        List<SysUser> userList = sysUserService.list(wrapper);
        //用户不存在
        if (Objects.isNull(userList) || userList.size() == 0) {
            throw ExceptionResultEnum.USER_NO_DATA.exception();
        }
        if (schoolCode.equalsIgnoreCase(SystemConstant.ADMIN_CODE)) {
            userList.forEach(o -> {
                AuthBean authBean = libraryCommonService.getUserAuth(o.getId());
                if (Objects.nonNull(authBean) && Objects.nonNull(authBean.getRoleList()) && authBean.getRoleList().size() > 0) {
                    if (Objects.nonNull(authBean.getSchool())) {
                        throw ExceptionResultEnum.ERROR.exception("用户无法通过当前页面登录");
                    }
                }
            });
        }
        if (userList.size() > 1) {
            throw ExceptionResultEnum.ERROR.exception("查询的用户有多条");
        }
        if (Objects.nonNull(sysUser.getSchoolId()) && sysUser.getSchoolId().longValue() != basicSchool.getId().longValue()) {
            throw ExceptionResultEnum.ERROR.exception("用户学校不匹配");
        }
        // 校验验证码
        sysUserService.checkSmsCode(sysUser.getId(), sysUser.getMobileNumber(), dictionaryConfig.smsDomain().getSmsNormalCode());

        return libraryCommonService.login(sysUser.getPassword(), sysUser, AppSourceEnum.SYSTEM);
    }

    @Transactional
    @Override
    public boolean bindRoles(SysUser sysUser) {
        Long[] roleIds = sysUser.getRoleIds();
        if (roleIds.length == 0) {
            throw ExceptionResultEnum.ERROR.exception("请选择角色");
        }

        // 删除
        sysUserRoleService.removeByUserId(sysUser.getId());

        List<SysUserRole> list = new ArrayList<>();
        for (Long roleId : roleIds) {
            List<SysRolePrivilege> rolePrivileges = sysRolePrivilegeService.listByRoleId(roleId);
            for (SysRolePrivilege rolePrivilege : rolePrivileges) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getId());
                userRole.setRoleId(roleId);
                userRole.setPrivilegeId(rolePrivilege.getPrivilegeId());
                list.add(userRole);
            }
        }
        return sysUserRoleService.saveBatch(list);
    }

    @Override
    public List<SysUser> listByOrgId(Long id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getOrgId, id);
        return this.list(queryWrapper);
    }

    /**
     * 保存用户公用
     *
     * @param userSaveParams userSaveParams
     * @return 新增或更新的用户id
     */
    @Transactional
    public Long saveUserCommon(UserSaveParams userSaveParams, Long requestUserId) {
        SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
        Long resultUserId = null;
        try {
            Long schoolId = userSaveParams.getSchoolId();
            if (schoolId == null) {
                schoolId = Objects.nonNull(ServletUtil.getRequestHeaderSchoolIdByNotVaild()) ? Long.valueOf(ServletUtil.getRequestHeaderSchoolIdByNotVaild().toString()) : null;
            }
            if (!SystemConstant.longNotNull(requestUserId)) {
                SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
                requestUserId = requestUser.getId();
            }

            String mobileNumber = userSaveParams.getMobileNumber();
            // 手机号检验
            if (SystemConstant.strNotNull(mobileNumber)) {
                SysUser checkMobileNumber = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getEnable, true).eq(SysUser::getMobileNumber, mobileNumber));
                if (Objects.nonNull(checkMobileNumber)) {
                    if (!checkMobileNumber.getId().equals(userSaveParams.getId())) {
                        throw ExceptionResultEnum.ERROR.exception("用户手机号【" + mobileNumber + "】重复");
                    }
                }
            }

            Gson gson = new Gson();
            userSaveParams.setSchoolId(schoolId);
            SysUser sysUser = gson.fromJson(gson.toJson(userSaveParams), SysUser.class);
            if (Objects.isNull(sysUser.getId())) {//新增用户
                sysUser.insertInfo(requestUserId);
                sysUser.setEnable(true);
                sysUserService.save(sysUser);
                resultUserId = sysUser.getId();
                commonService.addUserRolePrivilege(sysUser, userSaveParams.getRoleIds());
            } else {//修改用户
                resultUserId = sysUser.getId();
                List<SysUserRole> sysUserRoleList = libraryCommonService.getUserRolePrivilege(sysUser.getId());
                List<Long> userRolesList = Arrays.asList(userSaveParams.getRoleIds());
                Set<Long> dbUserRolesList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toSet());
                int count = (int) dbUserRolesList.stream().filter(s -> !userRolesList.contains(s)).count();
                Set<Long> removeRoleIds = dbUserRolesList.stream().filter(s -> !userRolesList.contains(s)).collect(Collectors.toSet());
                SysUser dbUser = sysUserService.getById(sysUser.getId());
                sysUserService.update(new UpdateWrapper<SysUser>().lambda()
                        .eq(SysUser::getId, sysUser.getId())
                        .set(SysUser::getSchoolId, userSaveParams.getSchoolId())
                        .set(SysUser::getLoginName, sysUser.getLoginName())
                        .set(SysUser::getRealName, sysUser.getRealName())
                        .set(SysUser::getMobileNumber, sysUser.getMobileNumber())
                        .set(SysUser::getOrgId, sysUser.getOrgId())
                        .set(SysUser::getEnable, dbUser.getEnable())
                        .set(SysUser::getUpdateId, requestUserId)
                        .set(SysUser::getUpdateTime, System.currentTimeMillis())
                );
                //如果修改了角色，需要重新登录
                if (count > 0 || dbUserRolesList.size() != userRolesList.size()) {
                    QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
                    sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
                    sysUserRoleService.remove(sysUserRoleQueryWrapper);

                    if (Objects.nonNull(removeRoleIds) && removeRoleIds.size() > 0) {
                        QueryWrapper<SysRoleGroupMember> sysRoleGroupMemberQueryWrapper = new QueryWrapper<>();
                        sysRoleGroupMemberQueryWrapper.lambda().eq(SysRoleGroupMember::getUserId, sysUser.getId())
                                .in(SysRoleGroupMember::getRoleId, removeRoleIds);
                        sysRoleGroupMemberService.remove(sysRoleGroupMemberQueryWrapper);
                    }

                    commonService.addUserRolePrivilege(sysUser, userSaveParams.getRoleIds());
                    commonService.removeUserInfo(sysUser.getId(), true);
                } else if (!dbUser.getOrgId().equals(sysUser.getOrgId())) {
                    commonService.removeUserInfo(sysUser.getId(), true);
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return resultUserId;
    }


    /**
     * 根据id获取
     *
     * @param id
     * @return
     */
    @Override
    public List<ApproveUserResult> findById(Long id) {
        return sysUserMapper.findById(id);
    }


    @Override
    public void checkSmsCode(Long userId, String mobileNumber, String code) {
        String verificationCodeLoginEnable = commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_VERIFICATION_CODE_LOGIN_ENABLE);
        if (Objects.nonNull(verificationCodeLoginEnable) && (verificationCodeLoginEnable.equals("true") || verificationCodeLoginEnable.equals("1"))) {
            if (Objects.isNull(code)) {
                throw ExceptionResultEnum.ERROR.exception("验证码为空");
            }
            if (!dictionaryConfig.smsDomain().getSmsNormalCode().equals(code)) {
                List<VerifyCodeCheckDto> verifyCodeCheckDtoList = this.baseMapper.findVerifyCodeByUser(userId, mobileNumber);
                if (verifyCodeCheckDtoList.size() < 1) {
                    throw ExceptionResultEnum.ERROR.exception("请确认已经发送了验证码");
                }
                VerifyCodeCheckDto accessControl = verifyCodeCheckDtoList.get(0);
                if (accessControl == null || !accessControl.getVerifyCode().equals(code)) {
                    throw ExceptionResultEnum.ERROR.exception("短信验证码错误，请仔细核对后再次输入");
                }

                if (new Date(accessControl.getExpireTime()).before(new Date())) {
                    throw ExceptionResultEnum.ERROR.exception("短信验证码已过期");
                }
            }
        }
    }

    @Transactional
    @Override
    public void expiredVerifyCode(Long userId, String mobileNumber) {
        String verificationCodeLoginEnable = commonCacheService.getSysSettingGlobal().get(SysSettingConstant.SYS_VERIFICATION_CODE_LOGIN_ENABLE);
        if (Objects.nonNull(verificationCodeLoginEnable) && (verificationCodeLoginEnable.equals("true") || verificationCodeLoginEnable.equals("1"))) {
            int count = this.baseMapper.updateVerifyCodeExpiredTime(userId, mobileNumber);
            if (count != 1) {
                throw ExceptionResultEnum.ERROR.exception("验证码过期失败");
            }
        }
    }

    /**
     * 查找用户角色名
     *
     * @param userIds
     * @return
     */
    @Override
    public List<UserRoleNameResult> selectRoleNames(List<Long> userIds) {
        return sysUserMapper.selectRoleNames(userIds);
    }

    /**
     * 根据id集合获取
     *
     * @param ids
     * @return
     */
    @Override
    public List<ApproveUserResult> findByIdsForResult(List<Long> ids) {
        return sysUserMapper.findByIdsForResult(ids);
    }

    @Override
    public List<Long> findOrgIdListByUserId(Long userId) {
        List<Long> orgIdList = new ArrayList<>();
        Long orgId = this.getById(userId).getOrgId();
        if (SystemConstant.longNotNull(orgId)) {
            orgIdList.add(orgId);
        }
        return orgIdList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public List<SysUserResult> findSysUserResultList() {
        Long schoolId = SystemConstant.convertIdToLong(String.valueOf(ServletUtil.getRequestHeaderSchoolId()));
        List<SysUser> sysUserDatasource = sysUserService.list(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId));
        List<SysRole> sysRoleDatasource = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getSchoolId, schoolId));
        List<SysUserRole> sysUserRoleDatasource = sysUserRoleService.list();

        return sysUserDatasource.stream().flatMap(e -> {
            Set<Long> roleIdSet = sysUserRoleDatasource.stream().filter(ur -> e.getId().equals(ur.getUserId())).map(SysUserRole::getRoleId).collect(Collectors.toSet());
            List<RoleResult> roleResultCellList = new ArrayList<>();
            if (roleIdSet.size() > 0) {
                roleResultCellList = sysRoleDatasource.stream().filter(r -> roleIdSet.contains(r.getId())).flatMap(rr -> {
                    RoleResult roleResult = new RoleResult();
                    roleResult.setRoleId(rr.getId());
                    roleResult.setRoleName(rr.getName());
                    return Stream.of(roleResult);
                }).collect(Collectors.toList());
            }
            SysUserResult sysUserResult = new SysUserResult();
            sysUserResult.setId(e.getId());
            sysUserResult.setLoginName(e.getLoginName());
            sysUserResult.setRealName(e.getRealName());
            sysUserResult.setMobileNumber(e.getMobileNumber());
            sysUserResult.setOrgId(e.getOrgId());
            sysUserResult.setRoleResultList(roleResultCellList);
            return Stream.of(sysUserResult);
        }).collect(Collectors.toList());
    }

    /**
     * 根据roleId和成员姓名获取
     *
     * @param roleId
     * @param name
     * @return
     */
    @Override
    public List<ApproveUserResult> findByRoldIdAndMemberName(Long roleId, String name) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return sysUserMapper.findByRoldIdAndMemberName(roleId, name, sysUser.getSchoolId());
    }

    @Transactional
    @Override
    public boolean delete(List<Long> ids) {
        this.removeByIds(ids);
        for (Long id : ids) {
            sysUserRoleService.removeByUserId(id);
        }
        return true;
    }

    @Override
    public boolean checkRoleIsAppoint(RoleTypeEnum roleTypeEnum, Long userId) {
        List<SysUserRole> sysRoleList = this.baseMapper.listByRoleTypeAndUserId(roleTypeEnum.name(), userId);
        return !sysRoleList.isEmpty();
    }

    /**
     * 根据角色名称获取角色id集合
     *
     * @param schoolId 学校id
     * @param roleName 角色名称组
     * @return 角色集合
     */
    private LinkedHashSet<Long> analyzeRoleName(Long schoolId, String roleName) {
        LinkedHashSet<Long> roleIdList = new LinkedHashSet<>();
        String[] arr = roleName.split(SystemConstant.COMMA);
        for (String cell : arr) {
            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
            sysRoleQueryWrapper.lambda().eq(SysRole::getEnable, true)
                    .eq(SysRole::getName, cell);
            if (!Objects.isNull(RoleTypeEnum.convertDescToEnum(cell))) {
                // 内置角色有该角色时，使用内置角色
                sysRoleQueryWrapper.lambda().isNull(SysRole::getSchoolId);
            } else {
                // 内置角色没有，则为自定义角色，使用学校创建角色
                sysRoleQueryWrapper.lambda().eq(SysRole::getSchoolId, schoolId);
            }
            SysRole sysRole = sysRoleService.getOne(sysRoleQueryWrapper);
            if (Objects.isNull(sysRole)) {
                throw ExceptionResultEnum.ERROR.exception("系统中不存在excel导入的角色【" + cell + "】");
            }
            roleIdList.add(sysRole.getId());
        }
        return roleIdList;
    }
}
