package com.lutao.cloud.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 cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lutao.cloud.admin.api.entity.SysDept;
import com.lutao.cloud.admin.api.entity.SysDeptRelation;
import com.lutao.cloud.admin.mapper.SysDeptMapper;
import com.lutao.cloud.admin.mq.DeptMqMessage;
import com.lutao.cloud.admin.mq.UserMqMessage;
import com.lutao.cloud.admin.service.SysDeptRelationService;
import com.lutao.cloud.admin.service.SysDeptService;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.data.datascope.DataScope;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *

 * @since 2018-01-20
 */
@Service
@AllArgsConstructor
@Slf4j
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService{

	private final SysDeptRelationService sysDeptRelationService;

	private final SysDeptMapper deptMapper;

	private final DeptMqMessage deptMqMessage;


	/**
	 * 添加信息部门
	 * @param dept 部门
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public MessageInfo<Boolean> saveDept(SysDept dept){
		SysDept sysDept = new SysDept();
		BeanUtils.copyProperties(dept, sysDept);
		// TODO: 2021/12/9 guoyc 判断名称是否存在
		if (count(Wrappers.<SysDept>query().lambda().eq(SysDept::getName, dept.getName())) > 0){
			return MessageInfo.failed("添加失败，该部门名称已存在");
		}
		this.save(sysDept);
		sysDeptRelationService.insertDeptRelation(sysDept);
		// 发送消息
		deptMqMessage.sendMessage(sysDept, DeptMqMessage.DEPT_ADD);
		return MessageInfo.ok();
	}

	/**
	 * 删除部门
	 * @param id 部门 ID
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDeptById(Integer id){
		// 级联删除部门
		List<Integer> 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);
			deptMqMessage.sendMessage(idList,id, DeptMqMessage.DEPT_DELETE);
		}

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

	/**
	 * 更新部门
	 * @param sysDept 部门信息
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public MessageInfo<Boolean> updateDeptById(SysDept sysDept){
		// TODO: 2021/12/9 guoyc 判断名称是否存在
		if (count(Wrappers.<SysDept>query().lambda().eq(SysDept::getName, sysDept.getName()).ne(SysDept::getDeptId, sysDept.getDeptId())) > 0){
			return MessageInfo.failed("更新失败，该部门名称已存在");
		}
		// 更新部门状态
		this.updateById(sysDept);
		// 更新部门关系
		SysDeptRelation relation = new SysDeptRelation();
		relation.setAncestor(sysDept.getParentId());
		relation.setDescendant(sysDept.getDeptId());
		sysDeptRelationService.updateDeptRealtion(relation);
		deptMqMessage.sendMessage(sysDept, DeptMqMessage.DEPT_UPDATE);
		return MessageInfo.ok();
	}


	/**
	 * 查询全部部门树
	 * @return 树
	 */
	@Override
	public List<Tree<Integer>> selectTree(){
		// 查询全部部门
		List<SysDept> deptAllList = deptMapper.selectList(Wrappers.emptyWrapper());
		// 查询数据权限内部门
		List<Integer> deptOwnIdList = deptMapper.selectListByScope(Wrappers.emptyWrapper(), new DataScope()).stream()
				.map(SysDept::getDeptId).collect(Collectors.toList());
		// 权限内部门
		List<TreeNode<Integer>> collect = deptAllList.stream()
				.filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
				.sorted(Comparator.comparingInt(SysDept::getSort)).map(dept ->{
					TreeNode<Integer> treeNode = new TreeNode();
					treeNode.setId(dept.getDeptId());
					treeNode.setParentId(dept.getParentId());
					treeNode.setName(dept.getName());
					treeNode.setWeight(dept.getSort());
					// 有权限不返回标识
					treeNode.setExtra(MapUtil.of("isLock", !deptOwnIdList.contains(dept.getDeptId())));
					return treeNode;
				}).collect(Collectors.toList());

		return TreeUtil.build(collect, 0);
	}

}
