package com.bonus.system.basic.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.constant.UserConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.FastJsonHelper;
import com.bonus.common.core.utils.ImportExcelUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.common.security.utils.ValidatorsUtils;
import com.bonus.system.api.domain.MapVo;
import com.bonus.system.api.domain.SysDictData;
import com.bonus.system.api.domain.SysRole;
import com.bonus.system.api.model.LoginUser;
import com.bonus.system.att.entity.OrgChangeBean;
import com.bonus.system.att.service.OrgChangeService;
import com.bonus.system.basic.domain.SysOrg;
import com.bonus.system.basic.domain.SysUserOrg;
import com.bonus.system.basic.domain.SysUserPost;
import com.bonus.system.basic.domain.SysUserRole;
import com.bonus.system.basic.service.SysMenuService;
import com.bonus.system.dept.service.SubOrgServiceImpl;
import com.bonus.system.holiday.entity.HolidayImportBean;
import com.bonus.system.holiday.entity.HolidayKeyBean;
import io.swagger.models.auth.In;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.basic.dao.SysUserMapper;
import com.bonus.system.basic.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户 业务层处理
 *
 * @author zys
 */
@Service
@Log4j2
public class SysUserServiceImpl implements SysUserService
{

    @Resource
    private SysUserMapper userMapper;

    @Resource(name = "sysMenuService")
    private SysMenuService sysMenuService;

    @Resource(name = "SubOrgService")
    private SubOrgServiceImpl subOrgServiceImpl;

