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.dto.DeptTree;
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.DeptMapper;
import com.elephant.framework.galaxy.aroad.module.system.service.DeptRelationService;
import com.elephant.framework.galaxy.aroad.module.system.service.DeptService;
import com.elephant.framework.galaxy.aroad.util.SecurityUtils;
import com.elephant.framework.galaxy.aroad.util.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author wangjian
 * @since 2019-02-21
 */
@Service
@AllArgsConstructor
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    private final DeptRelationService deptRelationService;

    //部门映射 key:三级节点部门id  value:二级单位
    private final Map<Integer,Dept> deptMap;

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


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

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

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

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

    /**
     * 查询全部部门树
     *
     * @return 树
     */
    @Override
    public List<DeptTree> selectTree() {
        return getDeptTree(this.list(Wrappers.emptyWrapper()));
    }

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

        List<Dept> deptList = baseMapper.selectBatchIds(descendantIdList);
        return getDeptTree(deptList);
    }

    /**
     * 构建部门树
     *
     * @param depts 部门
     * @return
     */
    private List<DeptTree> getDeptTree(List<Dept> depts) {
        List<DeptTree> treeList = depts.stream()
                .filter(dept -> !dept.getDeptId().equals(dept.getParentId()))
                .map(dept -> {
                    DeptTree node = new DeptTree();
                    node.setId(dept.getDeptId());
                    node.setParentId(dept.getParentId());
                    node.setName(dept.getName());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.bulid(treeList, 0);
    }



    /** 
    * @Description:  获取部门映射 key:三级节点部门id  value:二级单位
    * @Param: [] 
    * @return: java.util.Map<java.lang.Integer,com.elephant.framework.galaxy.aroad.module.system.entity.Dept> 
    * @Author: songwenjie 
    * @Date: 2019/5/8 
    */ 
    private Map<Integer,Dept> getDeptMap(){
        //二级节点单位
        List<Dept> secondaryDepts = baseMapper.getDeptByParentId(1);
        List<Integer> secondaryDeptIds = secondaryDepts.stream()
                .map(x -> x.getDeptId())
                .collect(Collectors.toList());
        //三级节点部门
        List<Dept> tertiaryDepts = baseMapper.getDeptByParentIds(secondaryDeptIds);
        List<Integer> tertiaryDeptIds = tertiaryDepts.stream()
                .map(x -> x.getDeptId())
                .collect(Collectors.toList());

        //key:三级节点部门id  value:二级单位
        Map<Integer,Dept> deptMap = new HashMap<>();
        tertiaryDepts.forEach(t->{
            secondaryDepts.forEach(s->{
                if(t.getParentId() == s.getDeptId() ){
                    deptMap.put(t.getDeptId(),s);
                }
            });
        });
        return deptMap;
    }

    /** 
    * @Description: 根据部门id获取二级单位名称
    * @Param: [deptId] 
    * @return: java.lang.String 
    * @Author: songwenjie 
    * @Date: 2019/5/8 
    */ 
    public String getDeptName(int deptId){
        Dept dept = baseMapper.getDeptById(deptId)
                .stream()
                .findFirst()
                .get();
        if(dept == null || dept.getParentId() == 0){
            return "";
        }
        if(dept.getParentId() == 1){
            return dept.getName();
        }
        //部门映射 key:三级节点部门id  value:二级单位
        Map<Integer,Dept> deptMap = getDeptMap();
        if(deptMap.containsKey(
                dept.getDeptId())){
            return deptMap.get(
                    dept.getDeptId())
                    .getName();
        }
        return getDeptName(dept.getParentId());
    }

    /**
    * @Description: 判断是否是省厅
    * @Param: [deptId]
    * @return: boolean
    * @Author: songwenjie
    * @Date: 2019/5/9
    */
    public boolean isProvince(int deptId){
        Dept dept = baseMapper.getDeptById(deptId)
                .stream()
                .findFirst()
                .get();
        String type = dept.getType();
        if(type.equals("省厅") || type.equals("省厅部门")){
            return true;
        }
        return false;
    }
}
