/*
 * Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yifu.cloud.plus.v1.yifu.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDept;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDeptRelation;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.DeptSortVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.DeptTreeSelectVO;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysDeptMoveVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysDeptVo;
import com.yifu.cloud.plus.v1.yifu.admin.constants.UserDeptPermConstants;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysDeptMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysUserMapper;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDeptRelationService;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDeptService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.UserPermissionVo;
import com.yifu.cloud.plus.v1.yifu.common.ldap.util.LdapUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2019/2/1
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

	private final SysDeptRelationService sysDeptRelationService;

	private final LdapUtil ldapUtil;

	private final SysUserMapper sysUserMapper;

	private final RedisUtil redisUtil;

	/**
	 * 添加信息部门
	 * @param dept 部门
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveDept(SysDept dept) {
		SysDept sysDept = new SysDept();
		BeanUtils.copyProperties(dept, sysDept);
		this.save(sysDept);
		sysDeptRelationService.saveDeptRelation(sysDept);
		return Boolean.TRUE;
	}

	/**
	 * 删除部门
	 * @param id 部门 ID
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDeptById(Long id) {
		// 级联删除部门
		List<Long> idList = sysDeptRelationService
				.list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, id)).stream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());

		if (CollUtil.isNotEmpty(idList)) {
			this.removeByIds(idList);
		}

		// 删除部门级联关系
		sysDeptRelationService.removeDeptRelationById(id);
		return Boolean.TRUE;
	}

	/**
	 * 更新部门
	 * @param sysDept 部门信息
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateDeptById(SysDept sysDept) {
		// 更新部门状态
		this.updateById(sysDept);
		// 更新部门关系
		SysDeptRelation relation = new SysDeptRelation();
		relation.setAncestor(sysDept.getParentId());
		relation.setDescendant(sysDept.getDeptId());
		sysDeptRelationService.updateDeptRelation(relation);
		return Boolean.TRUE;
	}

	@Override
	public List<Long> listChildDeptId(Long deptId) {
		List<SysDeptRelation> deptRelations = sysDeptRelationService.list(Wrappers.<SysDeptRelation>lambdaQuery()
				.eq(SysDeptRelation::getAncestor, deptId).ne(SysDeptRelation::getDescendant, deptId));
		if (CollUtil.isNotEmpty(deptRelations)) {
			return deptRelations.stream().map(SysDeptRelation::getDescendant).collect(Collectors.toList());
		}
		return new ArrayList<>();
	}

	/**
	 * 查询全部部门树
	 * @return 树
	 */
	@Override
	public List<Tree<Long>> listDeptTrees() {
		return getDeptTree(this.list(Wrappers.emptyWrapper()), 0L);
	}

	/**
	 * 查询用户部门树
	 * @return
	 */
	@Override
	public List<Tree<Long>> listCurrentUserDeptTrees() {
		Long deptId = SecurityUtils.getUser().getDeptId();
		List<Long> descendantIdList = sysDeptRelationService
				.list(Wrappers.<SysDeptRelation>query().lambda().eq(SysDeptRelation::getAncestor, deptId)).stream()
				.map(SysDeptRelation::getDescendant).collect(Collectors.toList());

		List<SysDept> deptList = baseMapper.selectBatchIds(descendantIdList);
		Optional<SysDept> dept = deptList.stream().filter(item -> item.getDeptId().intValue() == deptId).findFirst();
		return getDeptTree(deptList, dept.isPresent() ? dept.get().getParentId() : 0L);
	}

	/**
	 * 构建部门树
	 * @param depts 部门
	 * @param parentId 父级id
	 * @return
	 */
	private List<Tree<Long>> getDeptTree(List<SysDept> depts, Long parentId) {
		List<TreeNode<Long>> collect = depts.stream().filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
				.sorted(Comparator.comparingInt(SysDept::getSortOrder)).map(dept -> {
					TreeNode<Long> treeNode = new TreeNode();
					treeNode.setId(dept.getDeptId());
					treeNode.setParentId(dept.getParentId());
					treeNode.setName(dept.getName());
					treeNode.setWeight(dept.getSortOrder());
					// 扩展属性
					Map<String, Object> extra = new HashMap<>(4);
					extra.put("createTime", dept.getCreateTime());
					treeNode.setExtra(extra);
					return treeNode;
				}).collect(Collectors.toList());

		return TreeUtil.build(collect, parentId);
	}

	/**
	 * 从ldap中获取部门
	 * @return R
	 */
	@Override
	public R<Boolean> updateDeptByLdap() {
		List<SearchResultEntry> entryList = ldapUtil.getAllPersonNamesWithTraditionalWay();
		List<Map<String,Object>> updUserList = new ArrayList<>();
		for (SearchResultEntry entry : entryList) {
			String dn = entry.getDN();
			String userId = "";
			if (dn.contains("uid")) {
				userId = dn.substring(4, dn.indexOf(",", 1));
				dn = dn.substring(dn.indexOf(",", 1) + 1);
			}
			List<String> saveDnList = Arrays.stream(dn.split(",")).filter(e -> (e.contains("ou=") && !e.equals("ou=wanxin"))).collect(Collectors.toList());
			String deptName = saveDnList.get(0).replace("ou=", "");
			int size = saveDnList.size();
			if (size == 1) {
				SysDept sysDept = baseMapper.selectDeptDn(dn);
				if (null == sysDept) {
					if (StringUtils.isEmpty(userId)) {
						SysDept ins = baseMapper.selectCountId(Long.valueOf(entry.getAttributeValue("x-ouid")));
						if (Common.isNotNull(ins)) {
							ins.setName(deptName);
							ins.setDeptDn(dn);
							baseMapper.updateDeptById(ins);
						} else {
							SysDept insertSysDept = new SysDept();
							insertSysDept.setName(deptName);
							insertSysDept.setParentId(0L);
							insertSysDept.setDeptDn(dn);
							if (Common.isNotNull(entry.getAttributeValue("x-ouid"))) {
								insertSysDept.setDeptId(Long.valueOf(entry.getAttributeValue("x-ouid")));
							}
							baseMapper.insert(insertSysDept);
						}
					}
				} else {
					sysDept.setName(deptName);
					baseMapper.updateDeptById(sysDept);
				}
			} else {
				try {
					SysDept sysDept = this.getOne(Wrappers.<SysDept>query().lambda().eq(SysDept::getDeptDn, dn.substring(dn.indexOf("ou=", 2), dn.length())));
					if (null != sysDept) {
						SysDept sysDeptCount = baseMapper.selectDeptDn(dn);
						if (null == sysDeptCount) {
							if (StringUtils.isEmpty(userId)) {
								SysDept ins = baseMapper.selectCountId(Long.valueOf(entry.getAttributeValue("x-ouid")));
								if (Common.isNotNull(ins)) {
									ins.setName(deptName);
									ins.setDeptDn(dn);
									ins.setParentId(sysDept.getDeptId());
									baseMapper.updateDeptById(ins);
								} else {
									SysDept insertSysDept = new SysDept();
									insertSysDept.setName(deptName);
									insertSysDept.setParentId(sysDept.getDeptId());
									insertSysDept.setDeptDn(dn);
									if (Common.isNotNull(entry.getAttributeValue("x-ouid"))) {
										insertSysDept.setDeptId(Long.valueOf(entry.getAttributeValue("x-ouid")));
									}
									baseMapper.insert(insertSysDept);
								}
							}
						} else {
							if (!StringUtils.isEmpty(userId)) {
								Map<String,Object> map = new HashMap<>();
								map.put("userId",userId);
								map.put("deptId",sysDeptCount.getDeptId());
								map.put("deptName",deptName);
								updUserList.add(map);
							}else {
								sysDeptCount.setName(deptName);
								sysDeptCount.setParentId(sysDept.getDeptId());
								sysDeptCount.setDeptDn(dn);
								baseMapper.updateDeptById(sysDeptCount);
							}
						}
					}
				} catch (Exception e) {
					log.info("更新异常：" + e.getMessage());
					return R.failed("同步信息失败！");
				}
			}
		}
		//更新用户信息
		if (!updUserList.isEmpty()) {
			sysUserMapper.updateUser(updUserList);
		}
		return R.ok();
	}

	/**
	 * 客户服务平台——获取部门树（用于下拉选择）
	 *
	 * @param dept 部门信息
	 * @return 下拉树结构列表
	 */
	@Override
	public List<DeptTreeSelectVO> cspDeptTreeSelect(SysDeptVo dept) {
		List<DeptTreeSelectVO> cspDeptTree = new ArrayList<>();
		// 获取部门列表
		List<SysDeptVo> sysDeptList = baseMapper.cspDeptList(dept);
		if(Common.isNotNull(sysDeptList)){
			// 组装部门树
			List<SysDeptVo> deptTrees = buildDeptTree(sysDeptList);
			if(Common.isNotNull(deptTrees)){
				// 数据库查到的对象到视图对象的映射
				cspDeptTree = deptTrees.stream().map(DeptTreeSelectVO::new).collect(Collectors.toList());
			}
		}
		return cspDeptTree;
	}

	/**
	 * 客户服务平台——获取部门树（带部门下人数）
	 * @param dept 部门信息
	 * @return 部门树列表
	 */
	@Override
	public List<DeptTreeSelectVO> cspDeptTree(SysDeptVo dept) {
		List<DeptTreeSelectVO> cspDeptTree = new ArrayList<>();
		// 获取部门列表带用户数量
		List<SysDeptVo> sysDeptList = baseMapper.cspDeptUserList(dept);
		if(Common.isNotNull(sysDeptList)){
			// 组装部门树
			List<SysDeptVo> deptTrees = buildDeptTree(sysDeptList);
			if(Common.isNotNull(sysDeptList)){
				// 数据库查到的对象到视图对象的映射
				cspDeptTree = deptTrees.stream().map(DeptTreeSelectVO::new).collect(Collectors.toList());
			}
		}
		return cspDeptTree;
	}

	/**
	 * 客户服务平台——获取部门树（带部门下人数）
	 * @param dept 部门信息
	 * @param authority 用户在当前项目下的权限
	 * @return 部门树列表
	 */
	@Override
	public List<DeptTreeSelectVO> cspRosterTree(SysDeptVo dept, UserPermissionVo authority) {
		List<DeptTreeSelectVO> cspDeptTree = new ArrayList<>();
		List<SysDeptVo> sysDeptList = new ArrayList<>();
		// 有全部权限
		if(authority.isHaveAll()){
			sysDeptList = baseMapper.cspDeptList(dept);
		} else {
			// 获取用户部门集合
			Set<String> allDepartIdSet = new HashSet<>();
			Set<String> departIdSet = authority.getDepartIdSet();
			if(Common.isEmpty(departIdSet)){
				return cspDeptTree;
			}
			List<SysDeptVo> deptVoList = baseMapper.cspDeptListByDeptIdSet(dept, departIdSet);
			if(Common.isNotNull(deptVoList)){
				// 将指定部门和祖级部门都存到一个集合里
				for (SysDeptVo deptVo : deptVoList) {
					// 先存当前部门ID
					allDepartIdSet.add(deptVo.getDeptId().toString());
					String ancestors = deptVo.getAncestors();
					if(Common.isNotNull(ancestors)){
						String[] ancestorArr = ancestors.split(CommonConstants.COMMA_STRING);
						Set<String> ancestorDeptIdSet = Arrays.stream(ancestorArr).collect(Collectors.toSet());
						if(Common.isNotNull(ancestorDeptIdSet)){
							allDepartIdSet.addAll(ancestorDeptIdSet);
						}
					}
				}
			}
			sysDeptList = baseMapper.cspDeptListByDeptIdSet(dept, allDepartIdSet);
		}

		if(Common.isNotNull(sysDeptList)){
			Map<String,Integer> deptPeopleNumMap = dept.getDeptPeopleNumMap();
			for (SysDeptVo deptVo : sysDeptList) {
				Integer peopleNum = deptPeopleNumMap.get(deptVo.getDeptId().toString());
				if(Common.isEmpty(peopleNum)){
					peopleNum = 0;
				}
				deptVo.setPeopleNum(peopleNum.toString());
			}

			// 组装部门树
			List<SysDeptVo> deptTrees = buildDeptTree(sysDeptList);
			if(Common.isNotNull(sysDeptList)){
				// 数据库查到的对象到视图对象的映射
				cspDeptTree = deptTrees.stream().map(DeptTreeSelectVO::new).collect(Collectors.toList());
			}
		}
		return cspDeptTree;
	}

	/**
	 * 客户服务平台——组装部门树
	 *
	 * @param sysDeptList 部门列表
	 * @return 下拉树结构列表
	 */
	private List<SysDeptVo> buildDeptTree(List<SysDeptVo> sysDeptList) {
		List<SysDeptVo> returnList = new ArrayList<>();

		List<Long> tempDeptIdList = new ArrayList<>();
		for (SysDeptVo dept : sysDeptList) {
			tempDeptIdList.add(dept.getDeptId());
		}

		for (Iterator<SysDeptVo> iterator = sysDeptList.iterator(); iterator.hasNext();) {
			SysDeptVo dept = (SysDeptVo) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempDeptIdList.contains(dept.getParentId())) {
				// 遍历该父节点的所有子节点
				recursionFn(sysDeptList, dept);
				returnList.add(dept);
			}
		}
		if (Common.isEmpty(returnList)) {
			returnList = sysDeptList;
		}
		return returnList;
	}

	/**
	 * 递归列表
	 */
	private void recursionFn(List<SysDeptVo> list, SysDeptVo t) {
		// 得到子节点列表
		List<SysDeptVo> childList = getChildList(list, t);
		t.setChildren(childList);
		for (SysDeptVo tChild : childList) {
			if (hasChild(list, tChild))
			{
				recursionFn(list, tChild);
			}
			int i = 0;
			int i1= 0;
			if(Common.isNotNull(tChild.getPeopleNum())){
				i =Integer.parseInt(tChild.getPeopleNum());
			}
			if(Common.isNotNull(t.getPeopleNum())){
				i1=Integer.parseInt(t.getPeopleNum());
			}
			int i2=i+i1;
			String i3=String.valueOf(i2);
			t.setPeopleNum(i3);
		}
	}

	/**
	 * 得到子节点列表
	 */
	private List<SysDeptVo> getChildList(List<SysDeptVo> list, SysDeptVo t)
	{
		List<SysDeptVo> tlist = new ArrayList<>();
		Iterator<SysDeptVo> it = list.iterator();
		while (it.hasNext())
		{
			SysDeptVo n = (SysDeptVo) it.next();
			if (Common.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
			{
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<SysDeptVo> list, SysDeptVo t)
	{
		return getChildList(list, t).size() > 0 ? true : false;
	}

	/**
	 * 客户服务平台——添加部门
	 *
	 * @param dept 部门信息
	 * @return 结果
	 */
	@Override
	public R<String> saveCspDept(SysDept dept) {
		if (Common.isEmpty(dept.getParentId())){
			dept.setParentId(0L);
		}
		SysDept nameInfo = baseMapper.checkDeptNameUnique(dept.getProjectNo(),dept.getName(), dept.getParentId());
		if (Common.isNotNull(nameInfo)) {
			return R.failed("已存在同级同名部门");
		}

		if(0L == dept.getParentId()){
			LambdaQueryWrapper<SysDept> deptQuery = Wrappers.<SysDept>lambdaQuery()
					.eq(SysDept::getParentId, 0L)
					.eq(SysDept::getProjectNo, dept.getProjectNo())
					.eq(SysDept::getDelFlag, CommonConstants.ZERO_STRING)
					.last(" limit 1 ");
			SysDept firstInfo = baseMapper.selectOne(deptQuery);
			if (Common.isNotNull(firstInfo)) {
				return R.failed("一个项目下只能有一个顶级部门");
			}
		}
		// 新增部门
		if(0L == dept.getParentId()){
			dept.setAncestors(CommonConstants.ZERO_STRING);
		} else {
			if(Common.isNotNull(dept.getParentId())){
				SysDept info = baseMapper.selectById(dept.getParentId());
				if (Common.isEmpty(info)) {
					return R.failed("父级部门未找到");
				}
				// 暂时不加这个限制
//				if (Common.isNotNull(info.getAncestors())){
//					String[] split = info.getAncestors().split(",");
//					if (split.length >= 6){
//						return R.failed("添加部门的层级超出限制,最多支持5级");
//					}
//				}
				dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
			}
		}
		dept.setClient(ClientNameConstants.CLIENT_CSP);
		this.save(dept);

		// 清理用户权限,重新获取项目下的用户的部门权限
		List<String> userNames = sysUserMapper.getCspUserByProjectNo(dept.getProjectNo());
		if (Common.isNotNull(userNames)){
			for (String us:userNames){
				redisUtil.remove(CacheConstants.USER_DETAILS +"::"+ us);
			}
		}
		return R.ok("创建成功");
	}

	/**
	 * 客户服务平台——编辑部门
	 *
	 * @param dept 部门信息
	 * @return 结果
	 */
	@Override
	public R<String> updateCspDept(SysDept dept) {
		SysDept findInfo = baseMapper.selectById(dept.getDeptId());
		if (Common.isEmpty(findInfo)) {
			return R.failed("部门未找到");
		}
		if(findInfo.getName().equals(dept.getName())){
			return R.failed("名称未发生变化，未做更新");
		}
		SysDept nameInfo = baseMapper.checkDeptNameUnique(findInfo.getProjectNo(),dept.getName(), findInfo.getParentId());
		if (Common.isNotNull(nameInfo) && nameInfo.getDeptId().longValue() != dept.getDeptId().longValue()) {
			return R.failed("已存在同级同名部门");
		}

		LambdaUpdateWrapper<SysDept> updateInfoWrapper = new LambdaUpdateWrapper<>();
		updateInfoWrapper.eq(SysDept::getDeptId, dept.getDeptId())
				.set(SysDept::getName, dept.getName())
				.set(SysDept::getUpdateTime, LocalDateTime.now());
		this.update(null, updateInfoWrapper);

		return R.ok("更新成功");
	}

	/**
	 * 客户服务平台——删除部门
	 *
	 * @param deptId 部门id
	 * @return 结果
	 */
	@Override
	public R<String> removeCspDeptById(Long deptId) {
		SysDept findInfo = baseMapper.selectById(deptId);
		if (Common.isEmpty(findInfo)) {
			return R.failed("部门未找到");
		}
		int hasChild = baseMapper.hasChildByDeptId(deptId);
		if (hasChild > 0) {
			return R.failed("存在下级部门,不允许删除");
		}
		int existUser = baseMapper.checkDeptExistUser(deptId);
		if (existUser > 0) {
			return R.failed("部门下仍然有员工，请调出所有员工后，删除部门");
		}
		this.removeById(deptId);

		// 清理用户权限,重新获取项目下的用户的部门权限
		List<String> userNames = sysUserMapper.getCspUserByProjectNo(findInfo.getProjectNo());
		if (Common.isNotNull(userNames)){
			for (String us:userNames){
				redisUtil.remove(CacheConstants.USER_DETAILS +"::"+ us);
			}
		}
		return R.ok("删除成功");
	}

	/**
	 * 客户服务平台——获取项目下部门总数
	 *
	 * @param projectNo 项目编码
	 * @return R<Integer> 部门总数
	 */
	@Override
	public Integer cspDeptCount(String projectNo) {
		return baseMapper.cspDeptCount(projectNo);
	}

	/**
	 * @Author fxj
	 * @Description 按项目对应部门查询客户服务平台的用户信息
	 * @Date 14:27 2025/2/26
	 * @Param
	 * @return
	 **/
	@Override
	public R<Boolean> cspUpdateDept(SysDeptMoveVo dept) {
		try {
			if(Common.isEmpty(dept)
					|| Common.isEmpty(dept.getDeptId())
					|| Common.isEmpty(dept.getParentId())
					|| Common.isEmpty(dept.getDeptSortList())){
				R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
			}
			if (CommonConstants.ZERO_STRING.equals(dept.getParentId())){
				return R.failed(UserDeptPermConstants.DEPT_MOVE_FORBIDDEN);
			}
			SysDept parentDept = baseMapper.selectById(dept.getParentId());
			if (Common.isEmpty(parentDept)){
				return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
			}
			SysDept updateEntity = baseMapper.selectById(dept.getDeptId());
			if (Common.isEmpty(updateEntity)){
				return R.failed(CommonConstants.PARAM_IS_NOT_ERROR);
			}
			String oldStr = updateEntity.getAncestors()+","+updateEntity.getDeptId();
			String newStr = parentDept.getAncestors()+","+parentDept.getDeptId()+","+updateEntity.getDeptId();
			updateEntity.setParentId(parentDept.getDeptId());
			updateEntity.setAncestors(parentDept.getAncestors()+","+parentDept.getDeptId());
			int res = baseMapper.updateById(updateEntity);
			if (res > 0){
				baseMapper.updateAllAncestors(parentDept.getProjectNo(),oldStr,newStr,updateEntity.getDeptId());
			}

			List<DeptSortVo> moveVos = dept.getDeptSortList();
			baseMapper.batchUpdateSort(moveVos);
			// 清理用户权限
			List<String> userNames = sysUserMapper.getCspUserByProjectNo(updateEntity.getProjectNo());
			if (Common.isNotNull(userNames)){
				for (String us:userNames){
					redisUtil.remove(CacheConstants.USER_DETAILS +"::"+ us);
				}
			}
		}catch (Exception e){
			log.error("客户服务平台机构变更异常",e);
			return R.failed(CommonConstants.UPDATE_DATA_FAIL);
		}
		return R.ok();
	}

	/**
	 * 客户服务平台——获取项目下已删除的部门
	 *
	 * @param projectNo
	 * @return R<String> 删除部门的ID集合
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@Override
	public String cspDelDeptIds(String projectNo) {
		String delDeptIds = "";
		List<SysDept> deptList = baseMapper.cspDelDeptIds(projectNo);
		if(Common.isNotNull(deptList)){
			for(SysDept dept : deptList){
				delDeptIds = delDeptIds.concat(",").concat(dept.getDeptId().toString());
			}
		}
		if(delDeptIds.length()>0){
			delDeptIds = delDeptIds.substring(1);
		}
		return delDeptIds;
	}
}
