package com.storlead.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.result.Result;
import com.storlead.system.dto.CompanyDTO;
import com.storlead.system.util.SystemSettingCacheCheckUtil;
import com.storlead.user.pojo.dto.DepartmentParam;
import com.storlead.user.pojo.entity.CompanyEntity;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.vo.DepartmentTree;
import com.storlead.user.service.ICompanyService;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @program: sp-sales
 * @description:
 * @author: chenkq
 * @create: 2022-06-29 17:46
 */
@Api(tags = "平台中心 - 系统: 公司部门数据维护")
@RestController
@RequestMapping("/sys/dept")
@Log4j2
public class DeptApiController {

    @Resource
    private IDepartService departService;

    @Resource
    private IUserService userService;

    @Resource
    private ICompanyService companyService;

    @Resource
    private ISubCompanyService subCompanyService;
//    @ApiOperation("获取部门组织列")
//    @PostMapping("listPage")
//    public Result listPage(@RequestBody DepartmentParam p
//    aram) {
//        IPage page = new Page(param.getPageIndex(),param.getPageSize());
//        LambdaQueryWrapper<Dept> query = new LambdaQueryWrapper();
//        if (param.getOrgTypes() != null) {
//            query.in(Department::getOrgType,param.getOrgTypes());
//        }
//        if (param.getParentId() != null) {
//            Department depart = departmentService.getById(param.getParentId());
//            if (Objects.nonNull(depart)) {
//                query.likeLeft(Department::getOrgCode,depart.getOrgCode());
//            }
//        }
//        IPage<Department> depts = departmentService.page(page,query);
//        return Result.success(depts);
//    }
    @ApiOperation("通过公司id返回部门List")
    @PostMapping("getListBySub")
    public Result getListBySub(Long subCompanyId) {
        LambdaQueryWrapper<DeptEntity> deptQquery = new LambdaQueryWrapper<>();
        deptQquery.eq(DeptEntity::getIsDelete,0);
        deptQquery.eq(DeptEntity::getSubCompanyId,subCompanyId);
        List<DeptEntity> deptList = departService.list(deptQquery);
        return Result.result(deptList);
    }

    @ApiOperation("获取组织树")
    @PostMapping("scopelistTree")
    public Result scopelistTree(@RequestBody DepartmentParam param) {
        List<CompanyEntity> companys = new ArrayList<>();
        List<SubCompanyEntity> subCompanies = new ArrayList<>();
        List<DeptEntity> depts = new ArrayList<>();
        if (Objects.isNull(param.getOrgTypes())) {
            return Result.error("参数错误");
        }

        LambdaQueryWrapper<UserEntity> userQquery = new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getIsDelete,0);
        userQquery.eq(Objects.nonNull(param.getEnabled()),UserEntity::getEnabled,param.getEnabled());

        List<UserEntity> users = userService.listWithScope(userQquery);
        Set<Long> deptIds = new HashSet<>();
        Set<Long> subCompanyIds = new HashSet<>();
        Set<Long> companyIds = new HashSet<>();
        if (!CollectionUtils.isEmpty(users)) {

             deptIds = users.stream().map(UserEntity::getDeptId).collect(Collectors.toSet());
             subCompanyIds = users.stream().map(UserEntity::getSubCompanyId).collect(Collectors.toSet());
             companyIds = users.stream().map(UserEntity::getCompanyId).collect(Collectors.toSet());
        }

