package com.qmth.teachcloud.common.service.impl;

import com.alibaba.fastjson.JSON;
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.teachcloud.common.bean.auth.AuthBean;
import com.qmth.teachcloud.common.bean.dto.*;
import com.qmth.teachcloud.common.bean.dto.excel.SysUserImportDto;
import com.qmth.teachcloud.common.bean.dto.excel.export.SysUserErrorExportDto;
import com.qmth.teachcloud.common.bean.params.ApproveUserResult;
import com.qmth.teachcloud.common.bean.params.UserSaveParams;
import com.qmth.teachcloud.common.bean.params.UserSaveReportParams;
import com.qmth.teachcloud.common.bean.result.*;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.*;
import com.qmth.teachcloud.common.enums.*;
import com.qmth.teachcloud.common.mapper.SysUserMapper;
import com.qmth.teachcloud.common.service.*;
import com.qmth.teachcloud.common.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private BasicCourseService basicCourseService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRolePrivilegeService sysRolePrivilegeService;

    @Resource
    CommonCacheService commonCacheService;

    @Resource
    private TeachcloudCommonService commonService;

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    SysOrgService sysOrgService;

    @Resource
    SysUserService sysUserService;

    @Resource
    BasicSchoolService basicSchoolService;

    @Resource
    TeachcloudCommonService teachcloudCommonService;

    @Resource
    SysRoleGroupMemberService sysRoleGroupMemberService;

    @Resource
    BasicRoleDataPermissionService basicRoleDataPermissionService;

    @Override
    public IPage<UserDto> listForPrintSystem(String userInfo, Long orgId, String roleId, Boolean enable, Integer pageNumber, Integer pageSize) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionRule dpr = basicRoleDataPermissionService.findDataPermission(schoolId, requestUser.getId(), ServletUtil.getRequest().getServletPath());
        Page<UserDto> page = new Page<>(pageNumber, pageSize);
        IPage<UserDto> userDtoIPage = this.baseMapper.listForPrintSystem(page, schoolId, SystemConstant.translateSpecificSign(userInfo), orgId, roleId, enable, dpr);
        if (userDtoIPage.getRecords().size() > 0) {
            userDtoIPage.getRecords().forEach(m -> {
                //角色
                List<SysRole> roles = sysRoleService.listRolesByUserId(Long.valueOf(m.getId()));
                m.setRoles(roles);

                //课程
                List<BasicCourse> courses = basicCourseService.listCoursesByUserId(Long.valueOf(m.getId()));
                m.setCourses(courses);
            });
        }
        return userDtoIPage;
    }

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

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

                //课程
                List<BasicCourse> courses = basicCourseService.listCoursesByUserId(Long.valueOf(m.getId()));
                m.setCourses(courses);
            });
        }
        return userDtoIPage;
    }

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

    /**
     * 保存用户
     *
     * @return 结果
     */
    @Override
    public boolean saveUserReport(UserSaveReportParams userSaveReportParams) {
        Gson gson = new Gson();
        UserSaveParams userSaveParams = gson.fromJson(gson.toJson(userSaveReportParams), UserSaveParams.class);
        saveUserCommon(userSaveParams, null);
        return true;
    }

    @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());
        commonCacheService.updateUserCache(user.getId());
        boolean success = this.update(updateWrapper);
        //如果状态为禁用，需要踢下线重新登录
        if (!user.getEnable()) {
            commonService.removeUserInfo(user.getId(), true);
        }
        return success;
    }

    @Override
    public boolean enableReport(SysUser user) throws NoSuchAlgorithmException {
        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 {
        SysUser user = this.getById(id);
        BasicSchool basicSchool = commonCacheService.schoolCache(user.getSchoolId());
        String md5Password = StringUtils.isNoneBlank(basicSchool.getInitPassword()) ? basicSchool.getInitPassword() : Base64Util.encode(SystemConstant.INIT_PASSWORD.getBytes());

        String oldPassword = user.getPassword();
        user.setPassword(md5Password);

        //如果原密码和旧密码不一致，需要重新登录
        if (!Objects.equals(user.getPassword(), oldPassword)) {
            user.setPwdCount(0);
            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)) {
            // 校验验证码
            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);
                }
            }
        }
        // 如果不是共用验证码 再过期
        SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SMS_NORMAL_CODE);
        Optional.ofNullable(sysConfig).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置万能短信验证码"));
        if (Objects.nonNull(verifyCode) && !sysConfig.getConfigValue().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.listUserRoleIds(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 = commonCacheService.schoolCache(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 = teachcloudCommonService.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(), sysConfig.getConfigValue());

        return teachcloudCommonService.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 AssignTeacherDto listUser(String courseCode, String param) {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        QueryWrapper<BasicCourse> basicCourseQueryWrapper = new QueryWrapper<>();
        basicCourseQueryWrapper.lambda().eq(BasicCourse::getSchoolId, schoolId)
                .eq(BasicCourse::getCode, courseCode)
                .eq(BasicCourse::getEnable, true);
        BasicCourse basicCourse = basicCourseService.getOne(basicCourseQueryWrapper);
        if (Objects.isNull(basicCourse)) {
            throw ExceptionResultEnum.ERROR.exception("找不到此课程信息");
        }

//        Map<String, List<String>> flowSchoolCodeMap = SystemConstant.getFlowSchoolCodeMap();
//        BasicSchool basicSchool = (BasicSchool) ServletUtil.getRequestSchool();
//        if (flowSchoolCodeMap.get(SystemConstant.JXZYY_FLOW_KEY).contains(basicSchool.getCode())) {
//            List<ApproveUserResult> approveUserResultList = sysUserService.findByJxzyyDirectorApprove(null, FlowApproveNameEnum.TEACHER);
//            if (Objects.nonNull(approveUserResultList) && approveUserResultList.size() > 0) {//说明是实施人员提交
//                List<BlurryUserDto> blurryUserDtoList = new ArrayList<>();
//                for (ApproveUserResult sysUser : approveUserResultList) {
//                    blurryUserDtoList.add(new BlurryUserDto(sysUser.getId(), sysUser.getLoginName(), sysUser.getRealName()));
//                }
//                return blurryUserDtoList;
//            } else {
//                return listUserCommon(basicCourse, schoolId);
//            }
//        } else {
        return listUserCommon(basicCourse, schoolId);
//        }
    }

    /**
     * 查找命题老师公用
     *
     * @param basicCourse
     * @param schoolId
     * @return
     */
    private AssignTeacherDto listUserCommon(BasicCourse basicCourse, Long schoolId) {
//        int count = this.countByTeachingRoomId(basicCourse.getTeachingRoomId());
//        List<SysOrg> sysOrgList = null;
//        if (count == 0) {
//            sysOrgList = sysOrgService.findByConnectByParentId(basicCourse.getTeachingRoomId(), true, true);
//        } else {
//        List<SysOrg> sysOrgList = sysOrgService.findByConnectByRootOrgId(basicCourse.getTeachingRoomId());
//        }
//        Set<Long> orgIds = sysOrgList.stream().map(s -> s.getId()).collect(Collectors.toSet());
//        List<ApproveUserResult> sysUserList = sysUserService.filterFlowPrivilege(schoolId, orgIds, false, null, null);
        List<SysUserResult> finalSysUserResultList = sysUserService.findSysUserResultListNew(schoolId, null);
        if (!CollectionUtils.isEmpty(finalSysUserResultList)) {
            finalSysUserResultList.forEach(e -> {
                if (Objects.nonNull(e.getRoleIds())) {
                    String[] roldIds = StringUtils.split(e.getRoleIds(), ";");
                    List<RoleResult> roleResultList = new ArrayList<>(roldIds.length);
                    for (int y = 0; y < roldIds.length; y++) {
                        String[] strs = StringUtils.split(roldIds[y], ",");
                        roleResultList.add(new RoleResult(Long.parseLong(strs[0]), strs[1]));
                    }
                    e.setRoleResultList(roleResultList);
                }
            });
        }
        List<OrgDto> orgList = sysOrgService.listOrgAll(schoolId);
        Map<Long, OrgDto> map = orgList.stream()
                .peek(e -> {
                    // 加入机构下所有人员查询
                    e.setSysUserList(finalSysUserResultList.stream().filter(f -> Objects.nonNull(f.getOrgId()) && f.getOrgId().equals(e.getId())).collect(Collectors.toList()));
                })
                .collect(Collectors.toMap(OrgDto::getId, Function.identity(), (dto1, dto2) -> dto1));

        Iterator<Long> iterator = map.keySet().iterator();
        Set<Long> deleteKeys = new HashSet<>();
        while (iterator.hasNext()) {
            Long parentId = iterator.next();
            if (map.get(parentId).getParentId() != null) {
                if (Objects.nonNull(map.get(map.get(parentId).getParentId()))) {
                    map.get(map.get(parentId).getParentId()).getChildren().add(map.get(parentId));
                    deleteKeys.add(parentId);
                }
            }
        }
        for (Long key : deleteKeys) {
            map.remove(key);
        }
        List<OrgDto> list = new ArrayList<>(map.values());
        List<SysUserResult> resultList = sysUserService.findCourseSysUserResultList(schoolId, basicCourse.getCode());
//        List<BlurryUserDto> blurryUserDtoList = new ArrayList<>();
//        for (ApproveUserResult sysUser : sysUserList) {
//            blurryUserDtoList.add(new BlurryUserDto(sysUser.getId(), sysUser.getLoginName(), sysUser.getRealName()));
//        }
        return new AssignTeacherDto(list, resultList, finalSysUserResultList);
    }

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

    @Transactional
    @Override
    public boolean saveCustomer(UserSaveParams userSaveParams) {
        Long upUserId = saveUserCommon(userSaveParams, null);
        return SystemConstant.longNotNull(upUserId);
    }

    @Override
    public IPage<UserDto> listCustomer(String realName, Boolean enable, Integer pageNumber, Integer pageSize) {
        Page<UserDto> page = new Page<>(pageNumber, pageSize);
        IPage<UserDto> userDtoIPage = this.baseMapper.listCustomerPage(page, SystemConstant.translateSpecificSign(realName), enable);
        if (userDtoIPage.getRecords().size() > 0) {
            userDtoIPage.getRecords().forEach(m -> {
                //角色
                List<SysRole> roles = sysRoleService.listRolesByUserId(Long.valueOf(m.getId()));
                m.setRoles(roles);

                //课程
                List<BasicCourse> courses = basicCourseService.listCoursesByUserId(Long.valueOf(m.getId()));
                m.setCourses(courses);
            });
        }
        return userDtoIPage;
    }

    @Override
    public SysUser findByForeignKey(Long schoolId, String teacherCode) {
        List<SysUser> tbSchoolTeacherList = this.list(new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getSchoolId, schoolId)
                .eq(SysUser::getLoginName, teacherCode));
        SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.TEACHER));
