package com.zd.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.zd.common.core.constant.UserConstants;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.DictUtils;
import com.zd.system.api.domain.*;
import com.zd.system.domain.*;
import com.zd.system.mapper.*;
import com.zd.system.service.ISysConfigService;
import com.zd.system.service.ISysPermitMenuService;
import com.zd.system.service.ISysStudentService;
import com.zd.system.service.ISysTeacherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户 业务层处理
 *
 * @author zd
 */
@Service
public class SysStudentServiceImpl implements ISysStudentService {
    private static final Logger log = LoggerFactory.getLogger(SysStudentServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysMajorMapper sysMajorMapper;

    @Autowired
    private ISysPermitMenuService sysPermitMenuService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", permi = PerPrefix.SYSTEM_USER_STUDENT)
    public List<SysUser> selectUserList(SysUser user) {
        List<SysUser> sysUserList = userMapper.selectUserList(user);
        //查询数据字典列表
        List<SysDictData> proDictDatas = DictUtils.getDictCache("professional");
        List<SysDictData> edDictDatas = DictUtils.getDictCache("education");
        List<SysDictData> stDictDatas = DictUtils.getDictCache("student_status");

        List<SysMajor> sysMajorList = sysMajorMapper.selectSysMajorList(new SysMajor());
        Optional.ofNullable(sysUserList).orElseGet(Collections::emptyList)
                .stream().forEach(a->{
            Optional.ofNullable(proDictDatas).orElseGet(Collections::emptyList)
                    .stream().forEach(b->{
                    if(b.getDictValue().equals(a.getCategory())){
                        a.setCategory(b.getDictLabel());
                    }
            });
            Optional.ofNullable(edDictDatas).orElseGet(Collections::emptyList)
                    .stream().forEach(b->{
                if(b.getDictValue().equals(a.getEducation())){
                    a.setEducation(b.getDictLabel());
                }
            });
            Optional.ofNullable(stDictDatas).orElseGet(Collections::emptyList)
                    .stream().forEach(b->{
                if(b.getDictValue().equals(a.getWorkStatus())){
                    a.setWorkStatus(b.getDictLabel());
                }
            });

            Optional.ofNullable(sysMajorList).orElseGet(Collections::emptyList)
                    .stream().forEach(b->{
                if(b.getId()==a.getMajorId()){
                    a.setMajor(b.getMajorName());
                }
            });
        });
        return sysUserList;
    }

    /**
     * 根据部门ids查询用户列表
     *
     * @param deptIds
     * @return
     */
    @Override
    public List<SysUser> selectUserListByDeptIds(Long... deptIds) {
        return userMapper.selectUserListByDeptIds(deptIds);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", permi = PerPrefix.SYSTEM_USER_STUDENT)
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", permi = PerPrefix.SYSTEM_USER_STUDENT)
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }


    /**
     * 通过用户卡号查询
     *
     * @param cardNum 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByCardNum(String cardNum) {
        return userMapper.selectUserByCardNum(cardNum);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId())) {

            if (SecurityUtils.getUserId() != 1 && user.getUserId() == 2) {
                throw new ServiceException("不允许操作管理员用户");
            }

            if (user.isAdmin()) {
                throw new ServiceException("不允许操作超级管理员用户");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        //将10进制卡号转换至16进制
        if(StringUtils.isNotEmpty(user.getCardNum())){
            if(StringUtils.isNumeric(user.getCardNum())){
                Long carNum10 = Long.parseLong(user.getCardNum());
                String carNum16 = carNum10.toHexString(carNum10).toUpperCase();
                user.setCardNum(carNum16);
            }else{
                throw new ServiceException("卡号只能是数字，不能包含字母！");
            }

        }else{
            user.setCardNum(null);
        }

        // 新增用户信息
        int rows = userMapper.insertUser(user);
        //处理Object 转换实体类
        List <Object> permitMenus = user.getPermitMenus();
        List<SysPermitMenu> newPermitMenus = new ArrayList<>();
        for(Object obj:permitMenus){
            SysPermitMenu sysPermitMenu = JSONArray.parseObject(JSONArray.toJSONString(obj),SysPermitMenu.class);
            newPermitMenus.add(sysPermitMenu);
        }
        if(newPermitMenus.size()>0){
            // 插入最新用户绑定的权限数据
            sysPermitMenuService.insertSysPermitMenuList(null,user.getUserId(),newPermitMenus);
        }
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        try {
            //将10进制卡号转换至16进制
            if(StringUtils.isNotEmpty(user.getCardNum())){
                if(StringUtils.isNumeric(user.getCardNum())){
                    Long carNum10 = Long.parseLong(user.getCardNum());
                    String carNum16 = carNum10.toHexString(carNum10).toUpperCase();
                    user.setCardNum(carNum16);
                }else{
                    throw new ServiceException("卡号只能是数字，不能包含字母！");
                }
            }else{
                user.setCardNum(null);
            }
            return userMapper.updateUser(user);
        }catch (DuplicateKeyException e){
            throw new ServiceException("卡号已经存在，保存失败！");
        }

    }

    /**
     * 修改用户信息，不进行权限配置
     * @param user
     * @return
     */
    @Override
    public int update(SysUser user) {
        //将10进制卡号转换至16进制
        if(StringUtils.isNotEmpty(user.getCardNum())){
            if(StringUtils.isNumeric(user.getCardNum())){
                Long carNum10 = Long.parseLong(user.getCardNum());
                String carNum16 = carNum10.toHexString(carNum10).toUpperCase();
                user.setCardNum(carNum16);
            }else{
                throw new ServiceException("卡号只能是数字，不能包含字母！");
            }
        }else{
            user.setCardNum(null);
        }
        //处理Object 转换实体类
        List <Object> permitMenus = user.getPermitMenus();
        List<SysPermitMenu> newPermitMenus = new ArrayList<>();
        for(Object obj:permitMenus){
            SysPermitMenu sysPermitMenu = JSONArray.parseObject(JSONArray.toJSONString(obj),SysPermitMenu.class);
            newPermitMenus.add(sysPermitMenu);
        }
        if(newPermitMenus.size()>0){
            // 插入最新用户绑定的权限数据
            sysPermitMenuService.insertSysPermitMenuList(null,user.getUserId(),newPermitMenus);
        }
        return userMapper.updateStudentUser(user);
    }


    /**
     * 修改用户信息，不进行权限配置
     * @param userList
     * @return
     */
    public int editUserByDept(List<SysUser> userList) {
        Optional.ofNullable(userList).orElseGet(Collections::emptyList).stream()
                .forEach(a->{
                    userMapper.updateUser(a);
                });
        return 1;
    }



    /**
     * 修改用户手机号
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int changePhone(SysUser user) {
        try {
            return userMapper.updateUser(user);
        }catch (DuplicateKeyException e){
            throw new ServiceException("保存失败，请联系管理员！");
        }

    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public List<SysUserTeaCherByExcel> importUserByTeaCher(List<SysUserTeaCherByExcel> userList, Boolean isUpdateSupport, String operName, SysUserTeaCherByExcel sysUserTeaCherByExcel) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        List<SysUserTeaCherByExcel> failSysUserList = new ArrayList<>();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUserTeaCherByExcel user : userList) {
            //流水线验证
            flowLineCheck(user,failSysUserList,password, sysUserTeaCherByExcel);
        }
        return failSysUserList;
    }

    private void flowLineCheck(SysUserTeaCherByExcel user, List<SysUserTeaCherByExcel> failSysUserList, String password, SysUserTeaCherByExcel sysUserTeaCherByExcel){
        // 校验是否装入错误数据
        boolean checkBox = true;

        //验证必填字段是否为空
        if(StringUtils.isEmpty(user.getNickName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("姓名不能为空,");
        }

        if(StringUtils.isEmpty(user.getUserName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("工号不能为空,");
        }

        if(StringUtils.isEmpty(user.getDeptName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("所在部门不能为空,");
        }

        if(StringUtils.isEmpty(user.getPistionName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("身份不能为空,");
        }

        if(StringUtils.isNotEmpty(user.getCardNum()) && !StringUtils.isNumeric(user.getCardNum())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("卡号只能为数字,");
        }


        // 验证是否存在这个用户
        SysUser checkUser = userMapper.selectUserByUserName(user.getUserName());
        if (StringUtils.isNotNull(user.getUserName()) && StringUtils.isNotNull(checkUser)) {
            if(!sysUserTeaCherByExcel.getUpDate()){
                if(checkBox){
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("工号重复,");
            }
        }
        // 验证部门是否存在
        SysDept checkDept = deptMapper.getDeptNameUnique(user.getDeptName());
        if (StringUtils.isNotEmpty(user.getDeptName()) && StringUtils.isNull(checkDept)) {
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("部门不存在,");
        }
        //联系电话重复
        SysUser info = null;
        if(StringUtils.isNotNull(checkUser) && sysUserTeaCherByExcel.getUpDate()){
            if(StringUtils.isNotEmpty(user.getPhonenumber())){
                SysUser userInfo = new SysUser();
                userInfo.setUserName(checkUser.getUserName());
                userInfo.setPhonenumber(user.getPhonenumber());
                info = userMapper.checkPhoneUniqueNotOwn(userInfo);
            }
        }else{
            if(StringUtils.isNull(checkUser) && StringUtils.isNotEmpty(user.getPhonenumber())){
                info = userMapper.checkPhoneUnique(user.getPhonenumber());
            }
        }
        if(StringUtils.isNotNull(info)){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("联系电话重复,");
        }

        //身份是否存在
        SysPost sysPost = postMapper.checkPostNameUnique(user.getPistionName());
        if (StringUtils.isNotEmpty(user.getPistionName()) && StringUtils.isNull(sysPost)) {
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("身份不存在,");
        }
        //日期格式转换
        if(StringUtils.isNotNull(user.getDateBirth())){
            Date time = user.getDateBirth();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try{
                int year = time.getYear();
                int month = time.getMonth();
                int date = time.getDate();
                if(year > new Date().getYear()-15) {
                    if (checkBox) {
                        user.getFailRemark().append("失败：");
                        failSysUserList.add(user);
                        checkBox = false;
                    }
                    user.getFailRemark().append("日期格式错误,");
                }
            }catch (Exception e){
                if (checkBox) {
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("日期格式错误,");
                log.error("日期格式错误");
            }
        }

        //插入正确数据
        if(StringUtils.isEmpty(user.getFailRemark())){
            SysUser newSysUser = new SysUser();
            newSysUser.setNickName(user.getNickName());
            newSysUser.setUserName(user.getUserName());
            newSysUser.setDeptId(checkDept.getDeptId());
            newSysUser.setPosition(sysPost.getPostId()+"");
            newSysUser.setPhonenumber(user.getPhonenumber());
            newSysUser.setEmail(user.getEmail());
            newSysUser.setUserType("11");
            newSysUser.setSex(user.getSex());
            newSysUser.setDateBirth(user.getDateBirth());
            newSysUser.setCardNum(user.getCardNum());
            if(!sysUserTeaCherByExcel.getSysUserEnable()){
                newSysUser.setStatus(1+"");
            }
            newSysUser.setPassword(SecurityUtils.encryptPassword(password));
            newSysUser.setCreateBy(tokenService.getLoginUser().getNickName());
            if(StringUtils.isNotNull(checkUser)){
                newSysUser.setUserId(checkUser.getUserId());
                this.updateUser(newSysUser);
            }else{
                this.insertUser(newSysUser);
            }
        }
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public List<SysUserStudentByExcel> importUserByStudent(List<SysUserStudentByExcel> userList, Boolean isUpdateSupport, String operName, SysUserStudentByExcel sysUserStudentByExcel) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        List<SysUserStudentByExcel> failSysUserList = new ArrayList<>();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUserStudentByExcel user : userList) {
            //流水线验证
            flowLineCheckByStudent(user,failSysUserList,password, sysUserStudentByExcel);
        }
        return failSysUserList;
    }


    private void flowLineCheckByStudent(SysUserStudentByExcel user, List<SysUserStudentByExcel> failSysUserList, String password, SysUserStudentByExcel sysUserStudentByExcel){
        // 校验是否装入错误数据
        Boolean checkBox = true;

        //验证必填字段是否为空
        if(StringUtils.isEmpty(user.getNickName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("姓名不能为空、");
        }else{
            if(user.getNickName().length()>8){
                if(checkBox){
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("姓名最多八个字符、");
            }
        }

        if(StringUtils.isEmpty(user.getUserName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("学号不能为空、");
        }else{
            if(user.getUserName().length()>50){
                if(checkBox){
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("学号最多50个字符、");
            }
        }

        if(StringUtils.isEmpty(user.getDeptName())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("所属学院不能为空、");
        }

        if(StringUtils.isEmpty(user.getMajor())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("专业不能为空、");
        }

        if(StringUtils.isNotEmpty(user.getCardNum()) && !StringUtils.isNumeric(user.getCardNum())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("卡号只能为数字、");
        }

        if(StringUtils.isNotEmpty(user.getCardNum())){
            Long carNum10 = Long.parseLong(user.getCardNum());
            String carNum16 = carNum10.toHexString(carNum10).toUpperCase();
            SysUser sysUser = userMapper.selectUserByCardNum(carNum16);
            if(StringUtils.isNotNull(sysUser)){
                if(checkBox){
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("卡号重复、");
            }
        }

        // 验证是否存在这个用户
        SysUser checkUser = userMapper.selectUserByUserName(user.getUserName());
        if (StringUtils.isNotEmpty(user.getUserName()) && StringUtils.isNotNull(checkUser)) {
            if(!sysUserStudentByExcel.getUpDate()){
                if(checkBox){
                    user.getFailRemark().append("失败：");
                    failSysUserList.add(user);
                    checkBox = false;
                }
                user.getFailRemark().append("学号重复、");
            }
        }
        // 验证部门是否存在
        SysDept checkDept = deptMapper.getDeptNameUnique(user.getDeptName());
        if (StringUtils.isNotEmpty(user.getDeptName()) && StringUtils.isNull(checkDept)) {
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("部门不存在、");
        }
        //联系电话重复
        SysUser info = null;
        if(StringUtils.isNotNull(checkUser) && sysUserStudentByExcel.getUpDate()){
            SysUser userInfo = new SysUser();
            userInfo.setUserName(checkUser.getUserName());
            userInfo.setPhonenumber(user.getPhonenumber());
            info = userMapper.checkPhoneUniqueNotOwn(userInfo);
        }else{
            if(StringUtils.isNotEmpty(user.getPhonenumber())){
                info = userMapper.checkPhoneUnique(user.getPhonenumber());
            }
        }
        if(StringUtils.isNotNull(info)){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("联系电话重复、");
        }

        if(StringUtils.isEmpty(user.getPhonenumber())){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("手机号码不能为空、");
        }

        if(StringUtils.isNotEmpty(user.getPhonenumber()) && user.getPhonenumber().length()>11){
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("联系电话错误、");
        }

        //专业是否存在
        SysMajor sysMajor = new SysMajor();
        sysMajor.setMajorName(user.getMajor());
        List<SysMajor> sysMajorList = sysMajorMapper.selectSysMajorList(sysMajor);
        if (sysMajorList.size()==0) {
            if(checkBox){
                user.getFailRemark().append("失败：");
                failSysUserList.add(user);
                checkBox = false;
            }
            user.getFailRemark().append("专业不存在、");
        }
        //日期格式转换
        if(StringUtils.isNotNull(user.getDateBirth())){
            Date time = user.getDateBirth();
            if(StringUtils.isNotNull(time)){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try{
                    int year = time.getYear();
                    int month = time.getMonth();
                    int date = time.getDate();
                    if(year > new Date().getYear()-15) {
                        if (checkBox) {
                            user.getFailRemark().append("失败：");
                            failSysUserList.add(user);
                            checkBox = false;
                        }
                        user.getFailRemark().append("日期格式错误、");
                    }
                }catch (Exception e){
                    if (checkBox) {
                        user.getFailRemark().append("失败：");
                        failSysUserList.add(user);
                        checkBox = false;
                    }
                    user.getFailRemark().append("日期格式错误、");
                    log.error("日期格式错误");
                }
            }
        }

        // 验证是否存在这个导师,如果通过名字查出两个或以上的，则不绑定老师
        List<SysUser> sysUserByTeacherList = userMapper.selectUserByNickName(user.getTutorUserName());
        if(sysUserByTeacherList.size()==1){
            user.setTutorUserId(sysUserByTeacherList.get(0).getUserId());
        }

        if(StringUtils.isNotEmpty(user.getFailRemark())){
            user.getFailRemark().deleteCharAt(user.getFailRemark().length()-1);
        }

        //插入正确数据
        if(StringUtils.isEmpty(user.getFailRemark())){
            SysUser newSysUser = new SysUser();
            newSysUser.setNickName(user.getNickName());
            newSysUser.setUserName(user.getUserName());
            newSysUser.setDeptId(checkDept.getDeptId());
            newSysUser.setMajorId(sysMajorList.get(0).getId());
            newSysUser.setPhonenumber(user.getPhonenumber());
            newSysUser.setEmail(user.getEmail());
            newSysUser.setUserType(UserConstants.USER_TYPE_STUDENT);
            newSysUser.setSex(user.getSex());
            newSysUser.setDateBirth(user.getDateBirth());
            newSysUser.setCardNum(user.getCardNum());
            if(!sysUserStudentByExcel.getSysUserEnable()){
                newSysUser.setStatus(1+"");
            }
            newSysUser.setPassword(SecurityUtils.encryptPassword(password));
            newSysUser.setCreateBy(tokenService.getLoginUser().getNickName());
            if(StringUtils.isNotNull(user.getTutorUserId())){
                newSysUser.setTutorUserId(Integer.parseInt(user.getTutorUserId()+""));
            }
            if(StringUtils.isNotNull(checkUser)){
                newSysUser.setUserId(checkUser.getUserId());
                this.updateUser(newSysUser);
            }else{
                this.insertUser(newSysUser);
            }
        }
    }

    /**
     * 获取教职工下拉框列表
     */
    @Override
    public List<Map<String, Object>> selectOption(SysUser user) {
        return userMapper.selectOption(user);
    }

    /**
     * 根据ID查询电话号码
     *
     * @param ids
     * @return
     */
    @Override
    public List<String> queryPhoneByIds(Long... ids) {
        return userMapper.queryPhoneByIds(ids);
    }

    /***
     * 查询用户信息列表
     * @param sysUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserListByName(SysUser sysUser) {
        return userMapper.selectUserListByName(sysUser);
    }


    /***
     * 根据用户名查询不在白名单的用户
     * @param sysUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserListByNotWhite(SysUser sysUser) {
        return userMapper.selectUserListByNotWhite(sysUser);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> noJoinPositionByList(SysUser user) {
        return userMapper.noJoinPositionByList(user);
    }


    /**
     * 给用户绑定职位
     *
     * @param user 用户信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int bingUserByPosition(SysUser user) {
        Long[] userIds = user.getUserIds();
        for(int i=0;i<userIds.length;i++){
            user.setUserId(userIds[i]);
            userMapper.updateUser(user);
        }
        return 1;
    }


    /**
     * 解除用户绑定职位
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int relieveUserByPosition(SysUser user) {
        if(user.getUserId()!=null){
            userMapper.relieveUserByPosition(user);
        }else{
            Long[] userIds = user.getUserIds();
            for(int i=0;i<userIds.length;i++) {
                user.setUserId(userIds[i]);
                userMapper.relieveUserByPosition(user);
            }
        }
        return 1;
    }
}
