package com.yunzhupaas.permission.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.ImmutableList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.annotation.UserPermission;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.Page;
import com.yunzhupaas.base.Pagination;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.controller.SuperController;
import com.yunzhupaas.base.entity.DictionaryDataEntity;
import com.yunzhupaas.base.service.DictionaryDataService;
import com.yunzhupaas.base.service.SysconfigService;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.base.vo.ListVO;
import com.yunzhupaas.base.vo.PageListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.flowable.enums.ExtraRuleEnum;
import com.yunzhupaas.message.service.SynThirdDingTalkService;
import com.yunzhupaas.message.service.SynThirdQyService;
import com.yunzhupaas.model.*;
import com.yunzhupaas.model.tenant.AdminInfoVO;
import com.yunzhupaas.model.tenant.TenantReSetPasswordForm;
import com.yunzhupaas.model.tenant.TenantVO;
import com.yunzhupaas.permission.constant.UserColumnMap;
import com.yunzhupaas.permission.entity.*;
import com.yunzhupaas.permission.model.check.CheckResult;
import com.yunzhupaas.permission.model.permission.PermissionModel;
import com.yunzhupaas.permission.model.role.RoleModel;
import com.yunzhupaas.permission.model.user.UserIdListVo;
import com.yunzhupaas.permission.model.user.WorkHandoverModel;
import com.yunzhupaas.permission.model.user.form.UserCrForm;
import com.yunzhupaas.permission.model.user.form.UserResetPasswordForm;
import com.yunzhupaas.permission.model.user.form.UserUpForm;
import com.yunzhupaas.permission.model.user.mod.*;
import com.yunzhupaas.permission.model.user.page.PageUser;
import com.yunzhupaas.permission.model.user.page.PaginationUser;
import com.yunzhupaas.permission.model.user.vo.*;
import com.yunzhupaas.permission.rest.PullUserUtil;
import com.yunzhupaas.permission.service.*;
import com.yunzhupaas.base.util.ExcelTool;
import com.yunzhupaas.permission.util.PermissionUtil;
import com.yunzhupaas.service.AuthService;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.enums.DictionaryDataEnum;
import com.yunzhupaas.util.treeutil.SumTree;
import com.yunzhupaas.util.treeutil.newtreeutil.TreeDotUtils;
import com.yunzhupaas.workflow.service.TemplateApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.yunzhupaas.util.Constants.ADMIN_KEY;

/**
 * 用户管理
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024-09-26 上午9:18
 */
@Tag(name = "用户管理", description = "Users")
@Slf4j
@RestController
@RequestMapping("/api/permission/Users")
public class UserController extends SuperController<UserService, UserEntity> {

    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private SynThirdQyService synThirdQyService;
    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private PermissionGroupService permissionGroupService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private TemplateApi templateApi;

    @Autowired
    private AuthService authService;
    @Autowired
    private DictionaryDataService dictionaryDataApi;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private SysconfigService sysconfigApi;

    /**
     * 获取用户列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @Operation(summary = "获取用户列表")
    @GetMapping
    public ActionResult<PageListVO<UserListVO>> getList(PaginationUser pagination) {
        List<UserEntity> userList = userService.getList(pagination, pagination.getOrganizeId(), false, true, pagination.getEnabledMark(), pagination.getGender());
        List<UserListVO> list = new ArrayList<>();
        // 得到性别
        List<DictionaryDataEntity> dataServiceList4 = dictionaryDataApi.getListByTypeDataCode("sex");
        Map<String, String> dataServiceMap4 = dataServiceList4.stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName));
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        for (UserEntity userEntity : userList) {
            UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class);
            userVO.setHandoverMark(userEntity.getHandoverMark() == null ? 0 : userEntity.getHandoverMark());
            userVO.setHeadIcon(UploaderUtil.uploaderImg(userVO.getHeadIcon()));
            // 时间小于当前时间则判断已解锁
            if (userVO.getEnabledMark() != null && userVO.getEnabledMark() != 0) {
                if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) {
                    userVO.setEnabledMark(2);
                } else if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() < System.currentTimeMillis()) {
                    userVO.setEnabledMark(1);
                }
            }
            List<UserRelationEntity> orgRelationByUserId = userRelationService.getAllOrgRelationByUserId(userEntity.getId());
            // 储存组织id信息
            StringJoiner stringJoiner = new StringJoiner(",");
            for (UserRelationEntity userRelationEntity : orgRelationByUserId) {
                // 获取组织id详情
                OrganizeEntity entity = organizeService.getInfo(userRelationEntity.getObjectId());
                if (entity != null) {
                    // 获取到组织树
                    String organizeIdTree = entity.getOrganizeIdTree();
                    if (StringUtil.isNotEmpty(organizeIdTree)) {
                        stringJoiner.add(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeIdTree, "/"));
                    }
                }
            }
            userVO.setGender(dataServiceMap4.get(userEntity.getGender()));
            userVO.setOrganize(stringJoiner.toString());
            list.add(userVO);
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 获取用户列表
     *
     * @return ignore
     */
    @Operation(summary = "获取所有用户列表")
    @GetMapping("/All")
    public ActionResult<ListVO<UserAllVO>> getAllUsers(PaginationUser pagination) {
        List<UserEntity> list = userService.getList(pagination, null, false, false, null, null);
        List<UserAllVO> user = JsonUtil.getJsonToList(list, UserAllVO.class);
        ListVO<UserAllVO> vo = new ListVO<>();
        vo.setList(user);
        return ActionResult.success(vo);
    }

    /**
     * IM通讯获取用户接口
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @Operation(summary = "IM通讯获取用户")
    @GetMapping("/ImUser")
    public ActionResult<PageListVO<ImUserListVo>> getAllImUserUsers(Pagination pagination) {
        List<UserEntity> data = userService.getList(pagination, true);
        List<ImUserListVo> list = new ArrayList<>();
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrganizeName(data.stream().map(t -> t.getOrganizeId()).collect(Collectors.toList()), null, false, null);
        for (UserEntity entity : data) {
            ImUserListVo user = JsonUtil.getJsonToBean(entity, ImUserListVo.class);
            OrganizeEntity organize = orgMaps.get(entity.getOrganizeId());
            user.setDepartment(organize != null ? organize.getFullName() : "");
            user.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
            list.add(user);
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 获取用户下拉框列表
     *
     * @return ignore
     */
    @Operation(summary = "获取用户下拉框列表")
    @GetMapping("/Selector")
    public ActionResult<ListVO<UserSelectorVO>> selector() {
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
        List<OrganizeEntity> organizeData = new ArrayList<>(orgMaps.values());
        List<UserEntity> userData = userService.getList(true);
        List<UserSelectorModel> treeList = JsonUtil.getJsonToList(organizeData, UserSelectorModel.class);
        for (UserSelectorModel entity1 : treeList) {
            if ("department".equals(entity1.getType())) {
                entity1.setIcon("icon-ym icon-ym-tree-department1");
            } else if ("company".equals(entity1.getType())) {
                entity1.setIcon("icon-ym icon-ym-tree-organization3");
            }
        }
        for (UserEntity entity : userData) {
            UserSelectorModel treeModel = new UserSelectorModel();
            treeModel.setId(entity.getId());
            treeModel.setParentId(entity.getOrganizeId());
            treeModel.setFullName(entity.getRealName() + "/" + entity.getAccount());
            treeModel.setType("user");
            treeModel.setIcon("icon-ym icon-ym-tree-user2");
            treeList.add(treeModel);
        }
        List<SumTree<UserSelectorModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<UserSelectorVO> listvo = JsonUtil.getJsonToList(trees, UserSelectorVO.class);
        List<OrganizeEntity> entities = organizeData.stream().filter(
                t -> "-1".equals(t.getParentId())
        ).collect(Collectors.toList());
        Iterator<UserSelectorVO> iterator = listvo.iterator();
        while (iterator.hasNext()) {
            UserSelectorVO userSelectorVO = iterator.next();
            for (OrganizeEntity entity : entities) {
                if (entity.getId().equals(userSelectorVO.getParentId())) {
                    iterator.remove();//使用迭代器的删除方法删除
                }
            }
        }
        ListVO<UserSelectorVO> vo = new ListVO<>();
        vo.setList(listvo);
        return ActionResult.success(vo);
    }

