package com.yunzhupaas.permission.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.OrganizePermission;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.Pagination;
import com.yunzhupaas.base.controller.SuperController;
import com.yunzhupaas.base.entity.DictionaryDataEntity;
import com.yunzhupaas.base.service.DictionaryDataService;
import com.yunzhupaas.base.vo.DownloadVO;
import com.yunzhupaas.base.vo.ListVO;
import com.yunzhupaas.base.vo.PaginationVO;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.constant.PermissionConst;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.message.service.SynThirdDingTalkService;
import com.yunzhupaas.message.service.SynThirdQyService;
import com.yunzhupaas.model.ExcelColumnAttr;
import com.yunzhupaas.model.ExcelImportForm;
import com.yunzhupaas.model.ExcelImportVO;
import com.yunzhupaas.model.ExcelModel;
import com.yunzhupaas.permission.constant.OrgColumnMap;
import com.yunzhupaas.permission.entity.OrganizeAdministratorEntity;
import com.yunzhupaas.permission.entity.OrganizeEntity;
import com.yunzhupaas.permission.model.organize.*;
import com.yunzhupaas.permission.model.user.UserIdListVo;
import com.yunzhupaas.permission.model.user.mod.UserIdModel;
import com.yunzhupaas.permission.model.position.PaginationPosition;
import com.yunzhupaas.permission.service.OrganizeAdministratorService;
import com.yunzhupaas.permission.service.OrganizeRelationService;
import com.yunzhupaas.permission.service.OrganizeService;
import com.yunzhupaas.permission.service.UserService;
import com.yunzhupaas.base.util.ExcelTool;
import com.yunzhupaas.util.*;
import com.yunzhupaas.util.enums.DictionaryDataEnum;
import com.yunzhupaas.util.treeutil.ListToTreeUtil;
import com.yunzhupaas.util.treeutil.SumTree;
import com.yunzhupaas.util.treeutil.newtreeutil.TreeDotUtils;
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;

/**
 * 组织机构
 * 组织架构：公司》部门》岗位》用户
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024-09-26 上午9:18
 */
@Tag(name = "组织管理", description = "Organize")
@RestController
@RequestMapping("/api/permission/Organize")
@Slf4j
public class OrganizeController extends SuperController<OrganizeService, OrganizeEntity> {

    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private UserService userService;
    @Autowired
    private SynThirdQyService synThirdQyService;
    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private OrganizeAdministratorService organizeAdministratorService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DictionaryDataService dictionaryDataApi;

    //---------------------------组织管理--------------------------------------------