    @Resource(name = "OrgChangeService")
    private OrgChangeService orgChangeService;

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public R<LoginUser> selectUserByUserName(String userName)
    {
        SysUser sysUser = userMapper.selectUserByUserName(userName);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        //角色集合
        List<MapVo> orgList = userMapper.getOrgByUserId(sysUser);
        sysUser.setOrgList(orgList);
        // 获取考勤组
        List<MapVo> attGroupList = userMapper.getAttGroupByUserId(sysUser);
        if(!attGroupList.isEmpty()){
            sysUser.setAttGroupId(attGroupList.get(0).getId());
            sysUser.setAttGroupName(attGroupList.get(0).getName());
        }
        List<String> roleList =  userMapper.getRoleListById(sysUser);
        sysUser.setRoleList(roleList);
        // 权限集合
        Set<String> permissions = sysMenuService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setPermission(permissions);
        return R.ok(sysUserVo);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public List<MapVo> getOrgByUserId(SysUser user) {
        return userMapper.getOrgByUserId(user);
    }

    @Override
    public List<SysUser> selectUserList(SysUser bean) {
        List<SysUser> list = userMapper.selectUserList(bean);
        if (!list.isEmpty()){
            for (SysUser sysUser : list) {
                //角色集合
                Long[] roleIds = userMapper.getRoleIdsByUserId(sysUser.getUserId());
                //组织集合
                Long[] orgIds = userMapper.getOrgIdsByUserId(sysUser.getUserId());
                //岗位集合
                Long[] postIds = userMapper.getPostIdsByUserId(sysUser.getUserId());
                sysUser.setRoleIds(roleIds);
                sysUser.setOrgIds(orgIds);
                sysUser.setPostIds(postIds);
            }
        }
        return list;
    }

    @Override
    public AjaxResult getSelectRole() {
        try {
            List<SysRole> list = userMapper.getSelectRole();
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getSelectPost() {
        try {
            List<SysDictData> list = userMapper.getSelectPost();
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getSelectUser() {
        try {
            List<SysUser> list = userMapper.getSelectUser();
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult resetPwd(SysUser user) {
        String password = SecurityUtils.encryptPassword(SecurityConstants.DEFAULT_PASSWORD);
        user.setPassword(password);
        int result = userMapper.updateUser(user);
        return AjaxResult.success();
    }

    @Override
    public boolean checkIdNumberUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkIdNumberUnique(user.getIdNumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public AjaxResult updatePwd(SysUser user) {
        try {
            //查询用户密码
            SysUser u = userMapper.selectUserById(user.getUserId());
            if (! SecurityUtils.matchesPassword(user.getOldPassword(), u.getPassword())) {
                AjaxResult.error("旧密码错误");
            }
            String newPassword = SecurityUtils.encryptPassword(user.getPassword());
            SysUser newUser = new SysUser();
            newUser.setUserId(user.getUserId());
            newUser.setPassword(newPassword);
            int result = userMapper.updateUser(newUser);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error("修改失败");
        }
    }

    @Override
    public AjaxResult getSelectUserCurrent() {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        try {
            List<SysUser> list = userMapper.getSelectUserCurrent(userId);
            return AjaxResult.success(list);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult updateIsFace(SysUser user) {
        int result = userMapper.updateIsFace(user);
        if (result == 0) {
            return AjaxResult.error("修改失败");
        }else if (result == 1) {
            return AjaxResult.success();
        }else {
            return AjaxResult.error("修改失败");
        }
    }

    @Override
    public int checkPersonAssignment(SysUser bean) {
        return userMapper.checkPersonAssignment(bean);
    }

    @Override
    public List<MapVo> getAttGroupByUserId(SysUser user) {
        return userMapper.getAttGroupByUserId(user);
    }

    @Override
    public int updatePermission(SysUser user) {
        try {
            Long userId = user.getUserId();
            //删除用户与角色关联
            userMapper.deleteUserRoleByUserId(userId);
            insertUserRole(user);
            return userMapper.updateUser(user);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return 0;
        }
    }

    @Override
    public List<String> getRoleList(SysUser user) {
        return userMapper.getRoleListById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long userId) {
        try {
            //删除sys_user_org
            userMapper.deleteUserOrgByUserId(userId);
            //删除sys_user_role
            userMapper.deleteUserRoleByUserId(userId);
            //删除sys_user_post
            userMapper.deleteUserPostByUserId(userId);
            //删除人员角色分配的数据 sys_department_user
            subOrgServiceImpl.syncDelUser(userId);
            // 删除考勤组数据
            userMapper.delAttGroupPersonRelation(userId);
            return userMapper.deleteUserById(userId);
        } catch (Exception e) {
            log.error(e.toString(),e);
            return 0;
        }
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {
        try {
            Long userId = user.getUserId();
            //删除用户与岗位关联
            userMapper.deleteUserPostByUserId(userId);
            insertUserPost(user,1);
            //删除用户与角色关联
            userMapper.deleteUserRoleByUserId(userId);
            insertUserRole(user);
            //删除用户与组织关联
            //旧组织
            Long[] orgIdsByUserId = userMapper.getOrgIdsByUserId(userId);
            //新组织
            Long[] orgIds = user.getOrgIds();
            //绑定考勤组组织
            Long orgId = userMapper.getUserAttGroupByUserId(userId);
            if (orgId == null || containsOrgId(orgIds,orgId)) {
                //没有考勤组或新变换的组织包含考勤组组织，不变
            }else{
                List<Long> uniqueInOrgIds = findUniqueInOrgIds(orgIds, orgIdsByUserId);
                if(!uniqueInOrgIds.isEmpty()){
                    OrgChangeBean item = new OrgChangeBean();
                    item.setOldOrgId(orgId);
                    item.setNewOrgId(uniqueInOrgIds.get(0));
                    item.setUserId(userId);
                    userMapper.updateAttOrgByUserId(item);
                }
            }
            userMapper.deleteUserOrgByUserId(userId);
            insertUserOrg(user);
            //处理人员组织变更，休假/外出/等审批组织
            dealOrgUserLeave(orgIdsByUserId,user);
             return userMapper.updateUser(user);
        } catch (Exception e) {
             log.error(e.toString(),e);
            return 0;
        }
    }

    private static Map<String,List<Long>> compareMaps(Map<Long, Long> A, Map<Long, Long> B) {
        Set<Long> allKeys = new HashSet<>(A.keySet());
        allKeys.addAll(B.keySet());
        Map<String,List<Long>> map = new HashMap<>();
        List<Long> orgIds = new ArrayList<>();
        List<Long> sameList = new ArrayList<>();
        for (Long key : allKeys) {
            Long valueA = A.get(key);
            Long valueB = B.get(key);
            if (valueA == null) {
                orgIds.add(valueB);
                System.out.println("Key " + key + " is added in B with value " + valueB);
            } else if (valueB == null) {
                System.out.println("Key " + key + " is removed from A");
            } else if (!valueA.equals(valueB)) {
                orgIds.add(valueB);
                System.out.println("Key " + key + ": Changed from " + valueA + " to " + valueB);
            } else if (valueA.equals(valueB)) {
                sameList.add(valueB);
                System.out.println("Key " + key + ": no Changed from " + valueA + " to " + valueB);
            }
        }
        map.put("same",sameList);
        map.put("notSame",orgIds);
        return map;
    }

    private static boolean compareSameMaps(Map<Long, Long> A, Map<Long, Long> B) {
        Set<Long> allKeys = new HashSet<>(A.keySet());
        allKeys.addAll(B.keySet());
        List<Long> orgIds = new ArrayList<>();
         for (Long key : allKeys) {
            Long valueA = A.get(key);
             Long valueB = B.get(key);
             if (valueA == null) {
                System.out.println("Key " + key + " is added in B with value " + valueB);
              } else if (valueB == null) {
                System.out.println("Key " + key + " is removed from A");
             } else if (!valueA.equals(valueB)) {
                System.out.println("Key " + key + ": Changed from " + valueA + " to " + valueB);
            } else if (valueA.equals(valueB)) {
                orgIds.add(valueB);
                System.out.println("Key " + key + ": no Changed from " + valueA + " to " + valueB);
            }
        }
         if(!orgIds.isEmpty() && orgIds.size() == A.size()){
                      return true;
        }
        return false;
    }

    private static Map<Long, Long> arrayToMapUsingElementToList(Long[] array) {
        Map<Long, Long> map = new HashMap<>();
        for (int i = 0; i < array.length; i++) {
            // 这里我们简单地使用元素自身作为值
            map.put(array[i], array[i]);
        }
        return map;
    }

    /**
     * 处理用户退出组织时的逻辑
     * 当用户退出组织时，需要更新或处理与该用户相关的组织信息
     * 此方法旨在根据用户ID获取其相关的组织ID列表，并执行相应的处理逻辑
     *
     * @param orgIdsByUserId 用户相关的组织ID列表，表示该用户属于哪些组织
     * @param user           退出组织的用户信息，包含用户ID等必要数据
     */
    private void dealOrgUserLeave(Long[] orgIdsByUserId, SysUser user) {

        //比较老旧组织的是否发生改变

        Map<Long, Long> oldOrgArray = arrayToMapUsingElementToList(orgIdsByUserId);
         Map<Long, Long> newOrgArray = arrayToMapUsingElementToList(user.getOrgIds());
        boolean isSame = compareSameMaps(oldOrgArray, newOrgArray);
        if(isSame){
            //无变化集合
        }else{
            //有变化的集合
            Map<String,List<Long>> map = compareMaps(oldOrgArray, newOrgArray);
            if(user.getOrgIds().length == 1){
                //A -> B,AB -> A,AB -> C
                SysUser users = new SysUser();
                users.setUserId(user.getUserId());
                users.setOrgId(user.getOrgIds()[0] + "");
                SysOrg orgBean = userMapper.findOrgByOrgId(users);
                users.setOrgName(orgBean.getOrgName());
                userMapper.updateOrgIdByUserId(users);
            }else{
                //A -> BC,AB -> AC,AB -> CD
                List<Long> sameList = map.get("same");
                List<Long> notSameList = map.get("notSame");
                SysUser users = new SysUser();
                users.setUserId(user.getUserId());
                users.setOrgId(notSameList.get(0) + "");
                users.setOrgListIds(sameList);
                SysOrg orgBean = userMapper.findOrgByOrgId(users);
                users.setOrgName(orgBean.getOrgName());
                userMapper.updateOrgIdByUserIdWithOutSame(users);
            }
        }
    }

    public static boolean containsOrgId(Long[] orgIds, Long orgId) {
        // 将数组转换为 List
        return Arrays.asList(orgIds).contains(orgId);
    }

    public static List<Long> findUniqueInOrgIds(Long[] orgIds, Long[] orgIdsByUserId) {
        // 将两个数组转换为 Set
        Set<Long> orgIdSet = new HashSet<>(Arrays.asList(orgIds));
        Set<Long> orgIdByUserSet = new HashSet<>(Arrays.asList(orgIdsByUserId));
        // 计算差集：只保留在 orgIds 中的元素
        orgIdSet.removeAll(orgIdByUserSet);
        // 将结果转换回数组
        return new ArrayList<>(orgIdSet);
    }

    @Resource(name = "ValidatorsUtils")
    private ValidatorsUtils validatorsUtils;
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult excelUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<JSONObject> listObj = ImportExcelUtils.readExcel(file, SysUser.class, "");
            List<SysUser> list = new ArrayList<>();
            if (CollectionUtils.isEmpty(listObj)) {
                return AjaxResult.error("请勿导入空数据");
            }
            // 获取人员信息
            for (JSONObject obj : listObj) {
                SysUser vo = FastJsonHelper.jsonObjToBean(obj, SysUser.class);
                String validResult = validatorsUtils.valid(vo, SysUser.class);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(validResult)) {
                    return AjaxResult.error("第" + obj.getString("rowNo") + "行" + validResult);
                }
                list.add(vo);
            }
            //校验数据库是否存在
            //查询数据库中的部门数据
            List<HolidayKeyBean> orgList = userMapper.getOrgList();
            //查询数据库中的角色数据
            List<HolidayKeyBean> roleList = userMapper.getRoleList();
            //查询数据库中的岗位数据
            List<HolidayKeyBean> postList = userMapper.getPostList();
            int i = 0;
            for (SysUser user : list){
                i++;
                //检查手机号是否重复
                if (!checkPhoneUnique(user)){
                    return AjaxResult.error("第" + i + "行，手机号已存在");
                }
                //校验身份证是否合规
                if (!validateIDCard(user)){
                    return AjaxResult.error("第" + i + "行，身份证号不合规");
                }
                //检查身份证是否存在
                if (!idCardIsExist(user)){
                    return AjaxResult.error("第" + i + "行，身份证号已存在");
                }

                if ("是".equals(user.getIsCadre())){

                }else if("否".equals(user.getIsCadre())){

                }else{
                    return AjaxResult.error("第" + i + "行，是否干部只是为‘是’、‘否’");
                }


                List<Long> orgIds = new ArrayList<>();
                List<Long> roleIds = new ArrayList<>();
                List<Long> postIds = new ArrayList<>();
                if (!codeIsExist(orgList, user, 1,orgIds)){
                    return AjaxResult.error("第" + i + "行，部门不存在");
                }
                if (!codeIsExist(roleList, user, 2, roleIds)){
                    return AjaxResult.error("第" + i + "行，角色不存在");
                }
                if (!codeIsExist(postList, user, 3,postIds)){
                    return AjaxResult.error("第" + i + "行，岗位不存在");
                }
                user.setOrgIds(orgIds.toArray(new Long[0]));
                user.setRoleIds(roleIds.toArray(new Long[0]));
                user.setPostIds(postIds.toArray(new Long[0]));
            }
            for (SysUser user : list){
                String createBy = String.valueOf(SecurityUtils.getLoginUser().getSysUser().getUserId());
                user.setCreateBy(createBy);
                user.setPassword(SecurityUtils.encryptPassword(SecurityConstants.DEFAULT_PASSWORD));
                if("是".equals(user.getIsCadre())){
                    user.setIsCadre("1");
                }else if("否".equals(user.getIsCadre())){
                    user.setIsCadre("0");
                }
                int res = userMapper.insertUser(user);
                if (res > 0){
                    //新增sys_user_role
                    insertUserRole(user);
                    //新增sys_user_org
                    insertUserOrg(user);
                    //新增sys_user_post
                    insertUserPost(user,2);
                }else {
                    throw new RuntimeException("新增失败");
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    private boolean validateIDCard(SysUser user) {
        String idCard = user.getIdNumber();
        if (idCard == null || idCard.length() != 18) {
            return false;
        }

        // 地区码校验（这里仅做长度校验，实际应校验地区码是否合法）
        String areaCode = idCard.substring(0, 6);
        if (!areaCode.matches("\\d{6}")) {
            return false;
        }

        // 出生日期校验
        String birthDateStr = idCard.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sdf.setLenient(false);
        try {
            Date birthDate = sdf.parse(birthDateStr);
            // 这里可以增加对日期的合理性校验，例如不能是未来的日期等
        } catch (ParseException e) {
            return false;
        }

        // 顺序码校验（这里仅做长度和数字校验）
        String orderCode = idCard.substring(14, 17);
        if (!orderCode.matches("\\d{3}")) {
            return false;
        }

        return true;
    }

    private boolean idCardIsExist(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkIdNumberUnique(user.getIdNumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 判断导入部门、请假类型 是否存在
     * @param list
     * @param value
     * @return boolean
     * @author fly
     * @date 2024/10/15 18:09
     */
    public boolean codeIsExist(List<HolidayKeyBean> list, SysUser value, int type,List<Long> ids) {
        if (value == null) {
            throw new IllegalArgumentException("SysUser cannot be null.");
        }
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }
        //如果名字里面有逗号，分割，并循环判断
        String[] names=null;
        switch (type){
            case 1:
                names = StringUtils.split(value.getOrgName(), ",");
                break;
            case 2:
                names = StringUtils.split(value.getRoleName(), ",");
                break;
            case 3:
                names = StringUtils.split(value.getPostName(), ",");
                break;
            default:
                return false;
        }
        for (String name : names){
            for (HolidayKeyBean map : list){
                if (isMatch(type, map.getName(), name)) {
                    Long idStr = map.getId();
                    handleId(idStr, type, value, ids);
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 判断是否匹配
     */
    private boolean isMatch(int type, String name, String value) {
        return Objects.equals(name, value);
    }

    /**
     * 提取公共方法处理 id 设置
     */
    private boolean handleId(Long id, int type, SysUser value,List<Long> ids) {
        if (id == null) {
            return false;
        }
        ids.add(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertUser(SysUser user) {
        try{
            //判断手机号是否存在
            SysUser bean =new SysUser();
            bean.setPhone(user.getPhone());
            int phoneCount = userMapper.selectUserList(bean).size();
            if(phoneCount>0){
                return AjaxResult.warn("手机号已存在");
            }
            //查询名称是否存在，若存在则查出所在部门
            List<SysUser> list2 =userMapper.selectUserByUserNames(user.getUserName());
            if (list2.size()>0){
//                //判断user.getOrgId是否在list2中
//                Long[] orgId = user.getOrgIds();
//                for (Long aLong : orgId){
//                    for (SysUser sysUser : list2) {
//                        if (Objects.equals(aLong+"", sysUser.getOrgId())){
                return AjaxResult.warn("该用户名已存在");
//                        }
//                    }
//                }
            }
            user.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getSysUser().getUserId()));
            user.setPassword(SecurityUtils.encryptPassword(SecurityConstants.DEFAULT_PASSWORD));
            //新增sys_user,返回Id
            int res = userMapper.insertUser(user);
            if (res>0){
                //新增sys_user_role
                insertUserRole(user);
                //新增sys_user_org
                insertUserOrg(user);
                //新增sys_user_post
                insertUserPost(user,1);
                return AjaxResult.success();
            }else {
                return AjaxResult.error();
            }
        } catch (Exception e) {
            log.error(e.toString(),e);
            return AjaxResult.error();
        }
    }

    /**
     * 新增用户与岗位管理
     *
     * @param user 用户对象
     */
    private void insertUserOrg(SysUser user) {
        Long[] orgIds = user.getOrgIds();
        if (StringUtils.isNotNull(orgIds)) {
            // 新增用户与岗位管理
            List<SysUserOrg> list = new ArrayList<SysUserOrg>();
            for (Long orgId : orgIds) {
                SysUserOrg mapVo = new SysUserOrg();
                mapVo.setUserId(user.getUserId());
                mapVo.setOrgId(orgId);
                list.add(mapVo);
            }
            // 批量新增用户岗位信息
            userMapper.insertUserOrg(list);
        }
    }

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

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user, Integer type) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                String postIds="";
                SysUserPost up = new SysUserPost();
                if (type == 1){
                    //查询postId
                    postIds = userMapper.selectPostIdById(postId);
                    up.setPostId(Long.valueOf(postIds));
                }else if (type == 2){
                    up.setPostId(postId);
                }
                up.setUserId(user.getUserId());
                list.add(up);
            }
            // 批量新增用户岗位信息
            userMapper.insertUserPost(list);
        }
    }

}
