SysUserServiceImpl.java 32.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
package com.bs.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.common.annotation.SynchRecord;
import com.bs.common.constant.SynchRecordConstants;
import com.bs.common.constant.UserConstants;
import com.bs.common.context.SecurityContextHolder;
import com.bs.common.core.domain.SysUserManageScop;
import com.bs.common.core.domain.dto.SysUserDTO;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysRole;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.domain.entity.SysUserDept;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.common.core.page.PageDomain;
import com.bs.common.core.redis.RedisService;
import com.bs.common.enums.CorpUserEnum;
import com.bs.common.enums.RoleType;
import com.bs.common.enums.UserTypes;
import com.bs.common.exception.CustomException;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.StringUtils;
import com.bs.web.domain.SysPost;
import com.bs.web.domain.SysUserPost;
import com.bs.web.domain.SysUserRole;
import com.bs.web.domain.vo.ExternalUserCreateReq;
import com.bs.web.domain.vo.UserRoleVo;
import com.bs.web.domain.vo.UserVo;
import com.bs.web.mapper.*;
import com.bs.web.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

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

/**
 * 用户 业务层处理
 *
 * @author system
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysUserDeptMapper userDeptMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private SysRoleDeptMapper roleDeptMapper;

    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysUserDeptService sysUserDeptService;


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysRoleService sysRoleService;


    @Autowired
    private ISysUserManageScopService iSysUserManageScopService;

    @Autowired
    private RedisService redisService;

    @Value("${system.dept.excludeIds:}")
    private String deptExcludeIds;
    @Value("${rsa.privateKey}")
    private String rasPriKey;
    @Value("${rsa.publicKey}")
    private String rsaPubKey;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    @Override
    public List<UserVo> selectUserVoList(SysUser sysUser, PageDomain pageDomain) {
        List<Long> excludeDeptIds = null;
        try {
            String cfg = org.springframework.util.StringUtils.hasText(deptExcludeIds) ? deptExcludeIds : null;
            if (cfg != null) {
                excludeDeptIds = java.util.Arrays.stream(cfg.split(","))
                        .map(String::trim)
                        .filter(org.apache.commons.lang3.StringUtils::isNotEmpty)
                        .map(Long::valueOf)
                        .collect(java.util.stream.Collectors.toList());
            }
        } catch (Exception ignored) {}
        List<UserVo> userDeptList = userMapper.selectUserDeptList(sysUser, pageDomain, excludeDeptIds);

        if (CollectionUtil.isNotEmpty(userDeptList)) {

            List<UserRoleVo> userRoleList = userMapper.selectUserRoleList(userDeptList.stream().map(UserVo::getUserId).collect(Collectors.toList()));


            List<SysUserManageScop> manageScops = iSysUserManageScopService.list(new LambdaQueryWrapper<SysUserManageScop>()
                    .in(SysUserManageScop::getUserId, userDeptList.stream().map(UserVo::getUserId).collect(Collectors.toList())));


            Map<Long, List<UserRoleVo>> userRoleMap = userRoleList.stream().collect(Collectors.groupingBy(UserRoleVo::getUserId));

            Map<Long, List<SysUserManageScop>> sysUserManageScopMap
                    = manageScops.stream().collect(Collectors.groupingBy(SysUserManageScop::getUserId));



            Set<Long> roleIdSet = new HashSet<>();
            Map<Long, List<SysDept>> map = new HashMap<>();
            userDeptList.stream().filter(Objects::nonNull).forEach(u -> {
                if (CollectionUtils.isNotEmpty(userRoleMap.get(u.getUserId()))) {
                    List<Long> roleIdList = userRoleMap.get(u.getUserId()).stream().map(UserRoleVo::getRoleId).collect(Collectors.toList());
                    u.setRoles(userRoleMap.get(u.getUserId()));
                    roleIdSet.addAll(roleIdList);
                }


                u.setSysUserManageScops(
                        sysUserManageScopMap.get(u.getUserId())
                );

            });
            roleIdSet.stream().filter(Objects::nonNull).forEach(roleId -> {
                List<SysDept> depts = roleDeptMapper.selectRoleDeptList(roleId);
                map.put(roleId, depts);
            });
            return userDeptList.stream().peek(user -> {
                if (CollectionUtils.isNotEmpty(userRoleMap.get(user.getUserId()))) {
                    Set<SysDept> s = new HashSet<>();
                    userRoleMap.get(user.getUserId()).forEach(r -> s.addAll(new HashSet<>(map.get(r.getRoleId()))));
                    user.setRoleDepts(new ArrayList<>(s));
                }
            }).collect(Collectors.toList());
        }

        return new ArrayList<>();
    }

    @Override
    public int selectCountUserDeptList(SysUser sysUser) {
        List<Long> excludeDeptIds = null;
        try {
            String cfg = org.springframework.util.StringUtils.hasText(deptExcludeIds) ? deptExcludeIds : null;
            if (cfg != null) {
                excludeDeptIds = java.util.Arrays.stream(cfg.split(","))
                        .map(String::trim)
                        .filter(org.apache.commons.lang3.StringUtils::isNotEmpty)
                        .map(Long::valueOf)
                        .collect(java.util.stream.Collectors.toList());
            }
        } catch (Exception ignored) {}
        return userMapper.selectCountUserDeptList(sysUser, excludeDeptIds);
    }

    @Override
    @Transactional
    public Long externalCreateUser(ExternalUserCreateReq req) {
        /**
         * 对外创建用户
         * - 校验基础字段与存在性:用户名、手机号、部门、角色等
         * - 密码:优先使用透传的密码;否则取手机号后6位并按RSA加密
         * - 写入用户与部门关联、角色关联等
         * @param req 创建请求
         * @return 新增用户ID
         */
        if (req.getUserName() == null || req.getUserName().trim().isEmpty() || req.getUserName().trim().length() > 20) {
            throw new CustomException("用户名不合法");
        }
        if (req.getPosition() != null && req.getPosition().trim().length() > 50) {
            throw new CustomException("职务长度不能超过50");
        }
        if (req.getPhoneNumber() == null || !java.util.regex.Pattern.matches("^1\\d{10}$", req.getPhoneNumber())) {
            throw new CustomException("手机号格式不合法");
        }
        if (req.getDeptId() == null || sysDeptService.selectDeptById(req.getDeptId()) == null) {
            throw new CustomException("部门不存在");
        }
        if (req.getRoleIds() == null || req.getRoleIds().isEmpty()) {
            throw new com.bs.common.exception.CustomException("角色不能为空");
        }
        for (Long rid : req.getRoleIds()) {
            if (rid == null || sysRoleService.selectRoleById(rid) == null) {
                throw new com.bs.common.exception.CustomException("角色不存在: " + rid);
            }
        }
        RSA rsa = SecureUtil.rsa(rasPriKey, rsaPubKey);
        String encPwd = StringUtils.isNotEmpty(req.getPassword())
                ? req.getPassword()
                : rsa.encryptBase64((req.getPhoneNumber().length() > 5 ? req.getPhoneNumber().substring(req.getPhoneNumber().length() - 6) : "123456"), KeyType.PublicKey);
        SysUser user = new SysUser();
        user.setDeptId(req.getDeptId());
        user.setUserName(req.getUserName().trim());
        user.setWeUserId(req.getUserName().trim());
        user.setNickName(req.getUserName().trim());
        user.setPosition(req.getPosition());
        user.setPhoneNumber(req.getPhoneNumber());
        user.setStatus("0");
        user.setSex("2");
        user.setUserType("02");
        user.setPassword(encPwd);
        user.setDataScope(req.getDataScope() == null ? 5 : req.getDataScope());
        user.setCreateBy(SecurityUtils.getUserName());
        user.setCreateById(SecurityUtils.getUserId());
        user.setUpdateBy(SecurityUtils.getUserName());
        user.setUpdateById(SecurityUtils.getUserId());
        user.setUpdateTime(new Date());
        user.setDelFlag(0);
        user.setIsUserLeave(0);
        user.setRoleIds(req.getRoleIds().toArray(new Long[0]));
        this.insertUser(user);
        SysUserDept userDept = new SysUserDept();
        userDept.setOrderInDept("0");
        userDept.setLeaderInDept(0);
        userDept.setUserId(user.getUserId());
        userDept.setWeUserId(user.getUserName());
        userDept.setDeptId(req.getDeptId());
        userDept.setDelFlag("0");
        userDept.setCreateBy(SecurityUtils.getUserName());
        userDept.setCreateById(SecurityUtils.getUserId());
        userDept.setCreateTime(new Date());
        userDept.setUpdateBy(SecurityUtils.getUserName());
        userDept.setUpdateById(SecurityUtils.getUserId());
        userDept.setUpdateTime(new Date());
        userDeptMapper.insert(userDept);
        return user.getUserId();
    }

    @Override
    @Transactional
    public Long externalUpdateUser(com.bs.web.domain.vo.ExternalUserUpdateReq req) {
        /**
         * 对外修改用户
         * - 支持修改用户名、部门、职务、手机号、数据范围、密码、角色等
         * - 变更部门时,旧部门映射置为删除,新建一条最新映射
         * - 变更角色时,清空旧映射并批量重建
         * @param req 修改请求
         * @return 用户ID
         */
        if (req.getUserId() == null) {
            throw new CustomException("用户ID不能为空");
        }
        SysUser user = this.getById(req.getUserId());
        if (user == null) {
            throw new CustomException("用户不存在");
        }
        if (StringUtils.isNotEmpty(req.getUserName())) {
            if (req.getUserName().trim().length() > 20) {
                throw new CustomException("用户名长度不能超过20");
            }
            String trimmedName = req.getUserName().trim();
            if (!trimmedName.equals(user.getUserName())) {
                SysUser existUser = userMapper.selectUserByUserName(trimmedName);
                if (existUser != null && !existUser.getUserId().equals(user.getUserId())) {
                    throw new CustomException("用户名已存在");
                }
            }
            user.setUserName(trimmedName);
            user.setNickName(trimmedName);
        }
        if (StringUtils.isNotEmpty(req.getPosition())) {
            if (req.getPosition().trim().length() > 50) {
                throw new CustomException("职务长度不能超过50");
            }
            user.setPosition(req.getPosition());
        }
        if (StringUtils.isNotEmpty(req.getPhoneNumber())) {
            if (!java.util.regex.Pattern.matches("^1\\d{10}$", req.getPhoneNumber())) {
                throw new CustomException("手机号格式不合法");
            }
            if (!req.getPhoneNumber().equals(user.getPhoneNumber())) {
                SysUser existPhoneUser = userMapper.checkPhoneUnique(req.getPhoneNumber(),null);
                if (existPhoneUser != null && !existPhoneUser.getUserId().equals(user.getUserId())) {
                    throw new CustomException("手机号已存在");
                }
            }
            user.setPhoneNumber(req.getPhoneNumber());
        }
        if (req.getDataScope() != null) {
            user.setDataScope(req.getDataScope());
        }
        if (StringUtils.isNotEmpty(req.getPassword())) {
            user.setPassword(req.getPassword());
        }
        if (req.getDeptId() != null) {
            if (sysDeptService.selectDeptById(req.getDeptId()) == null) {
                throw new CustomException("部门不存在");
            }
            user.setDeptId(req.getDeptId());
            UpdateWrapper<SysUserDept> uw = new UpdateWrapper<>();
            uw.lambda().eq(SysUserDept::getUserId, user.getUserId()).set(SysUserDept::getDelFlag, "2");
            userDeptMapper.update(null, uw);
            SysUserDept userDept = new SysUserDept();
            userDept.setUserId(user.getUserId());
            userDept.setDeptId(req.getDeptId());
            userDept.setDelFlag("0");
            userDept.setCreateBy(SecurityUtils.getUserName());
            userDept.setCreateById(SecurityUtils.getUserId());
            userDept.setCreateTime(new Date());
            userDept.setUpdateBy(SecurityUtils.getUserName());
            userDept.setUpdateById(SecurityUtils.getUserId());
            userDept.setUpdateTime(new Date());
            userDeptMapper.insert(userDept);
        }
        user.setUpdateBy(SecurityUtils.getUserName());
        user.setUpdateById(SecurityUtils.getUserId());
        userMapper.updateUser(user);
        if (req.getRoleIds() != null && !req.getRoleIds().isEmpty()) {
            for (Long rid : req.getRoleIds()) {
                if (rid == null || sysRoleService.selectRoleById(rid) == null) {
                    throw new CustomException("角色不存在: " + rid);
                }
            }
            userRoleMapper.deleteUserRoleByUserId(user.getUserId());
            List<SysUserRole> list = new ArrayList<>();
            for (Long rid : req.getRoleIds()) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(rid);
                list.add(ur);
            }
            if (!list.isEmpty()) {
                userRoleMapper.batchUserRole(list);
            }
        }
        return user.getUserId();
    }

    @Override
    @Transactional
    public Long externalSoftDeleteUser(Long userId) {
        /**
         * 对外软删除用户
         * - 将用户del_flag置为1,并更新审计字段
         * - 同步将部门关联映射置为删除
         * @param userId 用户ID
         * @return 用户ID
         */
        if (userId == null) {
            throw new CustomException("用户ID不能为空");
        }
        SysUser user = this.getById(userId);
        if (user == null) {
            throw new CustomException("用户不存在");
        }
        user.setDelFlag(1);
        user.setUpdateBy(SecurityUtils.getUserName());
        user.setUpdateById(SecurityUtils.getUserId());
        user.setUpdateTime(new Date());
        this.baseMapper.updateById(user);
        UpdateWrapper<SysUserDept> uw = new UpdateWrapper<>();
        uw.lambda().eq(SysUserDept::getUserId, userId).set(SysUserDept::getDelFlag, "2")
                .set(SysUserDept::getUpdateBy, SecurityUtils.getUserName())
                .set(SysUserDept::getUpdateById, SecurityUtils.getUserId())
                .set(SysUserDept::getUpdateTime, new Date());
        userDeptMapper.update(null, uw);
        // 删除用户角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        return userId;
    }
    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户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(), null);
        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()) && user.isAdmin()) {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改用户状态
     *
     * @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);
            }
        }
    }

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

        deleteUserByIds(Collections.singletonList(userId));
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public void deleteUserByIds(List<Long> userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
        }
        update(new LambdaUpdateWrapper<SysUser>().set(SysUser::getDelFlag, 1).in(SysUser::getUserId, 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 CustomException("导入用户数据不能为空!");
        }
        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((SysUserDTO) 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 CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
        }
        return successMsg.toString();
    }

    @Override
    public SysUser selectUserByWeUserId(String weUserId) {
        return this.baseMapper.selectUserByWeUserId(weUserId);
    }


    @Override
    @Transactional
    public void editUserRole(SysUserDTO user) {

        SysUser sysUser = this.getById(user.getUserId());
        if (null != sysUser) {
            //删除原有角色
            userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
            List<Long> roleIds = ListUtil.toList(user.getRoleIds());
            if (CollectionUtil.isNotEmpty(roleIds)) {

                List<SysRole> sysRoles = roleMapper.selectBatchIds(roleIds);

                if (CollectionUtil.isNotEmpty(sysRoles)) {
                    //新增新角色
                    List<SysUserRole> sysUserRoles = new ArrayList<>();
                    sysRoles.stream().forEach(sysUserRole -> {
                        //查询角色类
                        sysUserRoles.add(
                                SysUserRole.builder()
                                        .userId(sysUser.getUserId())
                                        .roleId(sysUserRole.getRoleId())
                                        .build()
                        );
                    });
                    userRoleMapper.batchUserRole(sysUserRoles);

                    Set<String> roleKeys
                            = sysRoles.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());

                    if (roleKeys.contains(RoleType.WECOME_USER_TYPE_FJGLY.getSysRoleKey())) {//分级管理员
                        sysUser.setUserType(UserTypes.USER_TYPE_FJ_ADMIN.getSysRoleKey());
                    } else if (roleKeys.contains(RoleType.WECOME_USER_TYPE_CY.getSysRoleKey())) {//普通成员
                        sysUser.setUserType(UserTypes.USER_TYPE_COMMON_USER.getSysRoleKey());
                    } else {
                        sysUser.setUserType(UserTypes.USER_TYPE_SELFBUILD_USER.getSysRoleKey());//自建角色
                    }
                    this.updateById(sysUser);
                }


            }
        }
    }

    @Override
    public void editDataScop(SysUserDTO user) {

        SysUser sysUser = this.getById(user.getUserId());
        if(null != sysUser){
            sysUser.setDataScope(user.getDataScope());

            if(this.updateById(sysUser)){
                List<SysUserManageScop> sysUserManageScops = user.getSysUserManageScops();

                if(CollectionUtil.isNotEmpty(sysUserManageScops)){
                    iSysUserManageScopService.remove(new LambdaQueryWrapper<SysUserManageScop>()
                            .eq(SysUserManageScop::getUserId,user.getUserId()));
                    iSysUserManageScopService.saveBatch(sysUserManageScops);
                }
            }
        }


    }

    @Override
    public void batchEditUserRole(Long roleId, List<SysUserDTO> users) {

        List<SysUser> sysUsers
                = this.listByIds(users.stream().map(SysUserDTO::getUserId).collect(Collectors.toSet()));

        if (CollectionUtil.isNotEmpty(sysUsers)) {
            //删除原有角色用户的当前角色
            userRoleMapper.deleteUserRole(
                    sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet()).toArray(new Long[]{}), roleId
            );

            SysRole sysRole = roleMapper.selectRoleById(roleId);

            if (null != sysRole) {
                //新增新角色
                List<SysUserRole> sysUserRoles = new ArrayList<>();
                sysUsers.stream().forEach(user -> {
                    //查询角色类
                    sysUserRoles.add(
                            SysUserRole.builder()
                                    .userId(user.getUserId())
                                    .roleId(roleId)
                                    .build()
                    );

                    if (RoleType.WECOME_USER_TYPE_FJGLY.getSysRoleKey().contains(sysRole.getRoleKey())) {//分级管理员
                        user.setUserType(UserTypes.USER_TYPE_FJ_ADMIN.getSysRoleKey());

                    } else if (RoleType.WECOME_USER_TYPE_CY.getSysRoleKey().contains(sysRole.getRoleKey())) {//普通成员

                        user.setUserType(UserTypes.USER_TYPE_COMMON_USER.getSysRoleKey());
                    } else {
                        user.setUserType(UserTypes.USER_TYPE_SELFBUILD_USER.getSysRoleKey());//自建角色
                    }


                });

                userRoleMapper.batchUserRole(sysUserRoles);


//                this.updateBatchById(sysUsers);
                this.baseMapper.batchAddOrUpdate(sysUsers);


            }


        }

    }


    @Override
    public List<SysUser> findAllSysUser(String weUserIds, String positions, String deptIds) {
        return this.baseMapper.findAllSysUser(weUserIds, positions, deptIds);
    }

    @Override
    public SysUser findOrSynchSysUser(String weUserId) {

        List<SysUser> sysUser = this.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getWeUserId, weUserId)
                .eq(SysUser::getDelFlag, 0));

        if (CollectionUtil.isEmpty(sysUser)) {//保存在则从企业微信端获取同时入库
            return null;
        }

        return sysUser.get(0);
    }



    @Override
    public List<String> screenConditWeUser(String weUserIds, String deptIds, String positions) {
        List<String> weUserIdList = new ArrayList<>();

        if (StringUtils.isNotEmpty(weUserIds)) {
            weUserIdList.addAll(
                    ListUtil.toList(weUserIds.split(","))
            );
        }


        if (StringUtils.isNotEmpty(positions) || StringUtils.isNotEmpty(deptIds)) {
            List<SysUser> allSysUser = this.baseMapper.findAllSysUser(null, positions, deptIds);
            if (CollectionUtil.isNotEmpty(allSysUser)) {
                weUserIdList.addAll(
                        allSysUser.stream().map(SysUser::getWeUserId).collect(Collectors.toList())
                );
            }
        }
        return weUserIdList;
    }

    @Override
    @Transactional
    public void builderLeaveSysUser(List<SysUser> sysUsers) {
        if (CollectionUtil.isNotEmpty(sysUsers)) {
            this.updateBatchById(sysUsers);
            this.removeByIds(sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toList()));
        }

    }


}