        Map<Long,String> usMap = userService.list().stream().collect(Collectors.toMap(UserEntity::getId,UserEntity::getRealName));
        List<DepartmentTree> pidls = Collections.EMPTY_LIST;
        List<DepartmentTree> trees = new ArrayList<>();
        //类型:10 集团,20:公司(分公司),30:部门,40:小组,50:雇员
        if (param.getOrgTypes().contains(Integer.valueOf(10)) && !CollectionUtils.isEmpty(companyIds)) {
            LambdaQueryWrapper<CompanyEntity> cuwp = new LambdaQueryWrapper<CompanyEntity>();
            cuwp.in(CompanyEntity::getId,companyIds);
            companys = companyService.list(cuwp);
            List<DepartmentTree> ls =  DepartmentTree.companyListToDepartmentTreeVoList(companys);
            if (!CollectionUtils.isEmpty(ls)) {
                pidls = ls;
                trees.addAll(ls);
            }
        }
        if (param.getOrgTypes().contains(Integer.valueOf(20)) && !CollectionUtils.isEmpty(subCompanyIds)) {
            LambdaQueryWrapper<SubCompanyEntity> subCompanyQquery = new LambdaQueryWrapper<SubCompanyEntity>().eq(SubCompanyEntity::getIsDelete,0);
            subCompanyQquery.eq(Objects.nonNull(param.getEnabled()),SubCompanyEntity::getEnabled,param.getEnabled());
            if (!CollectionUtils.isEmpty(subCompanyIds)) {
                subCompanyQquery.in(SubCompanyEntity::getId,subCompanyIds);
            }
            subCompanies = subCompanyService.list(subCompanyQquery);
            if (CollectionUtils.isEmpty(subCompanies)) {
                subCompanies.forEach(sc -> {
                    String realName = usMap.get(sc.getLeaderId());
                    sc.setLeaderName(StrUtil.isEmpty(realName) ? "" : realName);
                });
            }
            List<DepartmentTree> ls =  DepartmentTree.subCompanyListToDepartmentTreeVoList(subCompanies);
            if (!CollectionUtils.isEmpty(ls)) {
                if (CollectionUtils.isEmpty(pidls)) {
                    pidls = ls;
                }
                trees.addAll(ls);
            }
        }

        if (param.getOrgTypes().contains(Integer.valueOf(30)) && !CollectionUtils.isEmpty(deptIds)) {
            LambdaQueryWrapper<DeptEntity> dmap1= new LambdaQueryWrapper<>();
            dmap1.eq(Objects.nonNull(param.getEnabled()),DeptEntity::getEnabled,param.getEnabled());

            List<DeptEntity> allDepts = departService.list(dmap1);
            if (!CollectionUtils.isEmpty(allDepts)) {
                Map<Long, DeptEntity> allDeptMaps =  allDepts.stream().collect(Collectors.toMap(DeptEntity::getId, a -> a,(existing, replacement) -> existing));
                Set<Long> allParentIds = getParentDeptsForMultiple(deptIds, allDeptMaps);
                if (!CollectionUtils.isEmpty(allParentIds)) {
                    deptIds.addAll(allParentIds);
                }
            }
            LambdaQueryWrapper<DeptEntity> dmap= new LambdaQueryWrapper<>();
            dmap.in(DeptEntity::getId,deptIds);
            dmap1.eq(Objects.nonNull(param.getEnabled()),DeptEntity::getEnabled,param.getEnabled());

            depts = departService.list(dmap);
            if (CollectionUtils.isEmpty(depts)) {
                depts.forEach(d -> {
                    String realName = usMap.get(d.getManagerId());
                    d.setLeaderName(StrUtil.isEmpty(realName) ? "" : realName);
                });
            }
            List<DepartmentTree> ls =  DepartmentTree.deptListToDepartmentTreeVoList(depts);
            if (!CollectionUtils.isEmpty(ls)) {
                if (CollectionUtils.isEmpty(pidls)) {
                    pidls = ls;
                }
                trees.addAll(ls);
            }
        }

