package common.service.impl;

import common.model.Menu;
import common.repository.MenuRepository;
import common.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by mxq on 2017/12/21.
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<Menu> listAll() {
        List<Menu> result = new ArrayList<>();
        List<Menu> parentMenuList = menuRepository.listAllParentMenu();
        List<Menu> menuList = menuRepository.listAllSonMenu();
        Map<Long, List<Menu>> map = new HashMap<>();
        for(Menu m : menuList){
            if(map.containsKey(m.getParent())){
                List<Menu> list = map.get(m.getParent());
                list.add(m);
                map.put(m.getParent(),list);
            } else{
                List<Menu> list = new ArrayList<>();
                list.add(m);
                map.put(m.getParent(), list);
            }
        }

        for(Menu m : parentMenuList){
            m.setSons(map.get(m.getId()));
            result.add(m);
        }
        return result;
    }
}