//        tbSchoolTeacherList = tbSchoolTeacherList.stream().filter(e -> Arrays.asList(e.getRoleIds()).contains(sysRole.getId())).collect(Collectors.toList());
        if (tbSchoolTeacherList.size() != 1) {
            throw ExceptionResultEnum.ERROR.exception("教师基础数据信息异常");
        }
        return tbSchoolTeacherList.get(0);
    }

    /**
     * 保存用户公用
     *
     * @param userSaveParams userSaveParams
     * @return 新增或更新的用户id
     */
    @Transactional
    public Long saveUserCommon(UserSaveParams userSaveParams, Long requestUserId) {
        SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
        boolean isSuccess = true;
        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 loginName = userSaveParams.getLoginName();
            String mobileNumber = userSaveParams.getMobileNumber();
            // 工号检验
            SysUser checkCode = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getEnable, true).eq(SysUser::getLoginName, loginName));
            if (Objects.nonNull(checkCode)) {
                if (!checkCode.getId().equals(userSaveParams.getId())) {
                    throw ExceptionResultEnum.ERROR.exception("用户名/工号[" + loginName + "]在系统中已使用");
                }
            }
            // 手机号检验
            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())) {//新增用户
                BasicSchool basicSchool = commonCacheService.schoolCache(schoolId);
                sysUser.insertInfo(requestUserId);
                String password = StringUtils.isNoneBlank(basicSchool.getInitPassword()) ? basicSchool.getInitPassword() : Base64Util.encode(SystemConstant.INIT_PASSWORD.getBytes());
                sysUser.setPassword(password);
                sysUser.setEnable(true);
                sysUser.setCode(sysUser.getLoginName());
                sysUserService.save(sysUser);
                resultUserId = sysUser.getId();
                commonService.addUserRolePrivilege(sysUser, userSaveParams.getRoleIds());
            } else {//修改用户
                resultUserId = sysUser.getId();
                List<SysUserRole> sysUserRoleList = commonCacheService.userRolePrivilegeCache(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::getCode, sysUser.getLoginName())
                        .set(SysUser::getAllowManualCard, sysUser.getAllowManualCard())
                        .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);
                    }

                    commonCacheService.removeUserRolePrivilegeCache(sysUser.getId());
                    commonService.addUserRolePrivilege(sysUser, userSaveParams.getRoleIds());
                    commonService.removeUserInfo(sysUser.getId(), true);
                } else if (!dbUser.getOrgId().equals(sysUser.getOrgId())) {
                    commonService.removeUserInfo(sysUser.getId(), true);
                }
                //如果修改了机构或手机号，需更新用户缓存
                if (Objects.nonNull(dbUser.getOrgId())) {
                    if (dbUser.getOrgId().longValue() != sysUser.getOrgId().longValue()
                            || !Objects.equals(dbUser.getMobileNumber(), sysUser.getMobileNumber())) {
                        commonCacheService.updateUserCache(sysUser.getId());
                        commonCacheService.updateUserAuthCache(sysUser.getId());
                    }
                }

            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            isSuccess = false;
            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 DataIntegrityViolationException || e instanceof BadSqlGrammarException) {
                String content = JdbcErrorUtil.parseErrorMsg(e.getMessage().toString());
                throw ExceptionResultEnum.SQL_ERROR.exception(content);
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return resultUserId;
    }

    /**
     * 临时保存用户不鉴权
     *
     * @param userSaveParams 用户参数
     * @return 结果
     */
    @Override
    public boolean saveUserNoAuth(UserSaveParams userSaveParams) {
        SysUserService sysUserService = SpringContextHolder.getBean(SysUserService.class);
        boolean isSuccess = true;
        try {
            Long schoolId = userSaveParams.getSchoolId();
            if (schoolId == null) {
                schoolId = Objects.nonNull(ServletUtil.getRequestHeaderSchoolIdByNotVaild()) ? Long.valueOf(ServletUtil.getRequestHeaderSchoolIdByNotVaild().toString()) : null;
            }
            List<SysUser> requestUserList = this.list(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId).like(SysUser::getLoginName, "admin"));
            if (requestUserList.size() == 0 && !Objects.equals(userSaveParams.getRealName(), "学校管理员")) {
                this.buildAdministratorForSchool(schoolId);
            }
            Long requestUserId = 1L;
            if (requestUserList.size() > 0) {
                requestUserId = requestUserList.get(0).getId();
            }
            Gson gson = new Gson();
            userSaveParams.setSchoolId(schoolId);
            SysUser sysUser = gson.fromJson(gson.toJson(userSaveParams), SysUser.class);
            if (Objects.isNull(sysUser.getId())) {//新增用户
                // 登录名是否唯一
                QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                if (Objects.isNull(schoolId)) {
                    queryWrapper.lambda().isNull(SysUser::getSchoolId);
                } else {
                    queryWrapper.lambda().eq(SysUser::getSchoolId, schoolId);
                }
                queryWrapper.lambda().eq(SysUser::getLoginName, sysUser.getLoginName());
                SysUser user = sysUserService.getOne(queryWrapper);
                if (user != null) {
                    throw ExceptionResultEnum.ERROR.exception("用户名已存在");
                }

                sysUser.insertInfo(requestUserId);
                sysUserService.save(sysUser);
                for (Long roleId : userSaveParams.getRoleIds()) {
                    commonService.addUserRolePrivilege(sysUser, roleId);
                }
            } else {//修改用户
                List<SysUserRole> sysUserRoleList = commonCacheService.userRolePrivilegeCache(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(userRolesList::contains).count();
                SysUser dbUser = sysUserService.getById(sysUser.getId());
                sysUser.updateInfo(requestUserId);
                sysUserService.updateById(sysUser);
                List<SysRole> list = sysUserRoleService.listRoleByUserId(sysUser.getId());
                boolean containsQuestionTeacher = list.stream().anyMatch(m -> RoleTypeEnum.SCHOOL_ADMIN.equals(m.getType()));
                if (containsQuestionTeacher || count == 0 || dbUserRolesList.size() != userRolesList.size()) {
                    QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
                    sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
                    sysUserRoleService.remove(sysUserRoleQueryWrapper);

                    commonCacheService.removeUserRolePrivilegeCache(sysUser.getId());
                    for (Long roleId : userSaveParams.getRoleIds()) {
                        commonService.addUserRolePrivilege(sysUser, roleId);
                    }
                }
                //如果修改了角色，需要重新登录
                if (count == 0 || dbUserRolesList.size() != userRolesList.size()) {
                    commonService.removeUserInfo(sysUser.getId(), true);
                }
                //如果修改了机构或手机号，需更新用户缓存
                if (Objects.nonNull(dbUser.getOrgId())) {
                    if (containsQuestionTeacher || dbUser.getOrgId().longValue() != sysUser.getOrgId().longValue()
                            || !Objects.equals(dbUser.getMobileNumber(), sysUser.getMobileNumber())) {
                        commonCacheService.updateUserCache(sysUser.getId());
                        commonCacheService.updateUserAuthCache(sysUser.getId());
                    }
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            isSuccess = false;
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return isSuccess;
    }

    @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);
            //  处理机构
            if (CollectionUtils.isNotEmpty(sysUserImportDtoList) && 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) {
                    try {
                        String name = sysUserImportDto.getName();
                        String loginName = sysUserImportDto.getLoginName();
                        String phoneNumber = sysUserImportDto.getPhoneNumber();
                        String orgName = sysUserImportDto.getOrgName();
                        if (!orgInfoMap.containsKey(orgName)) {
                            // 系统异常
                            throw ExceptionResultEnum.ERROR.exception("系统中未查询到机构名称[" + 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;
                        if (Objects.nonNull(oldUser)) {
                            oldUserId = oldUser.getId();
                        }
                        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.setSchoolId(schoolId);

                        Long upUserId = this.saveUserCommon(userSaveParams, requestUser.getId());
                        userIdList.add(upUserId);
                    } catch (Exception e) {
                        String error = e.getMessage();
                        List<SysUserErrorExportDto> errorDataList = JSON.parseArray(JSON.toJSONString(map.get(SystemConstant.ERROR_DATA_LIST)), SysUserErrorExportDto.class);
                        if (Objects.isNull(errorDataList)) {
                            errorDataList = new ArrayList<>();
                        }
                        SysUserErrorExportDto sysUserErrorExportDto = new SysUserErrorExportDto();
                        BeanUtils.copyProperties(sysUserImportDto, sysUserErrorExportDto);
                        sysUserErrorExportDto.setErrorMsg(error);
                        errorDataList.add(sysUserErrorExportDto);
                        map.put(SystemConstant.ERROR_DATA_LIST, errorDataList);

                        int dataCount = (int) map.get(SystemConstant.DATA_COUNT);
                        map.put(SystemConstant.SUCCESS_DATA_COUNT, dataCount - errorDataList.size());
                        map.put(SystemConstant.ERROR_DATA_COUNT, errorDataList.size());
                    }
                }
            }
        }
        map.put("userIdList", userIdList);
        return map;
    }

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

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

    @Override
    public void checkSmsCode(Long userId, String mobileNumber, String code) {
        SysConfig value = sysConfigService.getByKey("sys.code.enable");
        if (Objects.nonNull(value) && value.getConfigValue().equals("true")) {
            if (Objects.isNull(code)) {
                throw ExceptionResultEnum.ERROR.exception("验证码不能为空");
            }
            SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SMS_NORMAL_CODE);
            Optional.ofNullable(sysConfig).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("未配置万能短信验证码"));
            if (!sysConfig.getConfigValue().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) {
        SysConfig value = sysConfigService.getByKey("sys.code.enable");
        if (Objects.nonNull(value) && value.getConfigValue().equals("true")) {
            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 boolean isAdminDataAuth(Long userId) {
        boolean result = false;
        List<SysOrg> sysOrgList = sysOrgService.list();
        SysUser user = this.getById(userId);
        if (Objects.isNull(user)) {
            throw ExceptionResultEnum.ERROR.exception("用户不存在");
        }
        Long schoolId = user.getSchoolId();
        if (SystemConstant.longNotNull(schoolId)) {
            List<Long> orgIdList = this.findOrgIdListByUserId(userId);
            if (sysOrgList.stream().anyMatch(e -> orgIdList.contains(e.getId()) && OrgTypeEnum.SCHOOL.equals(e.getType()))) {
                result = true;
            }
        } else {
            result = true;
        }
        return result;
    }

    /**
     * 根据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());
    }

    @Override
    public List<SysUser> findBySchoolIdAndCode(Long schoolId, String code) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getCode, code);
        return sysUserMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void buildAdministratorForSchool(Long schoolId) {
        // 为没有学校管理员的学校自动创建一个学校管理员
        QueryWrapper<BasicSchool> basicSchoolQueryWrapper = new QueryWrapper<>();
        if (SystemConstant.longNotNull(schoolId)) {
            basicSchoolQueryWrapper.lambda().eq(BasicSchool::getId, schoolId);
        }
        List<BasicSchool> basicSchoolList = basicSchoolService.list(basicSchoolQueryWrapper);
        SysRole role = sysRoleService.list(new QueryWrapper<SysRole>().lambda().eq(SysRole::getType, RoleTypeEnum.SCHOOL_ADMIN)).get(0);
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(role.getId());
        for (BasicSchool basicSchool : basicSchoolList) {
            Long cellSchoolId = basicSchool.getId();
            SysOrg schoolOrg = sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda()
                    .eq(SysOrg::getSchoolId, cellSchoolId)
                    .eq(SysOrg::getType, OrgTypeEnum.SCHOOL));
            if (Objects.isNull(schoolOrg)) {
                throw ExceptionResultEnum.ERROR.exception("未找到学校对应的顶级机构");
            }
            // 用户id集合
            List<Long> adminUserIdList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda()
                            .in(SysUserRole::getRoleId, roleIds))
                    .stream()
                    .map(SysUserRole::getUserId)
                    .distinct().collect(Collectors.toList());
            if (adminUserIdList.size() > 0) {
                List<SysUser> adminUserList = sysUserService.list(new QueryWrapper<SysUser>().lambda()
                        .eq(SysUser::getSchoolId, cellSchoolId)
                        .in(SysUser::getId, adminUserIdList));
                if (adminUserList.size() > 0) {
                    // 存在管理员
                    continue;
                }
            }
            UserSaveParams userSaveParams = new UserSaveParams();
            userSaveParams.setSchoolId(cellSchoolId);
            userSaveParams.setLoginName("admin");
            userSaveParams.setRealName("学校管理员");
            userSaveParams.setPassword(SystemConstant.DEFAULT_PASSWORD);

            userSaveParams.setOrgId(schoolOrg.getId());
            userSaveParams.setEnable(true);
            userSaveParams.setRoleIds(roleIds.toArray(new Long[0]));
            sysUserService.saveUserNoAuth(userSaveParams);
        }
    }

    @Override
    public boolean removeBasicCourseBatch(List<Long> idList) {
        this.removeByIds(idList);
        idList.forEach(m -> {
            try {
                commonService.removeUserInfo(m, true);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        });
        return true;
    }

    @Override
    public boolean remove(Long id) throws NoSuchAlgorithmException {
        this.removeById(id);
        //如果用户被删除，需要踢下线重新登录
//        commonService.removeUserInfo(id, true);
        commonCacheService.removeUserCache(id);
        commonCacheService.removeUserAuthCache(id);
        commonCacheService.removeUserMenuCache(id);
        commonCacheService.removeUserRolePrivilegeCache(id);
        return true;
    }

    @Override
    public void exportData(HttpServletResponse response, String userInfo, Long orgId, String roleId, Boolean enable) throws Exception {
        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
        sysOrgService.list();

        List<UserExportDto> userExportDtos = this.baseMapper.listExportData(schoolId, SystemConstant.translateSpecificSign(userInfo), orgId, roleId, enable);
        if (userExportDtos.isEmpty()) {
            throw ExceptionResultEnum.ERROR.exception("没有可导出数据");
        }
        userExportDtos.forEach(m -> {
            List<SysOrg> byConnectByParentIdList = sysOrgService.findByConnectByParentId(m.getOrgId(), true, false);
            if (CollectionUtils.isNotEmpty(byConnectByParentIdList)) {
                m.setOrgName(byConnectByParentIdList.stream().map(SysOrg::getName).collect(Collectors.joining("/")));
            }
            //角色
            List<SysRole> roles = sysRoleService.listRolesByUserId(Long.valueOf(m.getId()));
            if (roles.isEmpty()) {
                m.setRoleName("");
            } else {
                List<String> roleList = roles.stream().map(SysRole::getName).collect(Collectors.toList());
                m.setRoleName(String.join(",", roleList));
            }
            m.setEnableName(m.getEnable() ? "启用" : "禁用");
        });
        // 生成excel文件
        ExcelUtil.excelExport("用户数据", UserExportDto.class, userExportDtos, response);
    }

    /**
     * 根据角色权限类型查询用户
     *
     * @param schoolId
     * @param specialPrivilegeEnum
     * @return
     */
    @Override
    public List<SysUserResult> findSysUserResultListNew(Long schoolId, RoleTypeEnum specialPrivilegeEnum) {
        Set<Long> roleIds = null;
        if (Objects.nonNull(specialPrivilegeEnum)) {
            roleIds = new HashSet<>();
            SysRole sysRole = sysRoleService.getDefaultRoleByType(specialPrivilegeEnum);
            if (sysRole != null && sysRole.getId() != null) {
                roleIds.add(sysRole.getId());
            }
        }
        return sysUserMapper.findSysUserResultListNew(schoolId, roleIds);
    }

    /**
     * 查找科目下命题老师
     *
     * @param schoolId
     * @param courseCode
     * @return
     */
    @Override
    public List<SysUserResult> findCourseSysUserResultList(Long schoolId, String courseCode) {
        return sysUserMapper.findCourseSysUserResultList(schoolId, courseCode);
    }

    /**
     * 查找内置老师
     *
     * @param teachIdSet
     * @return
     */
    @Override
    public List<SysUserResult> findCourseSysUserResultByTeachIdSet(Set<Long> teachIdSet) {
        return sysUserMapper.findCourseSysUserResultByTeachIdSet(teachIdSet);
    }

    @Override
    public SysUser getByUserId(Long userId) {
        return this.baseMapper.getByUserId(userId);
    }

    /**
     * 批量处理用户信息帮助类
     *
     * @param userSaveParamsList 用户信息集合
     * @param master             创建人信息
     * @return 处理后的结果
     */
    @Deprecated
    private UserBatchDisposeResult disposeUserInfoHelp(List<UserSaveParams> userSaveParamsList, SysUser master) throws NoSuchAlgorithmException {
        Long schoolId = master.getSchoolId();
        List<SysUser> userList = new ArrayList<>();
        List<SysUserRole> sysUserRoleList = new ArrayList<>();
        // 用户角色更新 - 对用户角色权限的各种清除操作
        Set<Long> willRemoveUserPri = new HashSet<>();
        // 用户基础信息更新 - 对用户权限缓存的更新
        Set<Long> willUpdateUserPri = new HashSet<>();
        for (UserSaveParams userSaveParams : userSaveParamsList) {
            String code = userSaveParams.getCode();
            String mobileNumber = userSaveParams.getMobileNumber();
            // 工号检验
            SysUser checkCode = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getSchoolId, schoolId).eq(SysUser::getEnable, true).eq(SysUser::getCode, code));
            if (Objects.nonNull(checkCode)) {
                if (!checkCode.getId().equals(userSaveParams.getId())) {
                    throw ExceptionResultEnum.ERROR.exception("用户工号[" + code + "]重复");
                }
            }
            // 手机号检验
            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 userCell = gson.fromJson(gson.toJson(userSaveParams), SysUser.class);
            if (Objects.isNull(userCell.getId())) {//新增用户
                userCell.insertInfo(master.getId());
                userCell.setLoginName(userCell.getCode());
                userList.add(userCell);
                List<SysUserRole> sysUserRoleCell = commonService.disposeUserPrivilege(userCell, userSaveParams.getRoleIds());
                sysUserRoleList.addAll(sysUserRoleCell);
            } else {//修改用户
                List<SysUserRole> oldRoleList = commonCacheService.userRolePrivilegeCache(userCell.getId());
                List<Long> newRoleList = Arrays.asList(userSaveParams.getRoleIds());
                Set<Long> dbUserRolesList = oldRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toSet());
                int count = (int) dbUserRolesList.stream().filter(newRoleList::contains).count();
                SysUser dbUser = this.getById(userCell.getId());
                userCell.updateInfo(master.getId());
                userList.add(userCell);
                //如果修改了角色，需要重新登录
                if (count == 0 || dbUserRolesList.size() != newRoleList.size()) {
                    List<SysUserRole> sysUserRoleCell = commonService.disposeUserPrivilege(userCell, userSaveParams.getRoleIds());
                    sysUserRoleList.addAll(sysUserRoleCell);
                    willRemoveUserPri.add(userCell.getId());
                } else if (!dbUser.getOrgId().equals(userCell.getOrgId())) {
                    commonService.removeUserInfo(userCell.getId(), true);
                }
                //如果修改了机构或手机号，需更新用户缓存
                if (Objects.nonNull(dbUser.getOrgId())) {
                    if (dbUser.getOrgId().longValue() != userCell.getOrgId().longValue()
                            || !Objects.equals(dbUser.getMobileNumber(), userCell.getMobileNumber())) {
                        willUpdateUserPri.add(userCell.getId());
                    }
                }
            }
        }
        UserBatchDisposeResult userBatchDisposeResult = new UserBatchDisposeResult();
        userBatchDisposeResult.setUserList(userList);
        userBatchDisposeResult.setUserRoleList(sysUserRoleList);
        userBatchDisposeResult.setRemoveIdSet(willRemoveUserPri);
        userBatchDisposeResult.setUpdateIdSet(willUpdateUserPri);

        return userBatchDisposeResult;
    }

    /**
     * 解析机构名称
     *
     * @param schoolId 学校id
     * @param orgName  结构名称
     * @return 机构id
     */
    private Long analyzeOrgName(Long schoolId, String orgName) {
        SysOrg sysOrg = sysOrgService.getOne(new QueryWrapper<SysOrg>().lambda().eq(SysOrg::getEnable, true).eq(SysOrg::getSchoolId, schoolId).eq(SysOrg::getName, orgName));
        if (Objects.isNull(sysOrg)) {
            throw ExceptionResultEnum.ERROR.exception("系统中不存在excel导入的机构[" + orgName + "]");
        }
        return sysOrg.getId();
    }

    /**
     * 根据角色名称获取角色id集合
     *
     * @param schoolId  学校id
     * @param roleNames 角色名称组
     * @return 角色集合
     */
    private LinkedHashSet<Long> analyzeRoleName(Long schoolId, String roleNames) {
        LinkedHashSet<Long> roleIdList = new LinkedHashSet<>();
        String[] arr = roleNames.split(SystemConstant.COMMA);
        for (String cell : arr) {
            String roleName = cell.trim();
            List<SysRole> sysRoles = sysRoleService.getByRoleName(schoolId, roleName);
            if (CollectionUtils.isEmpty(sysRoles)) {
                throw ExceptionResultEnum.ERROR.exception("角色[" + roleName + "]不存在");
            } else if (sysRoles.size() > 1) {
                throw ExceptionResultEnum.ERROR.exception("角色[" + roleName + "]查询到多条数据，请联系管理员处理");
            } else if (!sysRoles.get(0).getEnable()) {
                throw ExceptionResultEnum.ERROR.exception("角色[" + roleName + "]已禁用");
            }
            roleIdList.add(sysRoles.get(0).getId());
        }
        return roleIdList;
    }

    @Override
    public void updateUiSetting(Long userId, String uiSetting) {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SysUser::getUiSetting, uiSetting)
                .eq(SysUser::getId, userId);
        this.update(updateWrapper);
    }

    @Override
    public SysUser getByLoginName(Long schoolId, String teacherName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getSchoolId, schoolId)
                .eq(SysUser::getLoginName, teacherName);
        return this.getOne(queryWrapper);
    }
}