        Map<Long, List<UserEntity>> groupByGrade = new HashMap<>();
        if (!CollectionUtils.isEmpty(param.getOrgTypes()) && param.getOrgTypes().contains(99) && !CollectionUtils.isEmpty(depts)) {
            if (!CollectionUtils.isEmpty(users)) {
                groupByGrade = users.stream().collect(Collectors.groupingBy(UserEntity::getDeptId));
            }
        }
        List<DepartmentTree> newTrees = new ArrayList<>();
        for (DepartmentTree d : trees) {
            if (Integer.valueOf(30).equals(d.getType())) {
                d.setChildren(getEmployeeTree(groupByGrade.get(d.getId()),param.getCheckNodes()));
            }
            if (Objects.nonNull(param.getCheckNodes()) && param.getCheckNodes().contains(d.getType())) {
                d.setDisabled(false);
                d.setDisableCheckbox(false);
            }
            newTrees.add(d);
        }
        List<DepartmentTree> result =  createTreels(newTrees,pidls);;
        return Result.result(result);
    }


    @ApiOperation("获取组织树")
    @PostMapping("orgTree")
    public Result orgTree(@RequestBody DepartmentParam param) {
        param.setEnabled(null);
        return listTree(param);
    }

    @ApiOperation("获取组织树")
    @PostMapping("listTree")
    public Result listTree(@RequestBody DepartmentParam param) {
        if (StrUtil.isNotBlank(param.getScopeMenuId()) && !Integer.valueOf(1).equals(param.getReviewTag())) {
            return scopelistTree(param);
        }
        List<CompanyEntity> companys = Collections.EMPTY_LIST;
        List<SubCompanyEntity> subCompanies = Collections.EMPTY_LIST;
        List<DeptEntity> depts = Collections.EMPTY_LIST;
        if (Objects.isNull(param.getOrgTypes())) {
            return Result.error("参数错误");
        }
        Map<Long,String> usMap = userService.list().stream().collect(Collectors.toMap(UserEntity::getId,UserEntity::getRealName));
        List<DepartmentTree> pidls = Collections.EMPTY_LIST;
        List<DepartmentTree> trees = new ArrayList<>();
        //类型:10 集团,20:公司(分公司),30:部门,40:小组,50:雇员
        if (param.getOrgTypes().contains(Integer.valueOf(10))) {
            companys = companyService.list();
            List<DepartmentTree> ls =  DepartmentTree.companyListToDepartmentTreeVoList(companys);
            if (!CollectionUtils.isEmpty(ls)) {
                pidls = ls;
                trees.addAll(ls);
            }
        }
        if (param.getOrgTypes().contains(Integer.valueOf(20))) {
            LambdaQueryWrapper<SubCompanyEntity> subCompanyQquery = new LambdaQueryWrapper<SubCompanyEntity>().eq(SubCompanyEntity::getIsDelete,0);
            subCompanyQquery.eq(Objects.nonNull(param.getEnabled()),SubCompanyEntity::getEnabled,param.getEnabled());
            if (Objects.nonNull(param.getSubCompanyId())) {
                subCompanyQquery.eq(SubCompanyEntity::getId,param.getSubCompanyId());
            }
            subCompanies = subCompanyService.list(subCompanyQquery);
            if (CollectionUtils.isEmpty(subCompanies)) {
                subCompanies.forEach(sc -> {
                    String realName = usMap.get(sc.getLeaderId());
                    sc.setLeaderName(StrUtil.isEmpty(realName) ? "" : realName);
                });
            }
            List<DepartmentTree> ls =  DepartmentTree.subCompanyListToDepartmentTreeVoList(subCompanies);
            if (!CollectionUtils.isEmpty(ls)) {
                if (CollectionUtils.isEmpty(pidls)) {
                    pidls = ls;
                }
                trees.addAll(ls);
            }
        }

        if (param.getOrgTypes().contains(Integer.valueOf(30))) {
            LambdaQueryWrapper<DeptEntity> deptQquery = new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getIsDelete,0);
            deptQquery.eq(Objects.nonNull(param.getEnabled()),DeptEntity::getEnabled,param.getEnabled());
            if (Objects.nonNull(param.getDeptId())) {
                DeptEntity d = departService.getById(param.getDeptId());
                if (Objects.nonNull(d)) {
                    deptQquery.apply(" LOCATE(route_code,'"+d.getRouteCode()+"') = 1 ");
                }
            }
            depts = departService.list(deptQquery);
            if (CollectionUtils.isEmpty(depts)) {
                depts.forEach(d -> {
                    String realName = usMap.get(d.getManagerId());
                    d.setLeaderName(StrUtil.isEmpty(realName) ? "" : realName);
                });
            }
            List<DepartmentTree> ls =  DepartmentTree.deptListToDepartmentTreeVoList(depts);
            if (!CollectionUtils.isEmpty(ls)) {
                if (CollectionUtils.isEmpty(pidls)) {
                    pidls = ls;
                }
                trees.addAll(ls);
            }
        }

        Map<Long, List<UserEntity>> groupByGrade = new HashMap<>();
        if (!CollectionUtils.isEmpty(param.getOrgTypes()) && param.getOrgTypes().contains(99) && !CollectionUtils.isEmpty(depts)) {
            LambdaQueryWrapper<UserEntity> userQquery = new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getIsDelete,0);
            userQquery.eq(Objects.nonNull(param.getEnabled()),UserEntity::getEnabled,param.getEnabled());

            List<UserEntity> users = userService.list(userQquery);
            if (!CollectionUtils.isEmpty(users)) {
                groupByGrade = users.stream().collect(Collectors.groupingBy(UserEntity::getDeptId));
            }
        }
        List<DepartmentTree> newTrees = new ArrayList<>();
        for (DepartmentTree d : trees) {
            if (Integer.valueOf(30).equals(d.getType())) {
                d.setChildren(getEmployeeTree(groupByGrade.get(d.getId()),param.getCheckNodes()));
            }
            if (Objects.nonNull(param.getCheckNodes()) && param.getCheckNodes().contains(d.getType())) {
                d.setDisabled(false);
                d.setDisableCheckbox(false);
            }
            newTrees.add(d);
        }
        List<DepartmentTree> result =  createTreels(newTrees,pidls);;
        return Result.result(result);
    }

    public Set<Long> getParentDeptsForMultiple(Set<Long> deptIds, Map<Long, DeptEntity> allDepts) {
        Set<Long> allParentIds = new HashSet<>();
        Set<Long> currentLevel = new HashSet<>(deptIds);

        while (!currentLevel.isEmpty()) {
            Set<Long> nextLevel = new HashSet<>();
            for (Long deptId : currentLevel) {
                DeptEntity dept = allDepts.get(deptId);
                if (dept != null && dept.getPid() != null && dept.getPid() != 0) {
                    if (!allParentIds.contains(dept.getPid())) {
                        allParentIds.add(dept.getPid());
                        nextLevel.add(dept.getPid());
                    }
                }
            }
            currentLevel = nextLevel;
        }
        return allParentIds;
    }

    private List<DepartmentTree> createTreeVo(List<DepartmentTree> treels, DepartmentTree treeVo,Long topId) {
        List<DepartmentTree> trees = new ArrayList<>();
        for (DepartmentTree tree : treels) {

            /**
             * 处理公司,部门,用户id冲突无法满足组装通用树结构得问题 begin
             */
            if (Objects.nonNull(treeVo)
                    && (Integer.valueOf(10).equals(treeVo.getType())
                    && (!Integer.valueOf(20).equals(tree.getType()) && !Integer.valueOf(10).equals(tree.getType())))) {
                continue;
            }
            if (Objects.nonNull(treeVo)
                    && (Integer.valueOf(20).equals(treeVo.getType())
                    && !Integer.valueOf(30).equals(tree.getType()))) {
                continue;
            }
            if (Objects.nonNull(treeVo)
                    && (Integer.valueOf(30).equals(treeVo.getType())
                    && (!Integer.valueOf(30).equals(tree.getType())))) {
                continue;
            }

            Long pid = Objects.nonNull(topId) ? treeVo.getId() : Long.valueOf(0);
            Long parentId = tree.getParentId();

            if (Objects.nonNull(treeVo) && Integer.valueOf(20).equals(treeVo.getType()) && Integer.valueOf(30).equals(tree.getType()) ) {
                DeptEntity dept = (DeptEntity)tree.getArg();
                if (!Long.valueOf(0).equals(dept.getPid())) {
                    continue;
                }
            }
            else if (Objects.nonNull(treeVo) && Integer.valueOf(30).equals(treeVo.getType()) && Integer.valueOf(30).equals(tree.getType()) ) {
                DeptEntity deptp = (DeptEntity)treeVo.getArg();
                DeptEntity dept = (DeptEntity)tree.getArg();

                if (Long.valueOf(0).equals(dept.getPid())) {
                    continue;
                }
//                if (Long.valueOf(0).equals(deptp.getPid()) && Long.valueOf(0).equals(dept.getPid())) {
//                    continue;
//                }
            }
            if (pid.equals(parentId)) {
                trees.add(tree);
                List<DepartmentTree> childs =  createTreeVo(treels,tree,tree.getParentId());
                if (!CollectionUtils.isEmpty(childs)) {
                    if (tree.getChildren() != null) {
                        childs.addAll(tree.getChildren());
                    }
                    tree.setChildren(childs);
                }
            }
        }
        return trees;
    }

    private List<DepartmentTree> createTreels(List<DepartmentTree> treels, List<DepartmentTree>  pTrees) {
        List<DepartmentTree> trees = new ArrayList<>();
        trees.addAll(createTreeVo(treels,null,null));
        return trees;
    }


    public List<DepartmentTree> getEmployeeTree(List<UserEntity> users, List<Integer> checkNodes){
        if (CollectionUtils.isEmpty(users)) {
            return  null;
        }
        List<DepartmentTree> trees = new ArrayList<>();
        for (UserEntity d : users) {
            DepartmentTree departmentTree = new DepartmentTree();
            departmentTree.setId(d.getId());
            departmentTree.setParentId(d.getDeptId());
            departmentTree.setTitle(d.getRealName());
            departmentTree.setArg(d);
            departmentTree.setPhoto(d.getAvatar());
            departmentTree.setAvatar(d.getAvatar());
            departmentTree.setType(99);
            departmentTree.setExpand(false);
            if (Objects.nonNull(checkNodes) && checkNodes.contains(Integer.valueOf(99))) {
                departmentTree.setDisabled(false);
                departmentTree.setDisableCheckbox(false);
            }
            trees.add(departmentTree);
        }
        return trees;
    }


    @ApiOperation("新增部门")
    @PostMapping("save")
    public Result save(DeptEntity dept) {
        Result r = SystemSettingCacheCheckUtil.checkAddDataMode();
        if (!r.isSuccess()) {
            return r;
        }
        if (Objects.isNull(dept.getPid())) {
            dept.setPid(Long.valueOf(0));
        }
        if(Objects.isNull(dept.getId())) {
            dept.setDataSource(1);
            String topCode = "";
            LambdaQueryWrapper<DeptEntity> subQWrapper = new LambdaQueryWrapper();
            if (Long.valueOf(0).equals(dept.getPid())) {
                LambdaQueryWrapper<SubCompanyEntity> lm = new LambdaQueryWrapper();
                lm.eq(SubCompanyEntity::getId,dept.getSubCompanyId());
                lm.last("limit 1");
                SubCompanyEntity subCompany = subCompanyService.getOne(lm);
                if (Objects.isNull(subCompany)) {
                    return Result.error("部门需要挂载在在公司下面,请绑定部门公司");
                }
                dept.setCompanyId(subCompany.getCompanyId());
                subQWrapper.eq(DeptEntity::getSubCompanyId,subCompany.getId());
                topCode = subCompany.getRouteCode();
            } else {
                LambdaQueryWrapper<DeptEntity> lm = new LambdaQueryWrapper();
                lm.eq(DeptEntity::getId,dept.getPid());
                lm.last("limit 1");
                DeptEntity dept1 = departService.getOne(lm);
                if (Objects.isNull(dept1)) {
                    return Result.error("参数错误，未查到上级部门");
                }
                dept.setSubCompanyId(dept1.getSubCompanyId());
                dept.setCompanyId(dept1.getCompanyId());
                subQWrapper.eq(DeptEntity::getId,dept1.getId());
                topCode = dept1.getRouteCode();
            }
            subQWrapper.orderByDesc(DeptEntity::getRouteCode);
            subQWrapper.last("limit 1");
            DeptEntity dept1 = departService.getOne(subQWrapper);
            if (Objects.isNull(dept1)) {
                dept.setRouteCode(topCode+",100");
            }else {
                String [] routeCodes = dept1.getRouteCode().split(",");
                String lastCode = routeCodes[routeCodes.length-1];
                lastCode = String.valueOf(Integer.valueOf(lastCode)+1);
                routeCodes[routeCodes.length-1] = lastCode;
                String routeCode = StringUtils.join(routeCodes,",");
                dept.setRouteCode(routeCode);
            }
        }

        departService.saveOrUpdate(dept);
        return Result.ok();
    }

    @ApiOperation("分页查询部门")
    @PostMapping("pagelist")
    public Result save(CompanyDTO param) {
        IPage<DeptEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        IPage<DeptEntity> depts = departService.page(page);
        return Result.result(depts);
    }

    @ApiOperation("删除部门数据")
    @PostMapping("delete")
    public Result delete(Long [] ids) {
        if (ids == null || ids.length == 0) {
            return Result.error("参数错误");
        }
        Integer exist = userService.count(new LambdaQueryWrapper<UserEntity>().in(UserEntity::getDeptId, Arrays.asList(ids)));
        if (!Objects.equals(exist,Integer.valueOf(0))) {
            return Result.error("部门下有关联的员工,无法删除!");
        }
        departService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }


    @ApiOperation("设置部门领导")
    @PostMapping("setDepartManager")
    public Result delete(Long deptId ,Long managerId) {
        if (Objects.isNull(deptId)) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<DeptEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DeptEntity::getId,deptId);
        UserEntity user = userService.getById(managerId);
        if (Objects.nonNull(user)) {
            updateWrapper.set(DeptEntity::getManagerId,managerId);
            updateWrapper.set(DeptEntity::getLeaderName,user.getRealName());
        } else {
            updateWrapper.set(DeptEntity::getManagerId,null);
            updateWrapper.set(DeptEntity::getLeaderName,"");
        }
        DeptEntity deptMar = departService.getById(deptId);
        Boolean b =  departService.update(updateWrapper);
        if (b) {
            if (Objects.nonNull(deptMar)) {
                if (!managerId.equals(deptMar.getManagerId())) {
                    UserEntity oldUser = userService.getById(deptMar.getManagerId());
                    if (Objects.nonNull(oldUser) && !Integer.valueOf(1).equals(oldUser.getIsLeader()))  {
                        LambdaQueryWrapper userDeptLq =  new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getManagerId,deptMar.getManagerId()).ne(DeptEntity::getId,deptId);
                        Integer c = departService.count(userDeptLq);
                        LambdaUpdateWrapper<UserEntity> rmLeaderUpdate = new LambdaUpdateWrapper();
                        if (c > 0) {
                            rmLeaderUpdate.set(UserEntity::getIsLeader,Integer.valueOf(2));
                        } else {
                            rmLeaderUpdate.set(UserEntity::getIsLeader,Integer.valueOf(0));
                        }
                        rmLeaderUpdate.eq(UserEntity::getId,deptMar.getManagerId());
                        userService.update(rmLeaderUpdate);
                    }
                }
            }
            if (Integer.valueOf(1).equals(user.getIsLeader()) || Integer.valueOf(2).equals(user.getIsLeader())) {
                return Result.ok();
            }
            LambdaUpdateWrapper<UserEntity> userUpdate = new LambdaUpdateWrapper();
            userUpdate.set(UserEntity::getIsLeader,Integer.valueOf(2));
            userUpdate.eq(UserEntity::getId,managerId);
            userService.update(userUpdate);
        }
        return Result.ok();
    }

    @ApiOperation("设置部门分管领导")
    @PostMapping("setDepartSubManager")
    public Result delete(Long deptId,String subManagerIds) {
        if (Objects.isNull(deptId)) {
            return Result.error("参数错误");
        }
        LambdaUpdateWrapper<DeptEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DeptEntity::getId,deptId);
        updateWrapper.set(DeptEntity::getSubManagerIds,subManagerIds);
        departService.update(updateWrapper);
        return Result.ok();
    }

    @ApiOperation("矫正路由")
    @PostMapping("correctDeptRoute")
    public Result correctDeptRoute() {
        List<DeptEntity> depts = departService.list();
        List<DeptEntity> topDepts = depts.stream().filter(e -> Long.valueOf(0).equals(e.getPid())).collect(Collectors.toList());
        int code = 100;
        List<DeptEntity> deptEntities = new ArrayList<>();
        for (DeptEntity d:topDepts) {
            SubCompanyEntity subCompany = subCompanyService.getById(d.getSubCompanyId());
            String topRoute = subCompany.getRouteCode();
            String topRoute1 = topRoute+","+String.valueOf(code);
            d.setRouteCode(topRoute1);
            deptEntities.add(d);
            List<DeptEntity> ns = markRoute(d,depts);
            if (!CollectionUtils.isEmpty(ns)) {
                deptEntities.addAll(ns);
            }
            code ++;
        }
        departService.updateBatchById(deptEntities);
        Map<Long, String> map3 = deptEntities.stream().collect(Collectors.toMap(DeptEntity::getId, DeptEntity::getRouteCode, (u1, u2) -> u1));
        List<UserEntity> users = userService.list();
        for (UserEntity u:users) {
            u.setOrgRouteCode(map3.get(u.getDeptId()));
        }
        userService.updateBatchById(users);
        return Result.ok();
    }

    @ApiOperation("启用禁用部门")
    @PostMapping("enable")
    public Result setEnable(Long id,Boolean enable,Integer type) {
        if (id == null) {
            return Result.error("参数错误");
        }
        if (type == null) {
            return Result.error("参数错误");
        }
        if (type == 10) {
            return Result.error("无法禁用总公司");
        }
        if (type == 20) {

            LambdaUpdateWrapper<SubCompanyEntity> update = new LambdaUpdateWrapper();
            update.eq(SubCompanyEntity::getId,id);
            update.set(SubCompanyEntity::getEnabled,enable);
            Boolean re = subCompanyService.update(update);
            if (re) {
                // 下级部门同步禁用启用,用户同步
                LambdaUpdateWrapper<DeptEntity> update1 = new LambdaUpdateWrapper();
                update1.eq(DeptEntity::getSubCompanyId,id);
                update1.set(DeptEntity::getEnabled,enable);
                departService.update(update1);
                return Result.ok();
            } else {
                return Result.error("操作失败");
            }

        } else if (type == 30) {
            DeptEntity dept = departService.getById(id);
            if (Objects.isNull(dept)) {
                return Result.error("参数错误");
            }
            LambdaQueryWrapper<DeptEntity> query = new LambdaQueryWrapper();
            query.likeRight(DeptEntity::getRouteCode,dept.getRouteCode());
            query.eq(DeptEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            List<DeptEntity> deptls = departService.list(query);
            if (CollectionUtils.isEmpty(deptls)) {
                return Result.error("参数错误");
            }
            List<Long>  deptIds = deptls.stream().map(DeptEntity::getId).collect(Collectors.toList());
            // 下级部门同步禁用启用,用户同步
            LambdaUpdateWrapper<DeptEntity> update = new LambdaUpdateWrapper();
            update.in(DeptEntity::getId,deptIds);
            update.set(DeptEntity::getEnabled,enable);
            Boolean re =  departService.update(update);
            if (re) {
                return Result.ok();
            } else {
                return Result.error("操作失败");
            }
        } else {
            return Result.error("操作失败,参数错误");
        }
    }

    public List<DeptEntity> markRoute(DeptEntity d,List<DeptEntity> depts){
        List<DeptEntity> deptEntities = new ArrayList<>();
        int code = 100;
        List<DeptEntity> topDepts = depts.stream().filter(e -> e.getPid().equals(d.getId()) && e.getSubCompanyId().equals(d.getSubCompanyId())).collect(Collectors.toList());
        for (DeptEntity d1:topDepts) {
            String topRoute = d.getRouteCode();
            String topRoute1 = topRoute+","+String.valueOf(code);
            d1.setRouteCode(topRoute1);
            deptEntities.add(d1);
            List<DeptEntity> ns = markRoute(d1,depts);
            if (!CollectionUtils.isEmpty(ns)) {
                deptEntities.addAll(ns);
            }
            code++;
        }
        return deptEntities;
    }
}
