package com.zhgd.xmgl.modules.basicdata.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhgd.xmgl.modules.basicdata.entity.SystemDept;
import com.zhgd.xmgl.modules.basicdata.mapper.SystemDeptMapper;
import com.zhgd.xmgl.modules.basicdata.service.ISystemDeptService;
import com.zhgd.xmgl.security.SecurityUser;
import com.zhgd.xmgl.security.SecurityUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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

/**
 * @Description: 政府内部部门
 * @author： pds
 * @date：   2023-02-15
 * @version： V1.0
 */
@Service
public class SystemDeptServiceImpl extends ServiceImpl<SystemDeptMapper, SystemDept> implements ISystemDeptService {

    @Override
    public List<SystemDept> tree(Integer deptId) {
        SecurityUser user = SecurityUtil.getUser();
        List<SystemDept> list = this.list(Wrappers.<SystemDept>lambdaQuery()
                .eq(SystemDept::getType, user.getAccountType()).eq(SystemDept::getSn, user.getSn()));
        List<SystemDept> treeList = new ArrayList<>();
        if (deptId == 0) {
            treeList = list.stream().filter(d -> d.getParentId().equals(0)).collect(Collectors.toList());
            getTreeList(treeList, list);
        } else {
            treeList = list.stream().filter(d -> d.getDeptId().equals(deptId)).collect(Collectors.toList());
            getTreeList(treeList, list);
        }
        return treeList;
    }

    private List<SystemDept> getTreeList(List<SystemDept> treeList, List<SystemDept> list) {
        for (SystemDept systemDept : treeList) {
            List<SystemDept> children = this.list(Wrappers.<SystemDept>lambdaQuery().eq(SystemDept::getParentId, systemDept.getDeptId()));
            getTreeList(children, list);
            systemDept.setChildren(children);
        }
        return treeList;
    }
}
