package com.yeejoin.equipmanage.service.impl;


import com.yeejoin.equipmanage.common.entity.OrgUsr;
import com.yeejoin.equipmanage.common.entity.dto.OrgUsrDto;
import com.yeejoin.equipmanage.mapper.OrgUsrMapper;
import com.yeejoin.equipmanage.service.IOrgUsrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

@Service
public class OrgUsrServiceImpl implements IOrgUsrService {

    private final Logger logger = LoggerFactory.getLogger(OrgUsrServiceImpl.class);

    @Autowired
    OrgUsrMapper orgUsrMapper;

    @Override
    public List<OrgUsrDto> getCompanyTree(){
        List<OrgUsr> list = orgUsrMapper.getCompanyTree();
        return buildCompanyTree(list);
    }

    public static List<OrgUsrDto> buildCompanyTree(List<OrgUsr> list) {
        List<OrgUsrDto> menuList = list.stream()
                .map(o -> new OrgUsrDto(String.valueOf(o.getSequenceNbr()), o.getBizOrgName(),
                        ObjectUtils.isEmpty(o.getParentId()) ? "0" : String.valueOf(o.getParentId()),
                        o.getBizOrgCode(), o.getCode(), o.getCanClick())).collect(Collectors.toList());
        List<OrgUsrDto> result = new ArrayList<>();
        Map<String, OrgUsrDto> map = new HashMap<>(menuList.size());
        menuList.forEach(e -> map.put(e.getId(), e));
        Set<? extends Map.Entry<String, ? extends OrgUsrDto>> entries = map.entrySet();
        entries.forEach(entry -> {
            OrgUsrDto value = entry.getValue();
            if (value != null) {
                OrgUsrDto treeDto = map.get(value.getParentId());
                if (treeDto != null) {
                    List<OrgUsrDto> children = treeDto.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        treeDto.setChildren(children);
                    }
                    children.add(value);
                } else {
                    result.add(value);
                }
            }
        });
        return result;
    }

}