    /**
     * 获取组织列表
     *
     * @param pagination 分页模型
     * @return
     */
    @Operation(summary = "获取组织列表")
    @SaCheckPermission(value = {"permission.organize", "permission.position", "permission.user", "permission.role"}, mode = SaMode.OR)
    @GetMapping
    public ActionResult<ListVO<OrganizeListVO>> getList(PaginationOrganize pagination) {
        // 获取所有组织
        Map<String, OrganizeEntity> orgMaps;
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 通过权限转树
            List<OrganizeAdministratorEntity> listss = organizeAdministratorService.getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
            Set<String> orgIds = new HashSet<>(16);
            // 判断自己是哪些组织的管理员
            listss.stream().forEach(t -> {
                if (t != null) {
                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgIds.add(t.getOrganizeId());
                    }
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId(), Objects.equals(pagination.getEnabledMark(), 1));
                        orgIds.addAll(underOrganizations);
                    }
                }
            });
            List<String> list1 = new ArrayList<>(orgIds);
            // 得到所有有权限的组织
            orgMaps = organizeService.getOrganizeName(list1, pagination.getKeyword(), Objects.equals(pagination.getEnabledMark(), 1), pagination.getType());
        } else {
            orgMaps = organizeService.getOrgMaps(pagination.getKeyword(), Objects.equals(pagination.getEnabledMark(), 1), pagination.getType());
        }
        Map<String, OrganizeModel> orgMapsModel = JSONObject.parseObject(JSONObject.toJSONString(orgMaps), new TypeReference<LinkedHashMap<String, OrganizeModel>>() {
        }, new Feature[0]);
        ;

        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        orgMapsModel.values().forEach(t -> {
            if (PermissionConst.COMPANY.equals(t.getType())) {
                t.setIcon("icon-ym icon-ym-tree-organization3");
            } else {
                t.setIcon("icon-ym icon-ym-tree-department1");
            }
            // 处理断层
            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                String[] split = t.getOrganizeIdTree().split(",");
                List<String> list1 = Arrays.asList(split);
                Collections.reverse(list1);
                for (String orgId : list1) {
                    if (!orgId.equals(t.getId())) {
                        OrganizeModel organizeEntity1 = orgMapsModel.get(orgId);
                        if (organizeEntity1 != null) {
                            t.setParentId(organizeEntity1.getId());
                            String[] split1 = t.getOrganizeIdTree().split(organizeEntity1.getId());
                            if (split1.length > 1) {
                                t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
                            }
                            break;
                        }
                    }
                }
            }
        });
        List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertMapsToTreeDot(orgMapsModel);
        List<OrganizeListVO> listVO = JsonUtil.getJsonToList(trees, OrganizeListVO.class);
        listVO.forEach(t -> {
            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
        });
        ListVO<OrganizeListVO> vo = new ListVO<>();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 获取组织下拉框列表
     *
     * @param pagination 分页模型
     * @param id         主键
     * @return
     */
    @Operation(summary = "获取组织下拉框列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/Selector/{id}")
    public ActionResult<ListVO<OrganizeSelectorVO>> getSelector(Pagination pagination, @PathVariable("id") String id) {
        List<OrganizeEntity> allList = new LinkedList<>(organizeService.getOrgMaps(pagination.getKeyword(), true, null).values());
        if (!"0".equals(id)) {
            allList.remove(organizeService.getInfo(id));
        }
        List<OrganizeEntity> dataAll = allList;
        List<OrganizeEntity> list = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(allList, dataAll), OrganizeEntity.class);
        list = list.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
        List<OrganizeModel> models = JsonUtil.getJsonToList(list, OrganizeModel.class);
        for (OrganizeModel model : models) {
            model.setIcon("icon-ym icon-ym-tree-organization3");
        }
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        models.forEach(t -> {
            t.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                String[] split = t.getOrganizeIdTree().split(",");
                if (split.length > 0) {
                    t.setOrganizeIds(Arrays.asList(split));
                } else {
                    t.setOrganizeIds(new ArrayList<>());
                }
            }
        });

        List<OrganizeModel> modelAll = new ArrayList<>();
        modelAll.addAll(models);
        List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDotFilter(modelAll);
        List<OrganizeSelectorVO> listVO = JsonUtil.getJsonToList(trees, OrganizeSelectorVO.class);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 获取组织下拉框列表
     *
     * @param pagination 分页模型
     * @param id         主键
     * @return
     */
    @Operation(summary = "获取组织下拉框列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/SelectorByAuth/{id}")
    public ActionResult<ListVO<OrganizeSelectorByAuthVO>> getSelectorByAuth(Pagination pagination, @PathVariable("id") String id) {
        List<OrganizeEntity> allList = new LinkedList<>(organizeService.getOrgMaps(pagination.getKeyword(), true, null).values());
        allList = allList.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
        OrganizeEntity entity = organizeService.getInfo(id);
        List<OrganizeEntity> dataAll = allList;

        List<OrganizeEntity> list = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(allList, dataAll), OrganizeEntity.class);

        List<OrganizeByAuthModel> models = JsonUtil.getJsonToList(list, OrganizeByAuthModel.class);

        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 通过权限转树
            List<OrganizeAdministratorEntity> listss = organizeAdministratorService.getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
            Set<String> orgIds = new HashSet<>(16);
            // 判断自己是哪些组织的管理员
            listss.stream().forEach(t -> {
                if (t != null) {
                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgIds.add(t.getOrganizeId());
                    }
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId(), false);
                        orgIds.addAll(underOrganizations);
                    }
                }
            });
            List<String> list1 = new ArrayList<>(orgIds);
            // 得到所有有权限的组织
            List<OrganizeEntity> organizeName = organizeService.getOrganizeName(list1);
            organizeName = organizeName.stream().filter(t -> PermissionConst.COMPANY.equals(t.getCategory())).collect(Collectors.toList());
            models = JsonUtil.getJsonToList(organizeName, OrganizeByAuthModel.class);
        }

        // 判断当前编辑的权限时候是否有上级
        if (entity != null) {
            if (models.stream().filter(t -> t.getId().equals(entity.getParentId())).findFirst().orElse(null) == null) {
                OrganizeEntity info = organizeService.getInfo(entity.getParentId());
                if (info != null) {
                    OrganizeByAuthModel jsonToBean = JsonUtil.getJsonToBean(info, OrganizeByAuthModel.class);
                    jsonToBean.setDisabled(true);
                    models.add(jsonToBean);
                }
            }
        }
        List<OrganizeByAuthModel> finalModels = models;
        models.forEach(t -> {
            if (PermissionConst.COMPANY.equals(t.getType())) {
                t.setIcon("icon-ym icon-ym-tree-organization3");
            } else {
                t.setIcon("icon-ym icon-ym-tree-department1");
            }
            // 处理断层
            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                String[] split = t.getOrganizeIdTree().split(",");
                List<String> list1 = Arrays.asList(split);
                t.setOrganizeIds(list1);
                t.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
                List<String> list2 = new ArrayList<>(list1);
                Collections.reverse(list2);
                for (String orgId : list2) {
                    OrganizeModel organizeEntity1 = finalModels.stream().filter(organizeEntity -> organizeEntity.getId().equals(orgId)).findFirst().orElse(null);
                    if (organizeEntity1 != null && !organizeEntity1.getId().equals(t.getId())) {
                        t.setParentId(organizeEntity1.getId());
                        String[] split1 = t.getOrganizeIdTree().split(organizeEntity1.getId());
                        if (split1.length > 1) {
                            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
                        }
                        break;
                    }
                }
            }
        });
        List<SumTree<OrganizeByAuthModel>> trees = TreeDotUtils.convertListToTreeDot(models);
        List<OrganizeSelectorByAuthVO> listVO = JsonUtil.getJsonToList(trees, OrganizeSelectorByAuthVO.class);
        listVO.forEach(t -> {
            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
        });
        ListVO<OrganizeSelectorByAuthVO> vo = new ListVO<>();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 通过部门id获取部门下拉框下拉框
     *
     * @return
     */
    @Operation(summary = "通过部门id获取部门下拉框")
    @Parameters({
            @Parameter(name = "organizeConditionModel", description = "组织id模型", required = true)
    })
    @PostMapping("/OrganizeCondition")
    public ActionResult<ListVO<OrganizeListVO>> organizeCondition(@RequestBody OrganizeConditionModel organizeConditionModel) {
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        organizeConditionModel.setOrgIdNameMaps(orgIdNameMaps);
        List<OrganizeModel> organizeList = organizeRelationService.getOrgIdsList(organizeConditionModel);
        List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(organizeList);
        List<OrganizeListVO> listVO = JsonUtil.getJsonToList(trees, OrganizeListVO.class);
        listVO.forEach(t -> {
            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
        });
        ListVO<OrganizeListVO> vo = new ListVO<>();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 组织树形
     *
     * @return
     */
    @Operation(summary = "获取组织/公司树形")
    @GetMapping("/Tree")
    public ActionResult<ListVO<OrganizeTreeVO>> tree() {
        List<OrganizeEntity> list = new LinkedList<>(organizeService.getOrgMaps(null, true, null).values());
        list = list.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
        List<OrganizeModel> models = JsonUtil.getJsonToList(list, OrganizeModel.class);
        for (OrganizeModel model : models) {
            model.setIcon("icon-ym icon-ym-tree-organization3");
        }
        List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(models);
        List<OrganizeTreeVO> listVO = JsonUtil.getJsonToList(trees, OrganizeTreeVO.class);
        //将子节点全部删除
        Iterator<OrganizeTreeVO> iterator = listVO.iterator();
        while (iterator.hasNext()) {
            OrganizeTreeVO orananizeTreeVO = iterator.next();
            if (!"-1".equals(orananizeTreeVO.getParentId())) {
                iterator.remove();
            }
        }
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 获取组织信息
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "获取组织信息")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @GetMapping("/{id}")
    public ActionResult<OrganizeInfoVO> info(@PathVariable("id") String id) throws DataException {
        OrganizeEntity entity = organizeService.getInfo(id);
        OrganizeInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, OrganizeInfoVO.class);
        if (StringUtil.isNotEmpty(entity.getOrganizeIdTree())) {
            String replace = entity.getOrganizeIdTree().replace(entity.getId(), "");
            if (StringUtil.isNotEmpty(replace) && !",".equals(replace)) {
                vo.setOrganizeIdTree(Arrays.asList(replace.split(",")));
            } else {
                vo.setOrganizeIdTree(Arrays.asList(new String[]{"-1"}));
            }
        }
        return ActionResult.success(vo);
    }


    /**
     * 新建组织
     *
     * @param organizeCrForm 新建模型
     * @return
     */
    @OrganizePermission
    @Operation(summary = "新建组织")
    @Parameters({
            @Parameter(name = "organizeCrForm", description = "新建模型", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PostMapping
    public ActionResult create(@RequestBody @Valid OrganizeCrForm organizeCrForm) {
        OrganizeEntity entity = JsonUtil.getJsonToBean(organizeCrForm, OrganizeEntity.class);
        entity.setCategory("company");
        if (organizeService.isExistByFullName(entity, false, false)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (organizeService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }

        // 通过组织id获取父级组织
        String organizeIdTree = organizeService.getOrganizeIdTree(entity);
        entity.setOrganizeIdTree(organizeIdTree);

        organizeService.create(entity);
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            try {
                //创建组织后判断是否需要同步到企业微信
                synThirdQyService.createDepartmentSysToQy(false, entity, "");
                //创建组织后判断是否需要同步到钉钉
                synThirdDingTalkService.createDepartmentSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("创建组织后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 更新组织
     *
     * @param id             主键值
     * @param organizeUpForm 实体对象
     * @return
     */
    @OrganizePermission
    @Operation(summary = "更新组织")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true),
            @Parameter(name = "organizeUpForm", description = "实体对象", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid OrganizeUpForm organizeUpForm) {
        List<OrganizeEntity> synList = new ArrayList<>();
        OrganizeEntity entity = JsonUtil.getJsonToBean(organizeUpForm, OrganizeEntity.class);
        OrganizeEntity info = organizeService.getInfo(organizeUpForm.getParentId());
        if (id.equals(entity.getParentId()) || (info != null && info.getOrganizeIdTree() != null && info.getOrganizeIdTree().contains(id))) {
            return ActionResult.fail(MsgCode.PS013.get());
        }
        entity.setId(id);
        entity.setCategory("company");
        if (organizeService.isExistByFullName(entity, false, true)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (organizeService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        // 通过组织id获取父级组织
        String organizeIdTree = organizeService.getOrganizeIdTree(entity);
        entity.setOrganizeIdTree(organizeIdTree);
        boolean flag = organizeService.update(id, entity);
        synList.add(entity);

        // 得到所有子组织或部门id
        if (info != null && info.getParentId() != null && !entity.getParentId().equals(info.getParentId())) {
            List<String> underOrganizations = organizeService.getUnderOrganizations(id, false);
            underOrganizations.forEach(t -> {
                OrganizeEntity info1 = organizeService.getInfo(t);
                if (StringUtil.isNotEmpty(info1.getOrganizeIdTree())) {
                    String organizeIdTrees = organizeService.getOrganizeIdTree(info1);
                    info1.setOrganizeIdTree(organizeIdTrees);
                    organizeService.update(info1.getId(), info1);
                    synList.add(info1);
                }
            });
        }
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            synList.forEach(t -> {
                try {
                    //修改组织后判断是否需要同步到企业微信
                    synThirdQyService.updateDepartmentSysToQy(false, t, "");
                    //修改组织后判断是否需要同步到钉钉
                    synThirdDingTalkService.updateDepartmentSysToDing(false, t, "");
                } catch (Exception e) {
                    log.error("修改组织后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                }
            });
        });
        if (!flag) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除组织
     *
     * @param orgId 组织主键
     * @return
     */
    @OrganizePermission
    @Operation(summary = "删除组织")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String orgId) {
        return organizeService.delete(orgId);
    }

    /**
     * 删除部门
     *
     * @param orgId 部门主键
     * @return
     */
    @OrganizePermission
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @Operation(summary = "删除部门")
    @DeleteMapping("/Department/{id}")
    public ActionResult<String> deleteDepartment(@PathVariable("id") String orgId) {
        return organizeService.delete(orgId);
    }

    /**
     * 更新组织状态
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "更新组织状态")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PutMapping("/{id}/Actions/State")
    public ActionResult update(@PathVariable("id") String id) {
        OrganizeEntity organizeEntity = organizeService.getInfo(id);
        if (organizeEntity != null) {
            if ("1".equals(String.valueOf(organizeEntity.getEnabledMark()))) {
                organizeEntity.setEnabledMark(0);
            } else {
                organizeEntity.setEnabledMark(1);
            }
            organizeService.update(organizeEntity.getId(), organizeEntity);
            return ActionResult.success(MsgCode.SU004.get());
        }
        return ActionResult.success(MsgCode.FA002.get());
    }

    /**
     * 获取部门下拉框列表
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取部门下拉框列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/Department/Selector/{id}")
    public ActionResult<ListVO<OrganizeDepartSelectorListVO>> getListDepartment(@PathVariable("id") String id) {
        List<OrganizeEntity> data = new LinkedList<>(organizeService.getOrgMaps(null, true, null).values());
        if (!"0".equals(id)) {
            data.remove(organizeService.getInfo(id));
        }
        List<OrganizeModel> models = JsonUtil.getJsonToList(data, OrganizeModel.class);
        for (OrganizeModel model : models) {
            if ("department".equals(model.getType())) {
                model.setIcon("icon-ym icon-ym-tree-department1");
            } else if ("company".equals(model.getType())) {
                model.setIcon("icon-ym icon-ym-tree-organization3");
            }
        }

        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        models.forEach(t -> {
            t.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                String[] split = t.getOrganizeIdTree().split(",");
                if (split.length > 0) {
                    t.setOrganizeIds(Arrays.asList(split));
                } else {
                    t.setOrganizeIds(new ArrayList<>());
                }
            }
        });

        List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDotFilter(models);
        List<OrganizeDepartSelectorListVO> listVO = JsonUtil.getJsonToList(trees, OrganizeDepartSelectorListVO.class);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 获取部门下拉框列表
     *
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取部门下拉框列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/Department/SelectorByAuth/{id}")
    public ActionResult<ListVO<OrganizeSelectorByAuthVO>> getDepartmentSelectorByAuth(@PathVariable("id") String id) {
        Map<String, OrganizeEntity> orgMaps;
        OrganizeEntity entity = organizeService.getInfo(id);

        if (!UserProvider.getUser().getIsAdministrator()) {
            // 通过权限转树
            List<OrganizeAdministratorEntity> listss = organizeAdministratorService.getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
            Set<String> orgIds = new HashSet<>(16);
            // 判断自己是哪些组织的管理员
            listss.stream().forEach(t -> {
                if (t != null) {
                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgIds.add(t.getOrganizeId());
                    }
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId(), false);
                        orgIds.addAll(underOrganizations);
                    }
                }
            });
            List<String> list1 = new ArrayList<>(orgIds);
            orgMaps = organizeService.getOrganizeName(list1, null, true, null);
        } else {
            orgMaps = organizeService.getOrgMaps(null, true, null);
        }
        Map<String, OrganizeByAuthModel> orgMapsModel = JSONObject.parseObject(JSONObject.toJSONString(orgMaps), new TypeReference<LinkedHashMap<String, OrganizeByAuthModel>>() {}, new Feature[0]);;
        if (!"0".equals(id)) {
            orgMapsModel.remove(id);
        }
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        // 判断当前编辑的权限时候是否有上级
        if (entity != null) {
            if (orgMapsModel.values().stream().filter(t -> t.getId().equals(entity.getParentId())).findFirst().orElse(null) == null) {
                OrganizeEntity info = organizeService.getInfo(entity.getParentId());
                if (info != null) {
                    OrganizeByAuthModel jsonToBean = JsonUtil.getJsonToBean(info, OrganizeByAuthModel.class);
                    jsonToBean.setDisabled(true);
                    orgMapsModel.put(info.getId(), jsonToBean);
                }
            }
        }
        orgMapsModel.values().forEach(t -> {
            if (PermissionConst.COMPANY.equals(t.getType())) {
                t.setIcon("icon-ym icon-ym-tree-organization3");
            } else {
                t.setIcon("icon-ym icon-ym-tree-department1");
            }
            // 处理断层
            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
                List<String> list1 = new ArrayList<>();
                String[] split = t.getOrganizeIdTree().split(",");
                list1 = Arrays.asList(split);
                List<String> list = new ArrayList<>(16);
                list1.forEach(orgId -> {
                    if (StringUtil.isNotEmpty(orgId)) {
                        list.add(orgId);
                    }
                });
                t.setOrganizeIds(list);
                t.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
                Collections.reverse(list1);
                for (String orgId : list1) {
                    OrganizeModel organizeEntity1 = orgMapsModel.get(orgId);
                    if (organizeEntity1 != null && !organizeEntity1.getId().equals(t.getId())) {
                        t.setParentId(organizeEntity1.getId());
                        String[] split1 = t.getOrganizeIdTree().split(organizeEntity1.getId());
                        if (split1.length > 1) {
                            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
                        }
                        break;
                    }
                }
            }
        });
        List<SumTree<OrganizeByAuthModel>> trees = TreeDotUtils.convertMapsToTreeDot(orgMapsModel);
        List<OrganizeSelectorByAuthVO> listVO = JsonUtil.getJsonToList(trees, OrganizeSelectorByAuthVO.class);
        listVO.forEach(t -> {
            t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, t.getOrganizeIdTree(), "/"));
        });
        ListVO vo = new ListVO();
        vo.setList(listVO);
        return ActionResult.success(vo);
    }

    /**
     * 新建部门
     *
     * @param organizeDepartCrForm 新建模型
     * @return
     */
    @OrganizePermission
    @Operation(summary = "新建部门")
    @Parameters({
            @Parameter(name = "organizeDepartCrForm", description = "新建模型", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PostMapping("/Department")
    public ActionResult createDepartment(@RequestBody @Valid OrganizeDepartCrForm organizeDepartCrForm) {
        OrganizeEntity entity = JsonUtil.getJsonToBean(organizeDepartCrForm, OrganizeEntity.class);
        entity.setCategory("department");
        //判断同一个父级下是否含有同一个名称
        if (organizeService.isExistByFullName(entity, false, false)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        //判断同一个父级下是否含有同一个编码
        if (organizeService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }

        // 通过组织id获取父级组织
        String organizeIdTree = organizeService.getOrganizeIdTree(entity);
        entity.setOrganizeIdTree(organizeIdTree);

        organizeService.create(entity);
        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            try {
                //创建部门后判断是否需要同步到企业微信
                synThirdQyService.createDepartmentSysToQy(false, entity, "");
                //创建部门后判断是否需要同步到钉钉
                synThirdDingTalkService.createDepartmentSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("创建部门后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 更新部门
     *
     * @param id                    主键值
     * @param oraganizeDepartUpForm 修改模型
     * @return
     */
    @OrganizePermission
    @Operation(summary = "更新部门")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true),
            @Parameter(name = "oraganizeDepartUpForm", description = "修改模型", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PutMapping("/Department/{id}")
    public ActionResult updateDepartment(@PathVariable("id") String id, @RequestBody @Valid OrganizeDepartUpForm oraganizeDepartUpForm) {
        List<OrganizeEntity> synList = new ArrayList<>();
        OrganizeEntity entity = JsonUtil.getJsonToBean(oraganizeDepartUpForm, OrganizeEntity.class);
        OrganizeEntity info = organizeService.getInfo(oraganizeDepartUpForm.getParentId());
        if (id.equals(entity.getParentId()) || (info != null && info.getOrganizeIdTree() != null && info.getOrganizeIdTree().contains(id))) {
            return ActionResult.fail(MsgCode.PS013.get());
        }
        entity.setId(id);
        entity.setCategory("department");
        //判断同一个父级下是否含有同一个名称
        if (organizeService.isExistByFullName(entity, false, true)) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        //判断同一个父级下是否含有同一个编码
        if (organizeService.isExistByEnCode(entity.getEnCode(), entity.getId())) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        // 通过组织id获取父级组织
        String organizeIdTree = organizeService.getOrganizeIdTree(entity);
        entity.setOrganizeIdTree(organizeIdTree);
        boolean flag = organizeService.update(id, entity);
        synList.add(entity);

        // 得到所有子组织或部门id
        if (info.getParentId() != null && !entity.getParentId().equals(info.getParentId())) {
            List<String> underOrganizations = organizeService.getUnderOrganizations(id, false);
            underOrganizations.forEach(t -> {
                OrganizeEntity info1 = organizeService.getInfo(t);
                if (StringUtil.isNotEmpty(info1.getOrganizeIdTree())) {
                    String organizeIdTrees = organizeService.getOrganizeIdTree(info1);
                    info1.setOrganizeIdTree(organizeIdTrees);
                    organizeService.update(info1.getId(), info1);
                    synList.add(info1);
                }
            });
        }

        ThreadPoolExecutorUtil.getExecutor().execute(() -> {
            synList.forEach(t -> {
                try {
                    //修改部门后判断是否需要同步到企业微信
                    synThirdQyService.updateDepartmentSysToQy(false, organizeService.getInfo(id), "");
                    //修改部门后判断是否需要同步到钉钉
                    synThirdDingTalkService.updateDepartmentSysToDing(false, organizeService.getInfo(id), "");
                } catch (Exception e) {
                    log.error("修改部门后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                }
            });
        });
        if (flag == false) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 更新部门状态
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "更新部门状态")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @PutMapping("/Department/{id}/Actions/State")
    public ActionResult updateDepartment(@PathVariable("id") String id) {
        OrganizeEntity organizeEntity = organizeService.getInfo(id);
        if (organizeEntity != null) {
            if ("1".equals(String.valueOf(organizeEntity.getEnabledMark()))) {
                organizeEntity.setEnabledMark(0);
            } else {
                organizeEntity.setEnabledMark(1);
            }
            organizeService.update(organizeEntity.getId(), organizeEntity);
            return ActionResult.success(MsgCode.SU004.get());
        }
        return ActionResult.fail(MsgCode.FA002.get());
    }

    /**
     * 获取部门信息
     *
     * @param id 主键值
     * @return
     */
    @Operation(summary = "获取部门信息")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission(value = {"permission.organize"})
    @GetMapping("/Department/{id}")
    public ActionResult<OrganizeDepartInfoVO> infoDepartment(@PathVariable("id") String id) throws DataException {
        OrganizeEntity entity = organizeService.getInfo(id);
        OrganizeDepartInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, OrganizeDepartInfoVO.class);
        List<String> list = new ArrayList<>();
        if (StringUtil.isNotEmpty(entity.getOrganizeIdTree())) {
            String[] split = entity.getOrganizeIdTree().split(",");
            if (split.length > 1) {
                for (int i = 0; i < split.length - 1; i++) {
                    list.add(split[i]);
                }
            }
        }
        vo.setOrganizeIdTree(list);
        return ActionResult.success(vo);
    }

    /**
     * 获取默认当前值部门ID
     *
     * @param organizeConditionModel 参数
     * @return 执行结构
     * @throws DataException ignore
     */
    @Operation(summary = "获取默认当前值部门ID")
    @Parameters({
            @Parameter(name = "organizeConditionModel", description = "参数", required = true)
    })
    @PostMapping("/getDefaultCurrentValueDepartmentId")
    public ActionResult<?> getDefaultCurrentValueDepartmentId(@RequestBody OrganizeConditionModel organizeConditionModel) throws DataException {
        String departmentId = organizeService.getDefaultCurrentValueDepartmentId(organizeConditionModel);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("departmentId", departmentId);
        return ActionResult.success(MsgCode.SU005.get(), dataMap);
    }

    // -----临时调用

    /**
     * 获取组织列表
     *
     * @param id         主键
     * @param pagination 分页模型
     * @return
     */
    @Operation(summary = "获取组织列表")
    @SaCheckPermission(value = {"permission.organize", "permission.position", "permission.user", "permission.role"}, mode = SaMode.OR)
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/AsyncList/{id}")
    public ActionResult<?> getList(@PathVariable("id") String id, PaginationOrganize pagination) {
        boolean filterEnabledMark = false;
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        List<OrganizeSelectorVO> listVO = organizeList(pagination, id, filterEnabledMark);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        if(!isKeyWord){
            return ActionResult.success(vo);
        }
        PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, jsonToBean);
//        ListVO<OrganizeListVO> vo = new ListVO<>();
//        // 获取所有组织
//        Map<String, OrganizeEntity> orgMaps;
//        if (!UserProvider.getUser().getIsAdministrator()) {
//            // 通过权限转树
//            List<OrganizeAdministratorEntity> listss = organizeAdministratorService.getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
//            Set<String> orgIds = new HashSet<>(16);
//            // 判断自己是哪些组织的管理员
//            listss.stream().forEach(t -> {
//                if (t != null) {
//                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
//                        orgIds.add(t.getOrganizeId());
//                    }
//                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
//                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId(), false);
//                        orgIds.addAll(underOrganizations);
//                    }
//                }
//            });
//            List<String> list1 = new ArrayList<>(orgIds);
//            // 得到所有有权限的组织
//            orgMaps = organizeService.getOrganizeName(list1, null, false, null);
//        } else {
//            orgMaps = organizeService.getOrgMaps(null, false, null);
//        }
//        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
//        List<OrganizeEntity> organizeEntityList = new ArrayList<>();
//        OrganizeEntity parentEntity = null;
//        if ("0".equals(id)) {
//            parentEntity = organizeService.getInfoByParentId("-1");
//            OrganizeEntity organizeEntity = orgMaps.get(parentEntity.getId());
//            if (organizeEntity != null) {
//                organizeEntityList.add(organizeEntity);
//            }
//        } else {
//            parentEntity = organizeService.getInfo(id);
//        }
//        // 判断是否有顶级组织权限
//        if (organizeEntityList.size() == 0) {
//            List<OrganizeEntity> temOrganizeEntityList = new ArrayList<>();
//            temOrganizeEntityList.add(parentEntity);
//            getParentEntity(orgMaps, temOrganizeEntityList, organizeEntityList);
//        }
//        if (organizeEntityList.size() == 0) {
//            vo.setList(new ArrayList<>());
//            return ActionResult.success(vo);
//        }
//        List<OrganizeListVO> voList = JsonUtil.getJsonToList(organizeEntityList, OrganizeListVO.class);
//        voList.forEach(t -> {
//            if (PermissionConst.COMPANY.equals(t.getType())) {
//                t.setIcon("icon-ym icon-ym-tree-organization3");
//            } else {
//                t.setIcon("icon-ym icon-ym-tree-department1");
//            }
//            t.setHasChildren(true);
//            // 处理断层
//            if (StringUtil.isNotEmpty(t.getOrganizeIdTree())) {
//                String[] split = t.getOrganizeIdTree().split(",");
//                List<String> list1 = Arrays.asList(split);
//                Collections.reverse(list1);
//                for (String orgId : list1) {
//                    if (!orgId.equals(t.getId())) {
//                        OrganizeEntity organizeEntity1 = orgMaps.get(orgId);
//                        if (organizeEntity1 != null) {
//                            t.setParentId(organizeEntity1.getId());
//                            String[] split1 = t.getOrganizeIdTree().split(organizeEntity1.getId());
//                            if (split1.length > 1) {
//                                t.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
//                            }
//                            break;
//                        }
//                    }
//                }
//            }
//        });
//        vo.setList(voList);
//        return ActionResult.success(vo);
    }

    private void getParentEntity(Map<String, OrganizeEntity> orgMaps,
                                                 List<OrganizeEntity> temOrganizeEntityList,
                                                 List<OrganizeEntity> organizeEntityList) {
        List<OrganizeEntity> temOrganizeEntityList1 = new ArrayList<>();
        // 判断是否有顶级组织权限
        if (organizeEntityList.size() == 0) {
            temOrganizeEntityList.forEach(t -> {
                List<OrganizeEntity> organizeByParentId = organizeService.getOrganizeByParentId(t.getId());
                temOrganizeEntityList1.addAll(organizeByParentId);
                organizeByParentId.forEach(organizeEntity -> {
                    OrganizeEntity organizeEntity1 = orgMaps.get(organizeEntity.getId());
                    if (organizeEntity1 != null) {
                        organizeEntityList.add(organizeEntity1);
                    }
                });
            });
        }
        if (organizeEntityList.size() == 0 && temOrganizeEntityList1.size() > 0) {
            getParentEntity(orgMaps, temOrganizeEntityList1, organizeEntityList);
        }
    }

    /**
     * 获取列表
     *
     * @param pagination 分页模型
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/Department/SelectAsyncList/{id}")
    public ActionResult<?> getSelectAsyncList(@PathVariable("id") String id,PaginationOrganize pagination) {
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        List<OrganizeSelectorVO> listVO = organizeList(pagination, id);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        if(!isKeyWord){
            return ActionResult.success(vo);
        }
        PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, jsonToBean);
    }

    /**
     * 获取列表
     *
     * @param pagination 分页模型
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/SelectAsyncList/{id}")
    public ActionResult<?> selectAsyncList(@PathVariable("id") String id,PaginationOrganize pagination) {
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        pagination.setType("company");
        List<OrganizeSelectorVO> listVO = organizeList(pagination, id);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        if(!isKeyWord){
            return ActionResult.success(vo);
        }
        PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, jsonToBean);
    }

    /**
     * 获取列表
     *
     * @param pagination 分页模型
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/SelectAsyncByAuth/{id}")
    public ActionResult<?> selectAsyncByAuth(@PathVariable("id") String id,PaginationOrganize pagination) {
        boolean filterEnabledMark = true;
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        pagination.setType("company");
        List<OrganizeSelectorVO> listVO = organizeList(pagination, id, filterEnabledMark);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        if(!isKeyWord){
            return ActionResult.success(vo);
        }
        PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, jsonToBean);
    }

    /**
     * 获取列表
     *
     * @param pagination 分页模型
     * @param id 主键
     * @return
     */
    @Operation(summary = "获取列表")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true)
    })
    @GetMapping("/Department/SelectAsyncByAuth/{id}")
    public ActionResult<?> selectAsyncByAuthDepartment(@PathVariable("id") String id,PaginationOrganize pagination) {
        boolean filterEnabledMark = true;
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        List<OrganizeSelectorVO> listVO = organizeList(pagination, id, filterEnabledMark);
        ListVO vo = new ListVO();
        vo.setList(listVO);
        if(!isKeyWord){
            return ActionResult.success(vo);
        }
        PaginationVO jsonToBean = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, jsonToBean);
    }

    /**
     * 获取选中值
     *
     * @return ignore
     */
    @Operation(summary = "获取选中值")
    @Parameters({
            @Parameter(name = "userIdModel", description = "id", required = true)
    })
    @PostMapping("/SelectedList")
    public ActionResult<ListVO<UserIdListVo>> SelectedList(@RequestBody UserIdModel userIdModel) {
        List<String> ids = new ArrayList<>();
        for(String id : userIdModel.getIds()){
            ids.add(id+"--"+PermissionConst.COMPANY);
        }
        List<UserIdListVo> list = userService.selectedByIds(ids);
        ListVO<UserIdListVo> listVO = new ListVO<>();
        listVO.setList(list);
        return ActionResult.success(listVO);
    }


    private List<String> organizeList(boolean filterEnabledMark){
        List<String> orgIds = new ArrayList<>();
        if (!UserProvider.getUser().getIsAdministrator()) {
            // 通过权限转树
            List<OrganizeAdministratorEntity> listss = organizeAdministratorService.getOrganizeAdministratorEntity(UserProvider.getUser().getUserId());
            // 判断自己是哪些组织的管理员
            listss.stream().forEach(t -> {
                if (t != null) {
                    if (t.getThisLayerSelect() != null && t.getThisLayerSelect() == 1) {
                        orgIds.add(t.getOrganizeId());
                    }
                    if (t.getSubLayerSelect() != null && t.getSubLayerSelect() == 1) {
                        List<String> underOrganizations = organizeService.getUnderOrganizations(t.getOrganizeId(), filterEnabledMark);
                        orgIds.addAll(underOrganizations);
                    }
                }
            });
            orgIds.add("com.yunzhupaas");
        }
        return orgIds;
    }

    private List<OrganizeSelectorVO> organizeList(PaginationOrganize pagination, String id, boolean filterEnabledMark){
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        List<OrganizeSelectorVO> listVO = new ArrayList<>();
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        List<String> orgIds = organizeList(filterEnabledMark);
        if(isKeyWord) {
            List<OrganizeEntity> list = organizeService.getPageList(orgIds,pagination,filterEnabledMark);
            for (OrganizeEntity entity : list) {
                OrganizeSelectorVO vo = JsonUtil.getJsonToBean(entity,OrganizeSelectorVO.class);
                vo.setIcon(PermissionConst.COMPANY.equals(entity.getCategory()) ? "icon-ym icon-ym-tree-organization3" : "icon-ym icon-ym-tree-department1");
                vo.setHasChildren(false);
                vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, entity.getOrganizeIdTree(), "/"));
                vo.setOrganizeIds(organizeService.getOrgIdTree(entity));
                listVO.add(vo);
            }
        }else {
            Map<String, OrganizeEntity> orgMaps = ObjectUtil.isNotEmpty(orgIds)? organizeService.getOrganizeName(orgIds, null, filterEnabledMark, pagination.getType()) :organizeService.getOrgMaps(null, filterEnabledMark, pagination.getType());
            Map<String, OrganizeModel> orgMapsModel = JSONObject.parseObject(JSONObject.toJSONString(orgMaps), new TypeReference<LinkedHashMap<String, OrganizeModel>>() {}, new Feature[0]);
            orgMapsModel.values().forEach(vo -> {
                vo.setIcon(PermissionConst.COMPANY.equals(vo.getType()) ? "icon-ym icon-ym-tree-organization3" : "icon-ym icon-ym-tree-department1");
                vo.setHasChildren(true);
                // 处理断层
                if (StringUtil.isNotEmpty(vo.getOrganizeIdTree())) {
                    String[] split = vo.getOrganizeIdTree().split(",");
                    List<String> list1 = Arrays.asList(split);
                    Collections.reverse(list1);
                    for (String orgId : list1) {
                        if(!orgId.equals(vo.getId())) {
                            OrganizeModel organizeEntity1 = orgMapsModel.get(orgId);
                            if (organizeEntity1 != null) {
                                vo.setParentId(organizeEntity1.getId());
                                String[] split1 = vo.getOrganizeIdTree().split(organizeEntity1.getId());
                                if (split1.length > 1) {
                                    vo.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, split1[1], "/"));
                                }
                                break;
                            }
                        }
                    }
                }
            });
            if ("0".equals(id)) {
                List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertMapsToTreeDot(orgMapsModel);
                listVO.addAll(JsonUtil.getJsonToList(trees, OrganizeSelectorVO.class));
                listVO.forEach(vo -> {
                    vo.setFullName(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, vo.getOrganizeIdTree(), "/"));
                    vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, vo.getOrganizeIdTree(), "/"));
                    vo.setOrganizeIds(Arrays.asList(vo.getOrganizeIdTree().split(",")));
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    vo.setChildren(new ArrayList<>());
                });
            } else {
                List<OrganizeModel> organizeList = orgMapsModel.values().stream().filter(t -> t.getParentId().equals(id)).collect(Collectors.toList());
                List<OrganizeSelectorVO> jsonToList = JsonUtil.getJsonToList(organizeList, OrganizeSelectorVO.class);
                for (OrganizeSelectorVO vo : jsonToList) {
                    vo.setOrganizeIds(Arrays.asList(vo.getOrganizeIdTree().split(",")));
                    vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, vo.getOrganizeIdTree(), "/"));
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    vo.setChildren(new ArrayList<>());
                }
                listVO.addAll(jsonToList);
            }
        }
        return listVO;
    }

    private List<OrganizeSelectorVO> organizeList(PaginationOrganize pagination, String id){
        Map<String, String> orgIdNameMaps = organizeService.getInfoList();
        List<OrganizeSelectorVO> listVO = new ArrayList<>();
        boolean isKeyWord = StringUtil.isNotEmpty(pagination.getKeyword());
        List<OrganizeEntity> list = new ArrayList<>();
        if(isKeyWord) {
            list.addAll(organizeService.getPageList(new ArrayList<>(), pagination, true));
        }else {
            String parentId = "0".equals(id)?"-1":id;
            List<OrganizeEntity> parentList = organizeService.getListByParentId(parentId);
            if(StringUtil.isNotEmpty(pagination.getType())) {
                list = list.stream().filter(t->t.getCategory().equals(pagination.getType())).collect(Collectors.toList());
            }
            list.addAll(parentList);
        }
        for (OrganizeEntity entity : list) {
            OrganizeSelectorVO vo = JsonUtil.getJsonToBean(entity, OrganizeSelectorVO.class);
            vo.setIcon(PermissionConst.COMPANY.equals(entity.getCategory()) ? "icon-ym icon-ym-tree-organization3" : "icon-ym icon-ym-tree-department1");
            vo.setHasChildren(true);
            vo.setIsLeaf(false);
            vo.setChildren(new ArrayList<>());
            vo.setOrganize(organizeService.getFullNameByOrgIdTree(orgIdNameMaps, entity.getOrganizeIdTree(), "/"));
            vo.setOrganizeIds(organizeService.getOrgIdTree(entity));
            listVO.add(vo);
        }
        return listVO;
    }



    // -------------------导入导出--------------------

    @Operation(summary = "模板下载")
    @SaCheckPermission("permission.position")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        OrgColumnMap columnMap = new OrgColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        keyMap.remove("parentId");
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(false, 0);
        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.position")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        return ExcelTool.uploader();
    }

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

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

    @Operation(summary = "导入数据")
    @SaCheckPermission("permission.position")
    @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<OrganizeEntity> addList = new ArrayList<>();
        List<Map<String, Object>> failList = new ArrayList<>();
        // 对数据做校验
        this.validateImportData(listData, addList, failList);

        //正常数据插入
        for (OrganizeEntity each : addList) {
            organizeService.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);
    }

    @Operation(summary = "导出Excel")
    @SaCheckPermission("permission.position")
    @GetMapping("/ExportData")
    public ActionResult ExportData(PaginationPosition pagination) throws IOException {
        if (StringUtil.isEmpty(pagination.getSelectKey())) {
            return ActionResult.fail(MsgCode.IMP011.get());
        }
        String[] keys = pagination.getSelectKey();
        //获取数据
        String type = Objects.equals(pagination.getDataType(), 0) ? "" : Objects.equals(pagination.getDataType(), 1) ? PermissionConst.COMPANY : PermissionConst.DEPARTMENT;
        //获取当前用户的所有可见组织
        List<Map<String, Object>> realList = organizeService.getOrgTreeList(type, pagination.getKeyword());

        //获取字段
        OrgColumnMap columnMap = new OrgColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(pagination.getDataType());
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(true, pagination.getDataType());
        ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(Arrays.asList(keys)).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<OrganizeEntity> addList, List<Map<String, Object>> failList) {
        OrgColumnMap columnMap = new OrgColumnMap();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().isNull(OrganizeEntity::getDeleteMark);
        queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode).orderByDesc(OrganizeEntity::getCreatorTime);
        List<OrganizeEntity> allOrg = organizeService.list(queryWrapper);
        Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
        Map<String, Object> userNameMap = userService.getUserNameAndIdMap();

        List<DictionaryDataEntity> enList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.ENTERPRISE_NATURE.getDictionaryTypeId());
        Map<String, String> enMap = enList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));
        List<DictionaryDataEntity> itList = dictionaryDataApi.getListByTypeDataCode(DictionaryDataEnum.INDUSTRY_TYPE.getDictionaryTypeId());
        Map<String, String> itMap = itList.stream().collect(Collectors.toMap(DictionaryDataEntity::getFullName, DictionaryDataEntity::getId));

        Map<String, String> newOrgTreeNameAndId = new HashMap<>();
        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 category = "";
            if (eachMap.get("category") != null && StringUtil.isNotEmpty(eachMap.get("category").toString())) {
                if ("公司".equals(eachMap.get("category").toString())) {
                    category = PermissionConst.COMPANY;
                } else if ("部门".equals(eachMap.get("category").toString())) {
                    category = PermissionConst.DEPARTMENT;
                } else {
                    errInfo.add("找不到该类型值");
                }
            } else {
                errInfo.add("类型" + "不能为空");
            }
            if (errInfo.length() > 0) {
                eachMap.put("errorsInfo", errInfo.toString());
                failList.add(eachMap);
                continue;
            }
            realMap.put("category", category);
            boolean isOrg = PermissionConst.COMPANY.equals(category) ? true : false;

            for (String column : keyMap.keySet()) {
                Object valueObj = eachMap.get(column);
                String value = valueObj == null ? null : String.valueOf(valueObj);
                String columnName = keyMap.get(column);
                String thisCategory = isOrg ? PermissionConst.COMPANY : PermissionConst.DEPARTMENT;
                String preName = "";
//                String preName = eachMap.get("category").toString();
                switch (column) {
                    case "fullName":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(preName + columnName + "不能为空");
                            break;
                        }
                        if (value.length() > 50) {
                            errInfo.add(preName + columnName + "值超出最多输入字符限制");
                            break;
                        }
                        if (!value.contains("/")) {
                            errInfo.add("顶级公司已存在");
                            break;
                        }
                        int index = value.lastIndexOf("/");
                        String parentName = value.substring(0, index);
                        String fullName = value.substring(index + 1);

                        //库里寻找上级
                        String parentId = "";
                        String organizeIdTree = "";
                        //部门下不能创建公司报错后跳出双重循环
                        List<String> orgIds = new ArrayList<>();
                        for (String key : allOrgsTreeName.keySet()) {
                            String name = allOrgsTreeName.get(key).toString();
                            if (name.equals(parentName)) {
                                String substring = key.lastIndexOf(",") > 0 ? key.substring(key.lastIndexOf(",") + 1) : key;
                                orgIds.add(substring);
                            }
                        }
                        if (orgIds.size() == 2) {
                            OrganizeEntity thisOrg = organizeService.getById(orgIds.get(0));
                            if (!PermissionConst.COMPANY.equals(thisOrg.getCategory())) {
                                thisOrg = organizeService.getById(orgIds.get(1));
                            }
                            parentId = thisOrg.getId();
                            organizeIdTree = thisOrg.getOrganizeIdTree();
                        } else if (orgIds.size() == 1) {
                            OrganizeEntity thisOrg = organizeService.getById(orgIds.get(0));
                            if (isOrg && !PermissionConst.COMPANY.equals(thisOrg.getCategory())) {
                                errInfo.add("部门下不能创建公司");
                                break;
                            }
                            parentId = thisOrg.getId();
                            organizeIdTree = thisOrg.getOrganizeIdTree();
                        } else {
                            errInfo.add("找不到该所属组织");
                            break;
                        }
                        //当前导入excel里寻找上级
                        if (newOrgTreeNameAndId.containsKey(parentName)) {
                            organizeIdTree = newOrgTreeNameAndId.get(parentName);
                            List<String> list = Arrays.asList(organizeIdTree.split(","));
                            parentId = list.get(list.size() - 1);
                        }
                        if (StringUtil.isEmpty(parentId)) {
                            errInfo.add("找不到该所属组织");
                            break;
                        }
                        //库里重复
                        long fullNameCount = allOrg.stream().filter(t -> t.getFullName().equals(fullName) && thisCategory.equals(t.getCategory())).count();
                        if (fullNameCount > 0) {
                            errInfo.add(preName + columnName + "值已存在");
                            break;
                        }
                        //表格内重复
                        fullNameCount = addList.stream().filter(t -> t.getFullName().equals(fullName) && thisCategory.equals(t.getCategory())).count();
                        if (fullNameCount > 0) {
                            errInfo.add(preName + columnName + "值已存在");
                            break;
                        }
                        realMap.put("parentId", parentId);
                        realMap.put("organizeIdTree", organizeIdTree);
                        realMap.put("fullName", fullName);
                        break;
                    case "enCode":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(preName + columnName + "不能为空");
                        }
                        if (value.length() > 50) {
                            errInfo.add(preName + columnName + "值超出最多输入字符限制");
                        }
                        if (!RegexUtils.checkEnCode(value)) {
                            errInfo.add(columnName + "只能输入英文、数字和小数点且小数点不能放在首尾");
                        }
                        //库里重复
                        long enCodeCount = allOrg.stream().filter(t -> t.getEnCode().equals(value)).count();
                        if (enCodeCount > 0) {
                            errInfo.add(preName + columnName + "值已存在");
                            break;
                        }
                        //表格内重复
                        enCodeCount = addList.stream().filter(t -> t.getEnCode().equals(value)).count();
                        if (enCodeCount > 0) {
                            errInfo.add(preName + columnName + "值已存在");
                            break;
                        }
                        break;
                    case "enterpriseNature":
                        //公司性质
                        if (StringUtil.isNotEmpty(value) && isOrg) {
                            if (enMap.containsKey(valueObj.toString())) {
                                realMap.put("enterpriseNature", enMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "industry":
                        //所属行业
                        if (StringUtil.isNotEmpty(value) && isOrg) {
                            if (itMap.containsKey(valueObj.toString())) {
                                realMap.put("industry", itMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName + "值");
                            }
                        }
                        break;
                    case "foundedTime":
                        if (StringUtil.isNotEmpty(value) && isOrg) {
                            Date date = DateUtil.stringToDates(value);
                            if (date == null) {
                                errInfo.add(columnName + "值不正确");
                                break;
                            }
                            realMap.put("foundedTime", date);
                        }
                        break;
                    case "managerId":
                        if (StringUtil.isNotEmpty(value) && !isOrg) {
                            if (userNameMap.containsKey(value)) {
                                realMap.put("managerId", userNameMap.get(value));
                            } else {
                                errInfo.add("找不到该" + columnName);
                            }
                        }
                        if (isOrg) {
                            realMap.put("managerId", null);
                        }
                        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;
                    default:
                        break;
                }

            }
            if (errInfo.length() == 0) {
                OrganizeEntity organizeEntity = JsonUtil.getJsonToBean(realMap, OrganizeEntity.class);
                organizeEntity.setCreatorTime(new Date());
                String uuid = RandomUtil.uuId();
                organizeEntity.setId(uuid);
                organizeEntity.setOrganizeIdTree(organizeEntity.getOrganizeIdTree().replace("/", ","));
                newOrgTreeNameAndId.put(eachMap.get("fullName").toString(), organizeEntity.getOrganizeIdTree() + "," + uuid);
                if (isOrg) {
                    OrganizeCrModel propJson = JsonUtil.getJsonToBean(realMap, OrganizeCrModel.class);
                    organizeEntity.setPropertyJson(JSONObject.toJSONString(propJson));
                }
                addList.add(organizeEntity);
            } else {
                eachMap.put("errorsInfo", errInfo.toString());
                failList.add(eachMap);
            }
        }
    }

    /**
     * 获取下拉框
     *
     * @return
     */
    private Map<String, String[]> getOptionMap() {
        Map<String, String[]> optionMap = new HashMap<>();
        //类型
        String[] typeMap = new String[]{"公司", "部门"};
        optionMap.put("category", typeMap);
        //企业性质
        List<DictionaryDataEntity> enList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.ENTERPRISE_NATURE.getDictionaryTypeId());
        String[] enterpriseNature = enList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("enterpriseNature", enterpriseNature);
        //行业类别
        List<DictionaryDataEntity> itList = dictionaryDataApi.getByTypeCodeEnable(DictionaryDataEnum.INDUSTRY_TYPE.getDictionaryTypeId());
        String[] industry = itList.stream().map(DictionaryDataEntity::getFullName).toArray(String[]::new);
        optionMap.put("industry", industry);
        return optionMap;
    }

}

