package com.reyun.service.impl;

import com.beust.jcommander.internal.Maps;
import com.google.common.collect.Lists;
import com.reyun.model.SyDicItem;
import com.reyun.repository.SyDicItemRepository;
import com.reyun.service.IDicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * description:
 *
 * @author nolan
 * @date 25/12/2017
 */
@Service
public class DicServiceImpl
        implements IDicService
{
    private static final String DIC_GAME_CODE = "02";
    private static final String DIC_APP_CODE = "04";

    @Autowired
    private SyDicItemRepository syDicItemRepository;

    @Override
    public Map<String, Object> findByCampaign() {
        Map<String, Object> rtnMap = Maps.newHashMap();

        List<SyDicItem> dicItemList = syDicItemRepository.findByDicCode(DIC_GAME_CODE);
        rtnMap.put("game", buildTree(null, dicItemList));

        dicItemList = syDicItemRepository.findByDicCode(DIC_APP_CODE);
        rtnMap.put("app", buildTree(null, dicItemList));

        rtnMap.put("test", "");
        return rtnMap;
    }

    @Override
    public List<SyDicItem> find(List<String> tagIds) {
        return this.syDicItemRepository.findByItemCodeIn(tagIds);
    }

    private List<SyDicItem> buildTree(String pid, List<SyDicItem> menuList) {
        if (pid == null) {
            List<SyDicItem> rtnList = Lists.newArrayList();
            List subSyDicItemList = menuList.stream().filter(menu -> menu.getItemPid() != null).collect(Collectors.toList());

            menuList.stream().filter(menu -> menu.getItemPid() == null).forEach(menu -> {
                List<SyDicItem> subList = buildTree(menu.getItemCode(), subSyDicItemList);
                menu.setChild(subList);

                rtnList.add(menu);
            });
            return rtnList;
        } else {
            List<SyDicItem> result = Lists.newArrayList();
            for (SyDicItem menuItem : menuList) {
                if (menuItem.getItemPid().equals(pid)) {
                    List<SyDicItem> children = buildTree(menuItem.getItemCode(), menuList);
                    if (null != children && 0 < children.size()) {
                        menuItem.setChild(children);
                    }
                    result.add(menuItem);
                }
            }
            return result;
        }
    }
}