    /**
     * 通过部门、岗位、用户、角色、分组id获取用户列表
     *
     * @param userConditionModel 用户选择模型
     * @return
     */
    @Operation(summary = "通过部门、岗位、用户、角色、分组id获取用户列表")
    @Parameters({
            @Parameter(name = "userConditionModel", description = "用户选择模型", required = true)
    })
    @PostMapping("/UserCondition")
    public ActionResult userCondition(@RequestBody UserConditionModel userConditionModel) {
        List<String> list = new ArrayList<>(16);
        if (userConditionModel.getDepartIds() != null) {
            list.addAll(userConditionModel.getDepartIds());
        }
        if (userConditionModel.getRoleIds() != null) {
            list.addAll(userConditionModel.getRoleIds());
        }
        if (userConditionModel.getPositionIds() != null) {
            list.addAll(userConditionModel.getPositionIds());
        }
        if (userConditionModel.getGroupIds() != null) {
            list.addAll(userConditionModel.getGroupIds());
        }
        if (list.size() == 0) {
            list = userRelationService.getListByObjectType(userConditionModel.getType()).stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
            if (PermissionConst.GROUP.equals(userConditionModel.getType())) {
                List<GroupEntity> groupList = groupService.getListByIds(list, true);
                list = groupList.stream().map(GroupEntity::getId).collect(Collectors.toList());
            }
            if (PermissionConst.ORGANIZE.equals(userConditionModel.getType())) {
                List<OrganizeEntity> orgList = organizeService.getOrgEntityList(list, true);
                list = orgList.stream().map(OrganizeEntity::getId).collect(Collectors.toList());
            }
            if (PermissionConst.ROLE.equals(userConditionModel.getType())) {
                List<RoleEntity> roleList = roleService.getListByIds(list, null, false);
                list = roleList.stream().filter(t -> t.getEnabledMark() == 1).map(RoleEntity::getId).collect(Collectors.toList());
            }
            if (PermissionConst.POSITION.equals(userConditionModel.getType())) {
                List<PositionEntity> positionList = positionService.getPosList(list);
                list = positionList.stream().filter(t -> t.getEnabledMark() == 1).map(PositionEntity::getId).collect(Collectors.toList());
            }
        }
        List<String> collect = userRelationService.getListByObjectIdAll(list).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        if (userConditionModel.getUserIds() != null) {
            collect.addAll(userConditionModel.getUserIds());
        }
        collect = collect.stream().distinct().collect(Collectors.toList());
        List<UserEntity> userName = userService.getUserName(collect, userConditionModel.getPagination());
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(userName, UserIdListVo.class);
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        jsonToList.forEach(t -> {
            t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
            t.setFullName(t.getRealName() + "/" + t.getAccount());
            List<UserRelationEntity> listByUserId = userRelationService.getListByUserId(t.getId(), PermissionConst.ORGANIZE);
            List<String> orgId = listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
            List<OrganizeEntity> organizeName = new ArrayList<>(organizeService.getOrganizeName(orgId, null, false, null).values());
            StringBuilder stringBuilder = new StringBuilder();
            organizeName.forEach(org -> {
                if (StringUtil.isNotEmpty(org.getOrganizeIdTree())) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, org.getOrganizeIdTree(), "/");
                    stringBuilder.append(",");
                    stringBuilder.append(fullNameByOrgIdTree);
                }
            });
            if (stringBuilder.length() > 0) {
                t.setOrganize(stringBuilder.toString().replaceFirst(",", ""));
            }
        });
        PaginationVO paginationVO = JsonUtil.getJsonToBean(userConditionModel.getPagination(), PaginationVO.class);
        return ActionResult.page(jsonToList, paginationVO);
    }

    /**
     * 获取用户下拉框列表
     *
     * @param organizeIdForm 组织id
     * @param pagination     分页模型
     * @return
     */
    @Operation(summary = "获取用户下拉框列表")
    @Parameters({
            @Parameter(name = "organizeId", description = "组织id", required = true),
            @Parameter(name = "pagination", description = "分页模型", required = true)
    })
    @PostMapping("/ImUser/Selector/{organizeId}")
    public ActionResult<?> imUserSelector(@PathVariable("organizeId") String organizeIdForm, @RequestBody Pagination pagination) {
        String organizeId = XSSEscape.escape(organizeIdForm);
        List<UserSelectorVO> jsonToList = new ArrayList<>();
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
        //判断是否搜索关键字
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            //通过关键字查询
            List<UserEntity> list = userService.getList(pagination, false);
            //遍历用户给要返回的值插入值
            for (UserEntity entity : list) {
                UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class);
                vo.setParentId(entity.getOrganizeId());
                vo.setFullName(entity.getRealName() + "/" + entity.getAccount());
                vo.setType("user");
                vo.setIcon("icon-ym icon-ym-tree-user2");
                vo.setHeadIcon(UploaderUtil.uploaderImg(vo.getHeadIcon()));
                List<UserRelationEntity> listByUserId = userRelationService.getListByUserId(entity.getId()).stream().filter(t -> t != null && PermissionConst.ORGANIZE.equals(t.getObjectType())).collect(Collectors.toList());
                StringJoiner stringJoiner = new StringJoiner(",");
                listByUserId.forEach(t -> {
                    OrganizeEntity organizeEntity = orgMaps.get(t.getObjectId());
                    if (organizeEntity != null) {
                        String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                        if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                            stringJoiner.add(fullNameByOrgIdTree);
                        }
                    }
                });
                vo.setOrganize(stringJoiner.toString());
                vo.setHasChildren(false);
                vo.setIsLeaf(true);
                jsonToList.add(vo);
            }
            PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
            return ActionResult.page(jsonToList, jsonToBean);
        }
        //获取所有组织
        List<OrganizeEntity> collect = new ArrayList<>(orgMaps.values());
        //判断时候传入组织id
        //如果传入组织id，则取出对应的子集
        if (!"0".equals(organizeId)) {
            //通过组织查询部门及人员
            //单个组织
            OrganizeEntity organizeEntity = orgMaps.get(organizeId);
            if (organizeEntity != null) {
                //取出组织下的部门
                List<OrganizeEntity> collect1 = collect.stream().filter(t -> t.getParentId().equals(organizeEntity.getId())).collect(Collectors.toList());
                for (OrganizeEntity entitys : collect1) {
                    UserSelectorVO vo = JsonUtil.getJsonToBean(entitys, UserSelectorVO.class);
                    if ("department".equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-department1");
                    } else if ("company".equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, entitys.getOrganizeIdTree(), "/"));
                    // 判断组织下是否有人
                    jsonToList.add(vo);
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                }
                //取出组织下的人员
                List<UserEntity> entityList = userService.getListByOrganizeId(organizeId, null);
                for (UserEntity entity : entityList) {
                    if ("0".equals(String.valueOf(entity.getEnabledMark()))) {
                        continue;
                    }
                    UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class);
                    vo.setParentId(organizeId);
                    vo.setFullName(entity.getRealName() + "/" + entity.getAccount());
                    vo.setType("user");
                    vo.setIcon("icon-ym icon-ym-tree-user2");
                    List<UserRelationEntity> listByUserId = userRelationService.getListByUserId(entity.getId()).stream().filter(t -> t != null && PermissionConst.ORGANIZE.equals(t.getObjectType())).collect(Collectors.toList());
                    StringBuilder stringBuilder = new StringBuilder();
                    listByUserId.forEach(t -> {
                        OrganizeEntity organizeEntity1 = orgMaps.get(t.getObjectId());
                        if (organizeEntity1 != null) {
                            String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity1.getOrganizeIdTree(), "/");
                            if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                                stringBuilder.append("," + fullNameByOrgIdTree);
                            }
                        }
                    });
                    if (stringBuilder.length() > 0) {
                        vo.setOrganize(stringBuilder.toString().replaceFirst(",", ""));
                    }
                    vo.setHeadIcon(UploaderUtil.uploaderImg(vo.getHeadIcon()));
                    vo.setHasChildren(false);
                    vo.setIsLeaf(true);
                    jsonToList.add(vo);
                }
            }
            ListVO<UserSelectorVO> vo = new ListVO<>();
            vo.setList(jsonToList);
            return ActionResult.success(vo);
        }

        //如果没有组织id，则取出所有组织
        jsonToList = JsonUtil.getJsonToList(collect.stream().filter(t -> "-1".equals(t.getParentId())).collect(Collectors.toList()), UserSelectorVO.class);
        //添加图标
        for (UserSelectorVO userSelectorVO : jsonToList) {
            userSelectorVO.setIcon("icon-ym icon-ym-tree-organization3");
            userSelectorVO.setHasChildren(true);
            userSelectorVO.setIsLeaf(false);
            userSelectorVO.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, orgMaps.get(userSelectorVO.getId()).getOrganizeIdTree(), "/"));
        }
        ListVO<UserSelectorVO> vo = new ListVO<>();
        vo.setList(jsonToList);
        return ActionResult.success(vo);
    }

    /**
     * 获取用户下拉框列表
     *
     * @param organizeId 组织id
     * @param page       关键字
     * @return
     */
    @Operation(summary = "获取用户下拉框列表")
    @Parameters({
            @Parameter(name = "organizeId", description = "组织id", required = true),
            @Parameter(name = "page", description = "关键字", required = true)
    })
    @SaCheckPermission("permission.grade")
    @PostMapping("/GetListByAuthorize/{organizeId}")
    public ActionResult<ListVO<UserByRoleVO>> getListByAuthorize(@PathVariable("organizeId") String organizeId, @RequestBody Page page) {
        List<UserByRoleVO> jsonToList = userService.getListByAuthorize(organizeId, page);
        ListVO listVO = new ListVO();
        listVO.setList(jsonToList);
        return ActionResult.success(listVO);
    }

    /**
     * 获取用户信息
     *
     * @param id 用户id
     * @return ignore
     */
    @Operation(summary = "获取用户信息")
    @Parameters({
            @Parameter(name = "id", description = "用户id", required = true)
    })
    @SaCheckPermission("permission.user")
    @GetMapping("/{id}")
    public ActionResult<UserInfoVO> getInfo(@PathVariable("id") String id) throws DataException {
        UserEntity entity = userService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }

        QueryWrapper<UserRelationEntity> roleQuery = new QueryWrapper<>();
        roleQuery.lambda().eq(UserRelationEntity::getUserId, id);
        roleQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ROLE);
        List<String> roleIdList = new ArrayList<>();
        for (UserRelationEntity ure : userRelationService.list(roleQuery)) {
            roleIdList.add(ure.getObjectId());
        }

        entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
        // 得到组织树
        UserInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, UserInfoVO.class);
        vo.setRoleId(String.join(",", roleIdList));


        // 获取组织id数组
        QueryWrapper<UserRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(UserRelationEntity::getUserId, id);
        query.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ORGANIZE);
        List<String> organizeIds = new ArrayList<>();
        userRelationService.list(query).forEach(u -> {
            organizeIds.add(u.getObjectId());
        });

        // 岗位装配
        QueryWrapper<UserRelationEntity> positionQuery = new QueryWrapper<>();
        positionQuery.lambda().eq(UserRelationEntity::getUserId, id);
        positionQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.POSITION);
        String positionIds = "";
        for (UserRelationEntity ure : userRelationService.list(positionQuery)) {
            PositionEntity info = positionService.getInfo(ure.getObjectId());
            if (info != null) {
                positionIds = positionIds + "," + ure.getObjectId();
            }
        }
        if (positionIds.length() > 0) {
            vo.setPositionId(positionIds.substring(1));
        } else {
            vo.setPositionId(null);
        }
        // 设置分组id
        List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(entity.getId(), PermissionConst.GROUP);
        StringBuilder groupId = new StringBuilder();
        listByObjectType.stream().forEach(t -> groupId.append("," + t.getObjectId()));
        if (groupId.length() > 0) {
            vo.setGroupId(groupId.toString().replaceFirst(",", ""));
        }
        vo.setOrganizeIdTree(PermissionUtil.getOrgIdsTree(organizeIds, 1, organizeService));
        return ActionResult.success(vo);
    }

    /**
     * 新建用户
     *
     * @param userCrForm 表单参数
     */
    @UserPermission
    @Operation(summary = "新建用户")
    @Parameters({
            @Parameter(name = "userCrForm", description = "表单参数", required = true)
    })
    @SaCheckPermission("permission.user")
    @PostMapping
    public ActionResult<String> create(@RequestBody @Valid UserCrForm userCrForm) throws Exception {
        UserEntity entity = JsonUtil.getJsonToBean(userCrForm, UserEntity.class);
        if (userService.isExistByAccount(userCrForm.getAccount())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (StringUtil.isEmpty(entity.getGender())) {
            return ActionResult.fail(MsgCode.PS020.get());
        }
        userService.create(entity);
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            try {
                //添加用户之后判断是否需要同步到企业微信
                synThirdQyService.createUserSysToQy(false, entity, "");
                //添加用户之后判断是否需要同步到钉钉
                synThirdDingTalkService.createUserSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("添加用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        String catchKey = cacheKeyUtil.getAllUser();
        if (redisUtil.exists(catchKey)) {
            redisUtil.remove(catchKey);
        }
        BaseSystemInfo sysInfo = sysconfigApi.getSysInfo();
        entity.setPassword(sysInfo.getNewUserDefaultPassword());
        PullUserUtil.syncUser(entity, "create", UserProvider.getUser().getTenantId());
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改用户
     *
     * @param userUpForm 表单参数
     * @param id         主键值
     */
    @UserPermission
    @Operation(summary = "修改用户")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true),
            @Parameter(name = "userUpForm", description = "表单参数", required = true)
    })
    @SaCheckPermission("permission.user")
    @PutMapping("/{id}")
    public ActionResult<String> update(@PathVariable("id") String id, @RequestBody @Valid UserUpForm userUpForm) throws Exception {
        UserEntity entity = JsonUtil.getJsonToBean(userUpForm, UserEntity.class);
        if (StringUtil.isEmpty(entity.getGender())) {
            return ActionResult.fail(MsgCode.PS020.get());
        }
        //将禁用的id加进数据
        UserEntity originUser = userService.getInfo(id);
        UserInfoVO infoVO = this.getInfo(id).getData();
        // 如果是管理员的话
        if ("1".equals(String.valueOf(originUser.getIsAdministrator()))) {
            UserInfo operatorUser = UserProvider.getUser();
            // 管理员可以修改自己，但是无法修改其他管理员
            if (operatorUser.getIsAdministrator()) {
                if (originUser.getEnabledMark() != 0 && entity.getEnabledMark() == 0) {
                    return ActionResult.fail(MsgCode.PS021.get());
                }
                if (!ADMIN_KEY.equals(userService.getInfo(operatorUser.getUserId()).getAccount())) {
                    if (!operatorUser.getUserId().equals(id)) {
                        return ActionResult.fail(MsgCode.PS022.get());
                    }
                }
            } else {
                return ActionResult.fail(MsgCode.PS023.get());
            }
        }
        //直属主管不能是自己
        if (id.equals(userUpForm.getManagerId())) {
            return ActionResult.fail(MsgCode.PS024.get());
        }
        if (!originUser.getAccount().equals(entity.getAccount())) {
            if (userService.isExistByAccount(entity.getAccount())) {
                return ActionResult.fail(MsgCode.EXIST001.get());
            }
        }
        // 验证是否有十级,验证是否是自己的下属
        boolean subordinate = userService.isSubordinate(id, userUpForm.getManagerId());
        if (subordinate) {
            return ActionResult.fail(MsgCode.PS025.get());
        }
        // 如果账号被锁定
        if ("2".equals(String.valueOf(entity.getEnabledMark()))) {
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
        }
        // 如果原来是锁定，现在不锁定，则置空错误次数
        if (originUser.getEnabledMark() == 2 && entity.getEnabledMark() == 1) {
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
        }
        boolean flag = userService.update(id, entity);
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            try {
                //修改用户之后判断是否需要同步到企业微信
                synThirdQyService.updateUserSysToQy(false, entity, "");
                //修改用户之后判断是否需要同步到钉钉
                synThirdDingTalkService.updateUserSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("修改用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        if (!flag) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        // 删除在线的用户
//        if (needSignOut(id, userUpForm, infoVO)) {
            userService.delCurUser(MsgCode.PS030.get(), ImmutableList.of(id),3);
//        }
        PullUserUtil.syncUser(entity, "update", UserProvider.getUser().getTenantId());
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 修改用户【组织】【岗位】【角色】时
     * 需要退出登录的判断
     *
     * @param id
     * @param userUpForm
     * @param infoVO
     * @return
     */
    private boolean needSignOut(String id, UserUpForm userUpForm, UserInfoVO infoVO) {
        StringJoiner organizeIds = new StringJoiner(",");
        List<LinkedList<String>> organizeIdTree = infoVO.getOrganizeIdTree();
        for (LinkedList<String> ids : organizeIdTree) {
            if (ids.size() > 0) {
                organizeIds.add(ids.get(ids.size() - 1));
            }
        }
        return !Objects.equals(organizeIds.toString(), userUpForm.getOrganizeId()) || !Objects.equals(infoVO.getPositionId(), userUpForm.getPositionId())
                || !Objects.equals(infoVO.getRoleId(), userUpForm.getRoleId());
    }

    /**
     * 删除用户
     *
     * @param id 主键值
     * @return ignore
     */
    @UserPermission
    @Operation(summary = "删除用户")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.user")
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String id) {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            if ("1".equals(String.valueOf(entity.getIsAdministrator()))) {
                return ActionResult.fail(MsgCode.PS026.get());
            }
            //判断是否是部门主管
            if (organizeService.getList(false).stream().filter(t -> id.equals(t.getManagerId())).collect(Collectors.toList()).size() > 0) {
                return ActionResult.fail(MsgCode.PS027.get());
            }
            // 有下属不允许删除
//            if (userService.getListByManagerId(id, null).size() > 0) {
//                return ActionResult.fail(MsgCode.PS028.get());
//            }
            String tenantId = StringUtil.isEmpty(UserProvider.getUser().getTenantId()) ? "" : UserProvider.getUser().getTenantId();
            String catchKey = tenantId + "allUser";
            if (redisUtil.exists(catchKey)) {
                redisUtil.remove(catchKey);
            }
            userService.delete(entity);
            ThreadPoolExecutorUtil.getExecutor().execute(() -> {
                try {
                    //删除用户之后判断是否需要同步到企业微信
                    synThirdQyService.deleteUserSysToQy(false, id, "");
                    //删除用户之后判断是否需要同步到钉钉
                    synThirdDingTalkService.deleteUserSysToDing(false, id, "");
                } catch (Exception e) {
                    log.error("删除用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                }
            });
            userService.delCurUser(MsgCode.PS030.get(), ImmutableList.of(entity.getId()),null);
            PullUserUtil.syncUser(entity, "delete", UserProvider.getUser().getTenantId());
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }


    /**
     * 修改用户密码
     *
     * @param id                    主键
     * @param userResetPasswordForm 修改密码模型
     * @return ignore
     */
    @UserPermission
    @Operation(summary = "修改用户密码")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true),
            @Parameter(name = "userResetPasswordForm", description = "修改密码模型", required = true)
    })
    @SaCheckPermission("permission.user")
    @PostMapping("/{id}/Actions/ResetPassword")
    public ActionResult<String> modifyPassword(@PathVariable("id") String id, @RequestBody @Valid UserResetPasswordForm userResetPasswordForm) {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            entity.setPassword(userResetPasswordForm.getUserPassword());
            userService.updatePassword(entity);
            userService.delCurUser(MsgCode.PS010.get(), ImmutableList.of(entity.getId()),null);
            entity.setPassword(userResetPasswordForm.getUserPassword());
            PullUserUtil.syncUser(entity, "modifyPassword", UserProvider.getUser().getTenantId());
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success(MsgCode.FA001.get());
    }

    /**
     * 更新用户状态
     *
     * @param id 主键值
     * @return ignore
     */
    @Operation(summary = "更新用户状态")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.user")
    @PutMapping("/{id}/Actions/State")
    public ActionResult<String> disable(@PathVariable("id") String id) throws Exception {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            if ("1".equals(String.valueOf(entity.getIsAdministrator()))) {
                return ActionResult.fail(MsgCode.PS029.get());
            }
            if (entity.getEnabledMark() != null) {
                if ("1".equals(String.valueOf(entity.getEnabledMark()))) {
                    entity.setEnabledMark(0);
                    userService.delCurUser(null, ImmutableList.of(entity.getId()),null);
                    userService.update(id, entity);
                } else {
                    entity.setEnabledMark(1);
                    userService.update(id, entity);
                }
            } else {
                entity.setEnabledMark(1);
                userService.update(id, entity);
            }
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success(MsgCode.FA001.get());
    }

    /**
     * 解除锁定
     *
     * @param id 主键值
     * @return ignore
     */
    @Operation(summary = "解除锁定")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.user")
    @PutMapping("/{id}/Actions/unlock")
    public ActionResult<String> unlock(@PathVariable("id") String id) throws Exception {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            // 状态变成正常
            entity.setEnabledMark(1);
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
            entity.setId(id);
            userService.updateById(entity);
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success(MsgCode.FA001.get());
    }

    /**
     * 获取用户基本信息
     *
     * @param userIdModel 用户id
     * @return ignore
     */
    @Operation(summary = "获取用户基本信息")
    @Parameters({
            @Parameter(name = "userIdModel", description = "用户id", required = true)
    })
    @PostMapping("/getUserList")
    public ActionResult<ListVO<UserIdListVo>> getUserList(@RequestBody UserIdModel userIdModel) {
        List<UserEntity> userName = userService.getUserName(userIdModel.getIds(), true);
        List<UserIdListVo> list = JsonUtil.getJsonToList(userName, UserIdListVo.class);
        List<UserRelationEntity> listByUserIds = userRelationService.getRelationByUserIds(list.stream().map(UserIdListVo::getId).collect(Collectors.toList()));
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        for (UserIdListVo entity : list) {
            if (entity == null) {
                break;
            }
            entity.setFullName(entity.getRealName() + "/" + entity.getAccount());
            List<UserRelationEntity> listByUserId = listByUserIds.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList());
            StringBuilder stringBuilder = new StringBuilder();
            List<OrganizeEntity> orgEntityList = organizeService.getOrgEntityList(listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()), false);
            listByUserId.forEach(t -> {
                OrganizeEntity organizeEntity = orgEntityList.stream().filter(org -> org.getId().equals(t.getObjectId())).findFirst().orElse(null);
                if (organizeEntity != null) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                    if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                        stringBuilder.append("," + fullNameByOrgIdTree);
                    }
                }
            });
            if (stringBuilder.length() > 0) {
                entity.setOrganize(stringBuilder.toString().replaceFirst(",", ""));
            }
            entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
        }
        ListVO<UserIdListVo> listVO = new ListVO<>();
        listVO.setList(list);
        return ActionResult.success(listVO);
    }

    /**
     * 获取选中组织、岗位、角色、用户基本信息
     *
     * @param userIdModel 用户id
     * @return ignore
     */
    @Operation(summary = "获取选中组织、岗位、角色、用户基本信息")
    @Parameters({
            @Parameter(name = "userIdModel", description = "用户id", required = true)
    })
    @PostMapping("/getSelectedList")
    public ActionResult<ListVO<UserIdListVo>> getSelectedList(@RequestBody UserIdModel userIdModel) {
        List<String> ids = userIdModel.getIds();
        List<UserIdListVo> list = userService.selectedByIds(ids);
        ListVO<UserIdListVo> listVO = new ListVO<>();
        listVO.setList(list);
        return ActionResult.success(listVO);
    }


    /**
     * 获取用户基本信息
     *
     * @param userIdModel 用户id
     * @return ignore
     */
    @Operation(summary = "获取选中用户基本信息")
    @Parameters({
            @Parameter(name = "userIdModel", description = "用户id", required = true)
    })
    @PostMapping("/getSelectedUserList")
    public ActionResult<PageListVO<UserIdListVo>> getSelectedUserList(@RequestBody UserIdModelByPage userIdModel) {
        List<UserIdListVo> jsonToList = userService.getObjList(userIdModel.getIds(), userIdModel.getPagination(), null);
        PaginationVO paginationVO = JsonUtil.getJsonToBean(userIdModel.getPagination(), PaginationVO.class);
        return ActionResult.page(jsonToList, paginationVO);
    }

    /**
     * 获取组织下的人员
     *
     * @param page 页面信息
     * @return ignore
     */
    @Operation(summary = "获取组织下的人员")
    @GetMapping("/getOrganization")
    public ActionResult<List<UserIdListVo>> getOrganization(PageUser page) {
        String departmentId = page.getOrganizeId();
        // 判断是否获取当前组织下的人员
        if ("0".equals(departmentId)) {
            departmentId = UserProvider.getUser().getDepartmentId();
            // 为空则取组织id
            if (StringUtil.isEmpty(departmentId)) {
                departmentId = UserProvider.getUser().getOrganizeId();
            }
        }
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
        List<UserEntity> list = userService.getListByOrganizeId(departmentId, page.getKeyword());
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(PermissionConst.ORGANIZE);
        jsonToList.forEach(t -> {
            t.setRealName(t.getRealName() + "/" + t.getAccount());
            t.setFullName(t.getRealName());
            List<String> collect = listByObjectType.stream().filter(userRelationEntity -> userRelationEntity.getUserId().equals(t.getId())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
            StringJoiner stringJoiner = new StringJoiner(",");
            collect.forEach(objectId -> {
                OrganizeEntity organizeEntity = orgMaps.get(objectId);
                if (organizeEntity != null) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                    if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                        stringJoiner.add(fullNameByOrgIdTree);
                    }
                }
            });
            t.setOrganize(stringJoiner.toString());
            t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
        });
        return ActionResult.success(jsonToList);
    }

    /**
     * 获取人员，委托选人接口
     *
     * @param type       范围类型
     * @param pagination 参数
     */
    @Operation(summary = "获取人员")
    @GetMapping("/ReceiveUserList")
    public ActionResult receiveUserList(@RequestParam("type") Integer type, Pagination pagination) {
        UserInfo userInfo = UserProvider.getUser();
        UserEntity user = userService.getInfo(userInfo.getUserId());
        List<String> userId = new ArrayList<>();
        switch (ExtraRuleEnum.getByCode(type)) {
            case organize:
                // 委托范围为同一部门，但委托人的所属组织是公司，无需选人
                OrganizeEntity organize = organizeService.getInfo(user.getOrganizeId());
                if (null != organize && Objects.equals(organize.getCategory(), PermissionConst.DEPARTMENT)) {
                    List<String> orgIds = ImmutableList.of(user.getOrganizeId());
                    userId.addAll(userRelationService.getListByObjectIdAll(orgIds).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
                }
                break;
            case position:
                List<String> positionIds = ImmutableList.of(user.getPositionId());
                userId.addAll(userRelationService.getListByObjectIdAll(positionIds).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
                break;
            case department:
                List<String> organizeIds = organizeService.getDepartmentAll(user.getOrganizeId()).stream().map(OrganizeEntity::getId).collect(Collectors.toList());
                userId.addAll(userRelationService.getListByObjectIdAll(organizeIds).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
                break;
        }
        List<UserEntity> list = userService.getUserName(userId, pagination);
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, true, null);
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(PermissionConst.ORGANIZE);
        jsonToList.forEach(t -> {
            t.setRealName(t.getRealName() + "/" + t.getAccount());
            t.setFullName(t.getRealName());
            List<String> collect = listByObjectType.stream().filter(userRelationEntity -> userRelationEntity.getUserId().equals(t.getId())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
            StringJoiner stringJoiner = new StringJoiner(",");
            collect.forEach(objectId -> {
                OrganizeEntity organizeEntity = orgMaps.get(objectId);
                if (organizeEntity != null) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                    if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                        stringJoiner.add(fullNameByOrgIdTree);
                    }
                }
            });
            t.setOrganize(stringJoiner.toString());
            t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
        });
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(jsonToList, paginationVO);
    }

    /**
     * 获取岗位人员
     *
     * @param page 页面信息
     * @return ignore
     */
    @Operation(summary = "获取岗位人员")
    @GetMapping("/GetUsersByPositionId")
    public ActionResult<List<UserByRoleVO>> getUsersByPositionId(UsersByPositionModel page) {
        List<UserByRoleVO> list = new ArrayList<>(1);
        String keyword = page.getKeyword();
        // 岗位id
        String positionId = page.getPositionId();
        // 得到关联的组织id
        PositionEntity positionEntity = positionService.getInfo(positionId);
//        List<OrganizeRelationEntity> relationListByObjectIdAndType = organizeRelationService.getRelationListByObjectIdAndType(PermissionConst.POSITION, positionId);
        if (positionEntity != null) {
            UserByRoleVO vo = new UserByRoleVO();
            String organizeId = positionEntity.getOrganizeId();
            // 得到组织信息
            OrganizeEntity organizeEntity = organizeService.getInfo(organizeId);
            if (Objects.nonNull(organizeEntity)) {
                vo.setId(organizeEntity.getId());
                vo.setType(organizeEntity.getCategory());
                if ("department".equals(organizeEntity.getCategory())) {
                    vo.setIcon("icon-ym icon-ym-tree-department1");
                } else {
                    vo.setIcon("icon-ym icon-ym-tree-organization3");
                }
                vo.setEnabledMark(organizeEntity.getEnabledMark());
                Map<String, String> orgIdNameMaps = organizeService.getInfoList();
                // 组装组织名称
                String orgName = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                vo.setFullName(orgName);
                // 赋予子集
                List<UserByRoleVO> userByRoleVOS = new ArrayList<>(16);
                List<UserEntity> lists = userService.getListByOrganizeId(organizeEntity.getId(), keyword);
                if (lists.size() > 0) {
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    lists.stream().forEach(t -> {
                        UserByRoleVO userByRoleVO = new UserByRoleVO();
                        userByRoleVO.setParentId(organizeEntity.getId());
                        userByRoleVO.setId(t.getId());
                        userByRoleVO.setFullName(t.getRealName() + "/" + t.getAccount());
                        userByRoleVO.setEnabledMark(t.getEnabledMark());
                        userByRoleVO.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
                        userByRoleVO.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/"));
                        userByRoleVO.setIsLeaf(true);
                        userByRoleVO.setHasChildren(false);
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-user2");
                        userByRoleVO.setType("user");
                        userByRoleVOS.add(userByRoleVO);
                    });
                    vo.setChildren(userByRoleVOS);
                } else {
                    vo.setHasChildren(false);
                    vo.setIsLeaf(true);
                    vo.setChildren(new ArrayList<>());
                }
                list.add(vo);
            }
        }
        return ActionResult.success(list);
    }

    /**
     * 角色成员弹窗
     *
     * @param model 页面信息
     * @return ignore
     */
    @Operation(summary = "角色成员弹窗")
    @SaCheckPermission("permission.role")
    @GetMapping("/GetUsersByRoleOrgId")
    public ActionResult<List<UserByRoleVO>> getUsersByRoleOrgId(UserByRoleModel model) {
        List<UserByRoleVO> jsonToList = new ArrayList<>(16);
        // 得到组织关系
        List<OrganizeRelationEntity> relationListByRoleId = organizeRelationService.getRelationListByRoleId(model.getRoleId());
        // 得到组织信息
        List<OrganizeEntity> orgEntityList = organizeService.getOrgEntityList(relationListByRoleId.stream().map(OrganizeRelationEntity::getOrganizeId).collect(Collectors.toList()), true);
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        //判断是否搜索关键字
        if (StringUtil.isNotEmpty(model.getKeyword())) {
            //通过关键字查询
            List<UserEntity> list = userService.getList(orgEntityList.stream().map(OrganizeEntity::getId).collect(Collectors.toList()), model.getKeyword());
            List<UserRelationEntity> listByUserIds = userRelationService.getRelationByUserIds(list.stream().map(UserEntity::getId).collect(Collectors.toList()));
            //遍历用户给要返回的值插入值
            for (UserEntity entity : list) {
                UserByRoleVO vo = new UserByRoleVO();
                vo.setId(entity.getId());
                vo.setFullName(entity.getRealName() + "/" + entity.getAccount());
                vo.setEnabledMark(entity.getEnabledMark());
                vo.setIsLeaf(true);
                vo.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
                List<UserRelationEntity> listByUserId = listByUserIds.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList());
                StringBuilder stringBuilder = new StringBuilder();
                List<OrganizeEntity> orgEntityLists = organizeService.getOrgEntityList(listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()), false);
                listByUserId.forEach(t -> {
                    OrganizeEntity orgEntity = orgEntityLists.stream().filter(org -> org.getId().equals(t.getObjectId())).findFirst().orElse(null);
                    if (orgEntity != null) {
                        String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, orgEntity.getOrganizeIdTree(), "/");
                        if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                            stringBuilder.append("," + fullNameByOrgIdTree);
                        }
                    }
                });
                if (stringBuilder.length() > 0) {
                    vo.setOrganize(stringBuilder.toString().replaceFirst(",", ""));
                }
                vo.setHasChildren(false);
                vo.setIcon("icon-ym icon-ym-tree-user2");
                vo.setType("user");
                jsonToList.add(vo);
            }
            return ActionResult.success(jsonToList);
        }
        //获取所有组织
        List<OrganizeEntity> collect = organizeService.getList(false).stream().filter(t -> t.getEnabledMark() == 1).collect(Collectors.toList());
        //判断时候传入组织id
        //如果传入组织id，则取出对应的子集
        if (!"0".equals(model.getOrganizeId())) {
            //通过组织查询部门及人员
            //单个组织
            List<OrganizeEntity> list = collect.stream().filter(t -> model.getOrganizeId().equals(t.getId())).collect(Collectors.toList());
            if (list.size() > 0) {
                //获取组织信息
                OrganizeEntity organizeEntity = list.get(0);
                //取出组织下的部门
                List<OrganizeEntity> collect1 = collect.stream().filter(t -> t.getParentId().equals(organizeEntity.getId())).collect(Collectors.toList());
                // 判断组织关系中是否有子部门id
                List<OrganizeEntity> organizeEntities = new ArrayList<>();
                for (OrganizeEntity entity : collect1) {
                    List<OrganizeRelationEntity> collect2 = relationListByRoleId.stream().filter(t -> entity.getId().equals(t.getOrganizeId())).collect(Collectors.toList());
                    collect2.stream().forEach(t -> {
                        if (StringUtil.isNotEmpty(t.getOrganizeId())) {
                            organizeEntities.add(organizeService.getInfo(t.getOrganizeId()));
                        }
                    });
                }
                // 其他不是子集的直接显示
                List<OrganizeRelationEntity> collect2 = relationListByRoleId.stream()
                        .filter(item -> !organizeEntities.stream().map(e -> e.getId())
                                .collect(Collectors.toList()).contains(item.getOrganizeId()))
                        .collect(Collectors.toList());
                // 移除掉上级不是同一个的
                List<OrganizeRelationEntity> collect3 = collect2.stream().filter(t -> !organizeService.getInfo(t.getOrganizeId()).getOrganizeIdTree().contains(model.getOrganizeId())).collect(Collectors.toList());
                collect2.removeAll(collect3);
                List<OrganizeRelationEntity> collect4 = collect2.stream().filter(t -> !t.getOrganizeId().equals(model.getOrganizeId())).collect(Collectors.toList());
                List<OrganizeEntity> collect5 = collect.stream().filter(x -> collect4.stream().map(OrganizeRelationEntity::getOrganizeId).collect(Collectors.toList()).contains(x.getId())).collect(Collectors.toList());
                List<OrganizeEntity> organizeEntities1 = new ArrayList<>(collect5);
                // 不是子集的对比子集的
                for (OrganizeEntity entity : collect5) {
                    for (OrganizeEntity organizeEntity1 : organizeEntities) {
                        if (entity.getOrganizeIdTree().contains(organizeEntity1.getId())) {
                            organizeEntities1.remove(entity);
                        }
                    }
                }

                //取出组织下的人员
                List<UserEntity> entityList = userService.getListByOrganizeId(model.getOrganizeId(), null);
                List<UserRelationEntity> listByUserIds = userRelationService.getRelationByUserIds(entityList.stream().map(UserEntity::getId).collect(Collectors.toList()));
                for (UserEntity entity : entityList) {
                    UserByRoleVO vo = new UserByRoleVO();
                    vo.setId(entity.getId());
                    vo.setFullName(entity.getRealName() + "/" + entity.getAccount());
                    vo.setEnabledMark(entity.getEnabledMark());
                    vo.setIsLeaf(true);
                    vo.setHasChildren(false);
                    vo.setIcon("icon-ym icon-ym-tree-user2");
                    vo.setType("user");
                    vo.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
                    List<UserRelationEntity> listByUserId = listByUserIds.stream().filter(t -> t.getUserId().equals(entity.getId())).collect(Collectors.toList());
                    StringBuilder stringBuilder = new StringBuilder();
                    List<OrganizeEntity> orgEntityLists = organizeService.getOrgEntityList(listByUserId.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList()), false);
                    listByUserId.forEach(t -> {
                        OrganizeEntity orgEntity = orgEntityLists.stream().filter(org -> org.getId().equals(t.getObjectId())).findFirst().orElse(null);
                        if (orgEntity != null) {
                            String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, orgEntity.getOrganizeIdTree(), "/");
                            if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                                stringBuilder.append("," + fullNameByOrgIdTree);
                            }
                        }
                    });
                    if (stringBuilder.length() > 0) {
                        vo.setOrganize(stringBuilder.toString().replaceFirst(",", ""));
                    }
                    jsonToList.add(vo);
                }
                // 处理子集断层
                List<OrganizeEntity> organizeEntities2 = new ArrayList<>(collect5);
                for (OrganizeEntity entity : organizeEntities2) {
                    List<OrganizeEntity> collect6 = organizeEntities2.stream().filter(t -> !entity.getId().equals(t.getId()) && t.getOrganizeIdTree().contains(entity.getOrganizeIdTree())).collect(Collectors.toList());
                    organizeEntities1.removeAll(collect6);
                }
                for (OrganizeEntity entity : organizeEntities1) {
                    StringBuffer stringBuffer = new StringBuffer();
                    String[] split = entity.getOrganizeIdTree().split(",");
                    List<String> list1 = Arrays.asList(split);
                    List<String> list2 = new ArrayList<>(list1);
                    int indexOf = list2.indexOf(model.getOrganizeId());
                    while (indexOf >= 0) {
                        list2.remove(indexOf);
                        indexOf--;
                    }
                    StringBuffer organizeIdTree = new StringBuffer();
                    for (String parentId : list2) {
                        OrganizeEntity organizes = organizeService.getInfo(parentId);
                        if (Objects.nonNull(organizes) && StringUtil.isNotEmpty(organizes.getFullName())) {
                            organizeIdTree.append("/" + organizes.getFullName());
                        }
                    }
                    String toString = organizeIdTree.toString();
                    if (StringUtil.isNotEmpty(toString)) {
                        String organizeId = toString.replaceFirst("/", "");
                        stringBuffer.append("," + organizeId);
                    }
                    UserByRoleVO userByRoleVO = new UserByRoleVO();
                    userByRoleVO.setId(entity.getId());
                    userByRoleVO.setType(entity.getCategory());
                    userByRoleVO.setFullName(stringBuffer.toString().replace(",", ""));
                    if ("department".equals(entity.getCategory())) {
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-department1");
                    } else {
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    userByRoleVO.setHasChildren(true);
                    userByRoleVO.setIsLeaf(false);
                    userByRoleVO.setEnabledMark(entity.getEnabledMark());
                    jsonToList.add(userByRoleVO);
                }
                for (OrganizeEntity entitys : organizeEntities) {
                    UserByRoleVO vo = new UserByRoleVO();
                    vo.setId(entitys.getId());
                    vo.setType(entitys.getCategory());
                    vo.setFullName(entitys.getFullName());
                    if ("department".equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-department1");
                    } else {
                        vo.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    vo.setEnabledMark(entitys.getEnabledMark());
                    jsonToList.add(vo);
                }
            }
            return ActionResult.success(jsonToList);
        }

        // 判断是否有父级
        Set<OrganizeEntity> set = new HashSet<>(16);
        for (OrganizeEntity entity : orgEntityList) {
            List<OrganizeEntity> collect1 = orgEntityList.stream().filter(t -> !entity.getId().equals(t.getId()) && entity.getOrganizeIdTree().contains(t.getOrganizeIdTree())).collect(Collectors.toList());
            set.addAll(collect1);
        }
        List<OrganizeEntity> list = new ArrayList<>(set);
        // 从list中一处已经有的
        List<OrganizeEntity> list1 = new ArrayList<>(list);
        for (OrganizeEntity organizeEntity : list) {
            List<OrganizeEntity> collect1 = list.stream().filter(t -> !organizeEntity.getId().equals(t.getId()) && t.getOrganizeIdTree().contains(organizeEntity.getId())).collect(Collectors.toList());
            list1.removeAll(collect1);
        }
        list = list1;
        // 纯断层的
        List<OrganizeEntity> list2 = new ArrayList<>(orgEntityList);
        for (OrganizeEntity organizeEntity : orgEntityList) {
            if (list.stream().filter(t -> organizeEntity.getOrganizeIdTree().contains(t.getId())).count() > 0) {
                list2.remove(organizeEntity);
            }
        }
        list.addAll(list2);
        for (OrganizeEntity organizeEntity : list) {
            if (organizeEntity != null && organizeEntity.getEnabledMark() == 1) {
                UserByRoleVO userByRoleVO = new UserByRoleVO();
                userByRoleVO.setId(organizeEntity.getId());
                userByRoleVO.setType(organizeEntity.getCategory());
                String orgName = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                userByRoleVO.setFullName(orgName);
                if ("department".equals(organizeEntity.getCategory())) {
                    userByRoleVO.setIcon("icon-ym icon-ym-tree-department1");
                } else {
                    userByRoleVO.setIcon("icon-ym icon-ym-tree-organization3");
                }
                userByRoleVO.setHasChildren(true);
                userByRoleVO.setIsLeaf(false);
                userByRoleVO.setEnabledMark(organizeEntity.getEnabledMark());
                jsonToList.add(userByRoleVO);
            }
        }
        return ActionResult.success(jsonToList);
    }

    /**
     * 获取我的下属(不取子集)
     *
     * @param page 页面信息
     * @return ignore
     */
    @Operation(summary = "获取我的下属(不取子集)")
    @Parameters({
            @Parameter(name = "page", description = "关键字", required = true)
    })
    @PostMapping("/getSubordinates")
    public ActionResult<List<UserIdListVo>> getSubordinates(@RequestBody Page page) {
        Map<String, OrganizeEntity> orgMaps = organizeService.getOrgMaps(null, false, null);
        List<UserEntity> list = userService.getListByManagerId(UserProvider.getUser().getUserId(), page.getKeyword());
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        jsonToList.forEach(t -> {
            t.setRealName(t.getRealName() + "/" + t.getAccount());
            t.setFullName(t.getRealName());
            List<UserRelationEntity> listByUserId = userRelationService.getListByUserId(t.getId()).stream().filter(ur -> PermissionConst.ORGANIZE.equals(ur.getObjectType())).collect(Collectors.toList());
            StringJoiner stringJoiner = new StringJoiner(",");
            listByUserId.forEach(tt -> {
                OrganizeEntity organizeEntity = orgMaps.get(tt.getObjectId());
                if (organizeEntity != null) {
                    String fullNameByOrgIdTree = organizeService.getFullNameByOrgIdTree(orgIdNameMaps, organizeEntity.getOrganizeIdTree(), "/");
                    if (StringUtil.isNotEmpty(fullNameByOrgIdTree)) {
                        stringJoiner.add(fullNameByOrgIdTree);
                    }
                }
            });
            t.setOrganize(stringJoiner.toString());
            t.setHeadIcon(UploaderUtil.uploaderImg(t.getHeadIcon()));
        });
        return ActionResult.success(jsonToList);
    }

    /**
     * 根据角色ID获取所属组织的所有成员
     *
     * @param pagination 分页模型
     * @return
     */
    @Operation(summary = "根据角色ID获取所有成员")
    @SaCheckPermission("permission.role")
    @GetMapping("/getUsersByRoleId")
    public ActionResult getUsersByRoleId(PaginationUser pagination) {
        List<UserEntity> userList = new ArrayList<>();
        if (roleService.getInfo(pagination.getRoleId()).getGlobalMark() == 1) {
            userList.addAll(userService.getList(pagination, null, false, false, null, null));
        } else {
            // 根据roleId获取所有组织
            userService.getListByRoleId(pagination.getRoleId()).forEach(u -> {
                userList.add(userService.getInfo(u.getId()));
            });
        }
        // 去重
        List<UserEntity> afterUserList = userList.stream().distinct().collect(Collectors.toList());
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            afterUserList = afterUserList.stream().filter(t -> t.getRealName().contains(pagination.getKeyword()) || t.getAccount().contains(pagination.getKeyword())).collect(Collectors.toList());
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(afterUserList, paginationVO);
    }

    /**
     * 获取默认当前值用户ID
     *
     * @param userConditionModel 参数
     * @return 执行结构
     * @throws DataException ignore
     */
    @Operation(summary = "获取默认当前值用户ID")
    @Parameters({
            @Parameter(name = "userConditionModel", description = "参数", required = true)
    })
    @PostMapping("/getDefaultCurrentValueUserId")
    public ActionResult<?> getDefaultCurrentValueUserId(@RequestBody UserConditionModel userConditionModel) throws DataException {
        String userId = userService.getDefaultCurrentValueUserId(userConditionModel);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("userId", userId);
        return ActionResult.success(MsgCode.SU022.get(), dataMap);
    }

    /**
     * 工作交接
     *
     * @param workHandoverModel 模型
     * @return 执行结构
     */
    @Operation(summary = "工作交接")
    @SaCheckPermission("permission.user")
    @Parameters({
            @Parameter(name = "workHandoverModel", description = "模型", required = true)
    })
    @PostMapping("/workHandover")
    public ActionResult<?> workHandover(@RequestBody @Valid WorkHandoverModel workHandoverModel) {
        // 开始交接就禁用用户
        UserEntity entity = userService.getInfo(workHandoverModel.getFromId());
        UserEntity entitys = userService.getInfo(workHandoverModel.getToId());
        if (entity == null || entitys == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        if (workHandoverModel.getFromId().equals(workHandoverModel.getToId())) {
            return ActionResult.fail(MsgCode.PS035.get());
        }
        if(ADMIN_KEY.equals(entitys.getAccount())){
            return ActionResult.fail(MsgCode.PS034.get());
        }
        try {
            boolean flag = templateApi.flowWork(workHandoverModel);
            if (!flag) {
                return ActionResult.fail(MsgCode.FA101.get());
            }
            permissionGroupService.updateByUser(workHandoverModel.getFromId(), workHandoverModel.getToId(), workHandoverModel.getPermissionList());
            entity.setHandoverMark(1);
            return ActionResult.success(MsgCode.PS033.get());
        } finally {
            userService.updateById(entity);
        }
    }

    /**
     * 获取用户工作详情
     *
     * @return 执行结构
     */
    @Operation(summary = "获取用户工作详情")
    @SaCheckPermission("permission.user")
    @Parameters({
            @Parameter(name = "userId", description = "主键", required = true)
    })
    @GetMapping("/getWorkByUser")
    public ActionResult<FlowWorkListVO> getWorkByUser(@RequestParam("fromId") String fromId) {
        FlowWorkListVO flowWorkListVO = templateApi.flowWork(fromId);
        if (flowWorkListVO == null) {
            log.error("用户：" + UserProvider.getLoginUserId() + "，待办事宜及负责流程获取失败");
            flowWorkListVO = new FlowWorkListVO();
        }
        List<PermissionGroupEntity> permissionGroupByUserId = permissionGroupService.getPermissionGroupAllByUserId(fromId);
        List<FlowWorkModel> jsonToList = JsonUtil.getJsonToList(permissionGroupByUserId, FlowWorkModel.class);
        jsonToList.forEach(t -> t.setIcon("icon-ym icon-ym-authGroup"));
        flowWorkListVO.setPermission(jsonToList);
        return ActionResult.success(flowWorkListVO);
    }


    // ----------------------------- 多租户调用

    /**
     * 重置管理员密码
     *
     * @param userResetPasswordForm 修改密码模型
     * @return ignore
     */
    @UserPermission
    @Operation(summary = "重置管理员密码")
    @Parameters({
            @Parameter(name = "userResetPasswordForm", description = "修改密码模型", required = true)
    })
    @PutMapping("/Tenant/ResetPassword")
    @NoDataSourceBind
    public ActionResult<String> resetPassword(@RequestBody @Valid TenantReSetPasswordForm userResetPasswordForm) {
        if (configValueUtil.isMultiTenancy()) {
            TenantDataSourceUtil.switchTenant(userResetPasswordForm.getTenantId());
        }
        UserEntity entity = userService.getUserByAccount(ADMIN_KEY);
        if (entity != null) {
            entity.setPassword(userResetPasswordForm.getUserPassword());
            userService.updatePassword(entity);
            userService.delCurUser(MsgCode.PS010.get(), ImmutableList.of(entity.getId()),null);
            entity.setPassword(userResetPasswordForm.getUserPassword());
            PullUserUtil.syncUser(entity, "modifyPassword", userResetPasswordForm.getTenantId());
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.fail(MsgCode.FA001.get());
    }

    /**
     * 获取用户信息
     *
     * @param tenantId 租户号
     * @return ignore
     */
    @Operation(summary = "获取用户信息")
    @Parameters({
            @Parameter(name = "tenantId", description = "租户号", required = true)
    })
    @NoDataSourceBind
    @GetMapping("/Tenant/AdminInfo")
    public AdminInfoVO adminInfo(@RequestParam("tenantId") String tenantId) throws DataException {
        if (configValueUtil.isMultiTenancy()) {
            TenantDataSourceUtil.switchTenant(tenantId);
        }
        UserEntity entity = userService.getUserByAccount(ADMIN_KEY);
        AdminInfoVO adminInfoVO = JsonUtil.getJsonToBean(entity, AdminInfoVO.class);
        return adminInfoVO;
    }

    /**
     * 修改管理员信息
     *
     * @param adminInfoVO 模型
     * @return ignore
     */
    @Operation(summary = "修改管理员信息")
    @Parameters({
            @Parameter(name = "adminInfoVO", description = "模型", required = true)
    })
    @NoDataSourceBind
    @PutMapping("/Tenant/UpdateAdminInfo")
    public ActionResult adminInfo(@RequestBody AdminInfoVO adminInfoVO) throws DataException {
        if (configValueUtil.isMultiTenancy()) {
            TenantDataSourceUtil.switchTenant(adminInfoVO.getTenantId());
        }
        UserEntity entity = userService.getUserByAccount(ADMIN_KEY);
        if (entity == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        entity.setRealName(adminInfoVO.getRealName());
        entity.setMobilePhone(adminInfoVO.getMobilePhone());
        entity.setEmail(adminInfoVO.getEmail());
        userService.updateById(entity);
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            try {
                //修改用户之后判断是否需要同步到企业微信
                synThirdQyService.updateUserSysToQy(false, entity, "");
                //修改用户之后判断是否需要同步到钉钉
                synThirdDingTalkService.updateUserSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("修改用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        // 删除在线的用户
        PullUserUtil.syncUser(entity, "update", adminInfoVO.getTenantId());
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 移除租户账号在线用户
     *
     * @param tenantId 租户号
     * @return ignore
     */
    @Operation(summary = "移除租户账号在线用户")
    @Parameters({
            @Parameter(name = "tenantId", description = "租户号", required = true)
    })
    @NoDataSourceBind
    @GetMapping("/Tenant/RemoveOnlineByTenantId")
    public void removeOnlineByTenantId(@RequestParam("tenantId") String tenantId) throws DataException {
        List<String> tokenList = new ArrayList<>();
        List<String> tokens = UserProvider.getLoginUserListToken();
        tokens.forEach(token -> {
            UserInfo userInfo = UserProvider.getUser(token);
            if (tenantId.equals(userInfo.getTenantId())) {
                tokenList.add(token);
            }
        });
        authService.kickoutByToken(tokenList.toArray(new String[0]));
    }

    //--------------------以下导入导出-----

    @Operation(summary = "模板下载")
    @SaCheckPermission("permission.user")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserColumnMap columnMap = new UserColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(false);
        List<Map<String, Object>> list = columnMap.getDefaultList();
        Map<String, String[]> optionMap = getOptionMap();
        ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(new ArrayList<>(keyMap.keySet())).optionMap(optionMap).build();
        DownloadVO vo = ExcelTool.getImportTemplate(configValueUtil.getTemporaryFilePath(), excelName, keyMap, list, excelModel);
        return ActionResult.success(vo);
    }

    @Operation(summary = "上传导入Excel")
    @SaCheckPermission("permission.user")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        return ExcelTool.uploader();
    }

    @Operation(summary = "导入预览")
    @SaCheckPermission("permission.user")
    @GetMapping("/ImportPreview")
    public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
        // 导入字段
        UserColumnMap columnMap = new UserColumnMap();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        Map<String, Object> headAndDataMap = ExcelTool.importPreview(configValueUtil.getTemporaryFilePath(), fileName, keyMap);
        return ActionResult.success(headAndDataMap);
    }

    /**
     * 导出异常报告
     *
     * @return
     */
    @Operation(summary = "导出异常报告")
    @SaCheckPermission("permission.user")
    @PostMapping("/ExportExceptionData")
    public ActionResult<DownloadVO> ExportExceptionData(@RequestBody ExcelImportForm visualImportModel) {
        String temporaryFilePath = configValueUtil.getTemporaryFilePath();
        List<Map<String, Object>> dataList = visualImportModel.getList();
        UserColumnMap columnMap = new UserColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(true);
        ExcelModel excelModel = ExcelModel.builder().optionMap(getOptionMap()).models(models).build();
        DownloadVO vo = ExcelTool.exportExceptionReport(temporaryFilePath, excelName, keyMap, dataList, excelModel);
        return ActionResult.success(vo);
    }

    /**
     * 导入数据
     *
     * @return
     */
    @Operation(summary = "导入数据")
    @SaCheckPermission("permission.user")
    @PostMapping("/ImportData")
    public ActionResult<ExcelImportVO> ImportData(@RequestBody ExcelImportForm visualImportModel) throws Exception {
        List<Map<String, Object>> listData  = new ArrayList<>();
        List<Map<String, Object>> headerRow = new ArrayList<>();
        if (visualImportModel.isType()){
            ActionResult result = ImportPreview(visualImportModel.getFileName());
            if (result == null){
                throw new Exception(MsgCode.FA018.get());
            }
            if (result.getCode() != 200){
                throw new Exception(result.getMsg());
            }
            if (result.getData() instanceof Map){
                Map<String,Object> data = (Map<String, Object>) result.getData();
                listData = (List<Map<String, Object>>) data.get("dataRow");
                headerRow = (List<Map<String, Object>>) data.get("headerRow");
            }
        }else {
            listData = visualImportModel.getList();
        }
        List<UserEntity> addList = new ArrayList<>();
        List<Map<String, Object>> failList = new ArrayList<>();
        // 对数据做校验
        this.validateImportData(listData, addList, failList);

        //正常数据插入
        for (UserEntity each : addList) {
            userService.create(each);
        }
        ExcelImportVO importModel = new ExcelImportVO();
        importModel.setSnum(addList.size());
        importModel.setFnum(failList.size());
        importModel.setResultType(failList.size() > 0 ? 1 : 0);
        importModel.setFailResult(failList);
        importModel.setHeaderRow(headerRow);
        return ActionResult.success(importModel);
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @Operation(summary = "导出Excel")
    @SaCheckPermission("permission.user")
    @GetMapping("/ExportData")
    public ActionResult ExportData(PaginationUser pagination) throws IOException {
        if (StringUtil.isEmpty(pagination.getSelectKey())) {
            return ActionResult.fail(MsgCode.IMP011.get());
        }

        List<UserEntity> list = userService.getList(pagination, null, false, false, null, null);
        Map<Object, String> roleIdAndNameMap = roleService.getRoleNameAndIdMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        Map<Object, String> posIdAndName = positionService.getPosEncodeAndName(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        Map<Object, String> groupEncodeMap = groupService.getGroupEncodeMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        Map<String, Object> orgMap = organizeService.getAllOrgsTreeName(true);
        Map<Object, String> userNameMap = userService.getUserNameAndIdMap(true).entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        //性别
        Map<String, String> sexMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId())
                .stream().collect(Collectors.toMap(DictionaryDataEntity::getEnCode, DictionaryDataEntity::getFullName));
        //职级
        Map<String, String> ranksMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.RANK.getDictionaryTypeId())
                .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
        //民族
        Map<String, String> nationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId())
                .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
        //证件类型
        Map<String, String> certificatesTypeMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId())
                .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));
        //文化程度
        Map<String, String> educationMap = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId())
                .stream().collect(Collectors.toMap(DictionaryDataEntity::getId, DictionaryDataEntity::getFullName));

        List<Map<String, Object>> realList = new ArrayList<>();
        for (UserEntity entity : list) {
            //获取角色
            QueryWrapper<UserRelationEntity> roleQuery = new QueryWrapper<>();
            roleQuery.lambda().eq(UserRelationEntity::getUserId, entity.getId());
            roleQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ROLE);
            List<String> roleIdList = new ArrayList<>();
            for (UserRelationEntity ure : userRelationService.list(roleQuery)) {
                if(StringUtil.isNotEmpty(roleIdAndNameMap.get(ure.getObjectId()))){
                    roleIdList.add(roleIdAndNameMap.get(ure.getObjectId()));
                }
            }
            entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
            entity.setRoleId(String.join(",", roleIdList));

            // 组织
            QueryWrapper<UserRelationEntity> query = new QueryWrapper<>();
            query.lambda().eq(UserRelationEntity::getUserId, entity.getId());
            query.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ORGANIZE);
            List<String> organizeIds = new ArrayList<>();
            userRelationService.list(query).forEach(u -> {
                for (String orgIds : orgMap.keySet()) {
                    if (orgIds.endsWith(u.getObjectId())) {
                        organizeIds.add(orgMap.get(orgIds).toString());
                    }
                }
            });
            entity.setOrganizeId(String.join(",", organizeIds));

            // 岗位装配
            QueryWrapper<UserRelationEntity> positionQuery = new QueryWrapper<>();
            positionQuery.lambda().eq(UserRelationEntity::getUserId, entity.getId());
            positionQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.POSITION);
            List<String> positionIds = new ArrayList<>();
            for (UserRelationEntity ure : userRelationService.list(positionQuery)) {
                if (posIdAndName.containsKey(ure.getObjectId())) {
                    positionIds.add(posIdAndName.get(ure.getObjectId()));
                }
            }
            entity.setPositionId(String.join(",", positionIds));

            // 设置分组id
            List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(entity.getId(), PermissionConst.GROUP);
            List<String> groupIds = new ArrayList<>();
            for (UserRelationEntity item : listByObjectType) {
                if (groupEncodeMap.containsKey(item.getObjectId())) {
                    groupIds.add(groupEncodeMap.get(item.getObjectId()));
                }
            }
            entity.setManagerId(userNameMap.get(entity.getManagerId()));
            //性别
            entity.setGender(sexMap.get(entity.getGender()));
            entity.setRanks(ranksMap.get(entity.getRanks()));
            entity.setNation(nationMap.get(entity.getNation()));
            entity.setCertificatesType(certificatesTypeMap.get(entity.getCertificatesType()));
            entity.setEducation(educationMap.get(entity.getEducation()));

            entity.setGroupId(String.join(",", groupIds));
            Map<String, Object> obj = JsonUtil.entityToMap(entity);
            if (obj.get("enabledMark") != null) {
                String stateName = "";
                if (Objects.equals(obj.get("enabledMark"), 0)) {
                    stateName = "禁用";
                } else if (Objects.equals(obj.get("enabledMark"), 1)) {
                    stateName = "启用";
                } else if (Objects.equals(obj.get("enabledMark"), 2)) {
                    stateName = "锁定";
                }
                obj.put("enabledMark", stateName);
            }
            if (obj.get("birthday") != null) {
                obj.put("birthday", DateUtil.daFormat(Long.parseLong(obj.get("birthday").toString())));
            }
            if (obj.get("entryDate") != null) {
                obj.put("entryDate", DateUtil.daFormat(Long.parseLong(obj.get("entryDate").toString())));
            }
            realList.add(obj);
        }
        //todo 数据
        String[] keys = !StringUtil.isEmpty(pagination.getSelectKey()) ? pagination.getSelectKey() : new String[0];
        UserColumnMap columnMap = new UserColumnMap();
        String excelName = columnMap.getExcelName();
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(false);
        Map<String, String> keyMap = columnMap.getColumnByType(null);
        ExcelModel excelModel = ExcelModel.builder().selectKey(Arrays.asList(keys)).models(models).build();
        DownloadVO vo = ExcelTool.creatModelExcel(configValueUtil.getTemporaryFilePath(), excelName, keyMap, realList, excelModel);
        return ActionResult.success(vo);
    }

    /**
     * 导入验证
     *
     * @param listData
     * @param addList
     * @param failList
     */
    private void validateImportData(List<Map<String, Object>> listData, List<UserEntity> addList, List<Map<String, Object>> failList) {
        UserColumnMap columnMap = new UserColumnMap();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        List<DictionaryDataEntity> sexList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId());
        Map<String, String> genderMap = sexList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getEnCode));
        List<DictionaryDataEntity> rankList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.RANK.getDictionaryTypeId());
        Map<String, String> ranksMap = rankList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
        List<DictionaryDataEntity> nationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.NATION.getDictionaryTypeId());
        Map<String, String> nationMap = nationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
        List<DictionaryDataEntity> certificateList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId());
        Map<String, String> certificateMap = certificateList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
        List<DictionaryDataEntity> educationList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.EDUCATION.getDictionaryTypeId());
        Map<String, String> educationMap = educationList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
        Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
        Map<String, Object> userNameMap = userService.getUserNameAndIdMap();

        for (int i = 0, len = listData.size(); i < len; i++) {
            Map<String, Object> eachMap = listData.get(i);
            Map<String, Object> realMap = JsonUtil.getJsonToBean(eachMap, Map.class);
            StringJoiner errInfo = new StringJoiner(",");

            // 开启多租住的-判断用户额度
            String tenantId = UserProvider.getUser().getTenantId();
            if (StringUtil.isNotEmpty(tenantId)) {
                TenantVO cacheTenantInfo = TenantDataSourceUtil.getCacheTenantInfo(tenantId);
                long count = userService.count() + addList.size();
                if (cacheTenantInfo.getAccountNum() != 0 && cacheTenantInfo.getAccountNum() < count) {
                    eachMap.put("errorsInfo", MsgCode.PS009.get());
                    failList.add(eachMap);
                    continue;
                }
            }

            //组织多选id，用于查询角色和岗位
            StringJoiner organizeIds = new StringJoiner(",");
            for (String column : keyMap.keySet()) {
                Object valueObj = eachMap.get(column);
                String value = valueObj == null ? null : String.valueOf(valueObj);
                String columnName = keyMap.get(column);
                switch (column) {
                    case "gender":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if (genderMap.containsKey(valueObj.toString())) {
                            realMap.put("gender", genderMap.get(value));
                        } else {
                            errInfo.add("找不到该" + columnName + "值");
                        }
                        break;
                    case "ranks":
                        if (StringUtil.isNotEmpty(value)) {
                            if (ranksMap.containsKey(valueObj.toString())) {
                                realMap.put("ranks", ranksMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "nation":
                        if (StringUtil.isNotEmpty(value)) {
                            if (nationMap.containsKey(valueObj.toString())) {
                                realMap.put("nation", nationMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "certificatesType":
                        if (StringUtil.isNotEmpty(value)) {
                            if (certificateMap.containsKey(valueObj.toString())) {
                                realMap.put("certificatesType", certificateMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "education":
                        if (StringUtil.isNotEmpty(value)) {
                            if (educationMap.containsKey(valueObj.toString())) {
                                realMap.put("education", educationMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "account":
                        //账号
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if (value.length() > 50) {
                            errInfo.add(columnName + "值超出最多输入字符限制");
                        }
                        //值不能含有特殊符号
                        if (!RegexUtils.checkSpecoalSymbols(value)) {
                            errInfo.add(columnName + "值不能含有特殊符号");
                        }
                        //库里重复
                        if (userService.isExistByAccount(value)) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        //表格内重复
                        long enCodeCount = addList.stream().filter(t -> t.getAccount().equals(value)).count();
                        if (enCodeCount > 0) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        break;
                    case "realName":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if (value.length() > 50) {
                            errInfo.add(columnName + "值超出最多输入字符限制");
                        }
                        //值不能含有特殊符号
                        if (!RegexUtils.checkSpecoalSymbols(value)) {
                            errInfo.add(columnName + "值不能含有特殊符号");
                        }
                        break;
                    case "organizeId":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        List<String> orgList = Arrays.asList(value.split(","));
                        List<String> orgErrList = new ArrayList<>();
                        for (String orgName : orgList) {
                            CheckResult organizeIdCheckResult = checkOrganizeId(orgName, allOrgsTreeName);
                            if (!organizeIdCheckResult.isPass()) {
                                orgErrList.add(orgName);
                            } else {
                                organizeIds.add(organizeIdCheckResult.getValue().toString());
                            }
                        }
                        if (orgErrList.size() > 1) {
                            errInfo.add("找不到该所属组织(" + String.join("、", orgErrList) + ")");
                            break;
                        } else if (orgErrList.size() == 1) {
                            errInfo.add("找不到该所属组织");
                            break;
                        }
                        realMap.put("organizeId", organizeIds.toString());
                        break;
                    case "positionId":
                        if (StringUtil.isNotEmpty(value)) {
                            List<String> list = Arrays.asList(organizeIds.toString().split(","));
                            List<PermissionModel> listByOrganizeIds = StringUtil.isEmpty(organizeIds.toString()) ? new ArrayList<>()
                                    : positionService.getListByOrganizeIds(list, true,false);
                            Map<String, String> positionMap = new HashMap<>();
                            for (PermissionModel item : listByOrganizeIds) {
                                if (CollectionUtil.isNotEmpty(item.getChildren())) {
                                    List children = item.getChildren();
                                    for (Object obj : children) {
                                        PermissionModel model = (PermissionModel) obj;
                                        positionMap.put(model.getFullName(), model.getId());
                                    }
                                }
                            }
                            StringJoiner posIds = new StringJoiner(",");
                            List<String> posErrList = new ArrayList<>();
                            List<String> listName = Arrays.asList(value.split(","));
                            for (String item : listName) {
                                if (positionMap.containsKey(item)) {
                                    posIds.add(positionMap.get(item));
                                } else {
                                    posErrList.add(item);
                                }
                            }
                            if(posErrList.size()>0){
                                if (listName.size() > 1) {
                                    errInfo.add("找不到该所属组织的" + columnName + "(" + String.join("、", posErrList) + ")");
                                    break;
                                } else if (listName.size() == 1) {
                                    errInfo.add("找不到该所属组织的" + columnName);
                                    break;
                                }
                            }
                            if (StringUtil.isNotEmpty(posIds.toString())) {
                                realMap.put("positionId", posIds.toString());
                                break;
                            }
                            break;
                        }
                        break;
                    case "roleId":
                        if (StringUtil.isNotEmpty(value)) {
                            List<String> list = Arrays.asList(organizeIds.toString().split(","));
                            List<RoleModel> listByOrganizeIds = StringUtil.isEmpty(organizeIds.toString()) ? new ArrayList<>()
                                    : roleService.getListByOrganizeIds(list, true,false);
                            Map<String, String> roleMap = new HashMap<>();
                            for (RoleModel item : listByOrganizeIds) {
                                if (CollectionUtil.isNotEmpty(item.getChildren())) {
                                    List children = item.getChildren();
                                    for (Object obj : children) {
                                        RoleModel model = (RoleModel) obj;
                                        roleMap.put(model.getFullName(), model.getId());
                                    }
                                }
                            }
                            StringJoiner roleIds = new StringJoiner(",");
                            List<String> roleErrList = new ArrayList<>();
                            List<String> listName = Arrays.asList(value.split(","));
                            for (String item : listName) {
                                if (roleMap.containsKey(item)) {
                                    roleIds.add(roleMap.get(item));
                                } else {
                                    roleErrList.add(item);
                                }
                            }
                            if(roleErrList.size()>0){
                                if (listName.size() > 1) {
                                    errInfo.add("找不到该" + columnName + "(" + String.join("、", roleErrList) + ")");
                                    break;
                                } else if (listName.size() == 1) {
                                    errInfo.add("找不到该" + columnName);
                                    break;
                                }
                            }
                            if (StringUtil.isNotEmpty(roleIds.toString())) {
                                realMap.put("roleId", roleIds.toString());
                                break;
                            }
                            break;
                        }
                        break;
                    case "managerId":
                        if (StringUtil.isNotEmpty(value)) {
                            if (userNameMap.containsKey(value)) {
                                realMap.put("managerId", userNameMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName);
                            }
                        }
                        break;
                    case "entryDate":
                        if (StringUtil.isNotEmpty(value)) {
                            Date date = DateUtil.checkDate(value,"yyyy-MM-dd");
                            if (date == null) {
                                errInfo.add(columnName + "值不正确");
                                break;
                            }
                            realMap.put("entryDate", date);
                        }
                        break;
                    case "birthday":
                        if (StringUtil.isNotEmpty(value)) {
                            Date date = DateUtil.checkDate(value,"yyyy-MM-dd");
                            if (date == null) {
                                errInfo.add(columnName + "值不正确");
                                break;
                            }
                            realMap.put("birthday", date);
                        }
                        break;
                    case "sortCode":
                        if (StringUtil.isEmpty(value)) {
                            realMap.put("sortCode", 0);
                            break;
                        }
                        Long numValue = 0l;
                        try {
                            numValue = Long.parseLong(value);
                        } catch (Exception e) {
                            errInfo.add(columnName + "值不正确");
                            break;
                        }
                        if (numValue < 0) {
                            errInfo.add(columnName + "值不能小于0");
                            break;
                        }
                        if (numValue > 1000000) {
                            errInfo.add(columnName + "值不能大于999999");
                            break;
                        }
                        break;
                    case "enabledMark":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if ("启用".equals(value)) {
                            realMap.put("enabledMark", 1);
                        } else if ("禁用".equals(value)) {
                            realMap.put("enabledMark", 0);
                        } else if ("锁定".equals(value)) {
                            realMap.put("enabledMark", 2);
                        } else {
                            errInfo.add("找不到该" + columnName + "值");
                        }
                        break;
                    default:
                        break;
                }

            }

            if (errInfo.length() == 0) {
                UserEntity entity = JsonUtil.getJsonToBean(realMap, UserEntity.class);
                entity.setCreatorTime(new Date());
                addList.add(entity);
            } else {
                eachMap.put("errorsInfo", errInfo.toString());
                failList.add(eachMap);
            }
        }
    }

    private CheckResult checkOrganizeId(String organizeName, Map<String, Object> allOrgsTreeName) {
        for (String key : allOrgsTreeName.keySet()) {
            Object o = allOrgsTreeName.get(key);
            if (organizeName.equals(o.toString())) {
                String[] split = key.split(",");
                return new CheckResult(true, null, split[split.length - 1]);
            }
        }
        return new CheckResult(false, "所属组织不正确", null);
    }

    /**
     * 获取下拉框
     *
     * @return
     */
    private Map<String, String[]> getOptionMap() {
        Map<String, String[]> optionMap = new HashMap<>();
        //性别
        List<DictionaryDataEntity> sexList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.SEX_TYPE.getDictionaryTypeId());
        String[] gender = sexList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("gender", gender);
        //职级
        List<DictionaryDataEntity> ranksList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.RANK.getDictionaryTypeId());
        String[] ranks = ranksList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("ranks", ranks);
        //状态
        optionMap.put("enabledMark", new String[]{"启用", "禁用", "锁定"});
        //民族
        List<DictionaryDataEntity> nationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.NATION.getDictionaryTypeId());
        String[] nation = nationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("nation", nation);
        //证件类型
        List<DictionaryDataEntity> certificatesTypeList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.CERTIFICATE_TYPE.getDictionaryTypeId());
        String[] certificatesType = certificatesTypeList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("certificatesType", certificatesType);
        //文化程度
        List<DictionaryDataEntity> educationList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.EDUCATION.getDictionaryTypeId());
        String[] education = educationList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("education", education);
        return optionMap;
    }
}

