package com.elephant.framework.galaxy.aroad.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.elephant.framework.galaxy.aroad.module.system.entity.Dept;
import com.elephant.framework.galaxy.aroad.module.system.entity.DeptRelation;
import com.elephant.framework.galaxy.aroad.module.system.mapper.DeptRelationMapper;
import com.elephant.framework.galaxy.aroad.module.system.service.DeptRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 部门关系表 服务实现类
 * </p>
 *
 * @author wangjian
 * @since 2019-02-21
 */
@Service
@AllArgsConstructor
public class DeptRelationServiceImpl extends ServiceImpl<DeptRelationMapper, DeptRelation> implements DeptRelationService {
    private final DeptRelationMapper deptRelationMapper;

    /**
     * 维护部门关系
     *
     * @param dept 部门
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertDeptRelation(Dept dept) {
        //增加部门关系表
        DeptRelation condition = new DeptRelation();
        condition.setDescendant(dept.getParentId());
        List<DeptRelation> relationList = deptRelationMapper
                .selectList(Wrappers.<DeptRelation>query().lambda()
                        .eq(DeptRelation::getDescendant, dept.getParentId()))
                .stream().map(relation -> {
                    relation.setDescendant(dept.getDeptId());
                    return relation;
                }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(relationList)) {
            this.saveBatch(relationList);
        }

        //自己也要维护到关系表中
        DeptRelation own = new DeptRelation();
        own.setDescendant(dept.getDeptId());
        own.setAncestor(dept.getDeptId());
        deptRelationMapper.insert(own);
    }

    /**
     * 通过ID删除部门关系
     *
     * @param id
     */
    @Override
    public void deleteAllDeptRealtion(Integer id) {
        baseMapper.deleteDeptRelationsById(id);
    }

    /**
     * 更新部门关系
     *
     * @param relation
     */
    @Override
    public void updateDeptRealtion(DeptRelation relation) {
        baseMapper.deleteDeptRelations(relation);
        baseMapper.insertDeptRelations(relation);
    }

}
