package com.ym.mec.cms.service.impl;

import com.ym.mec.cms.dal.dao.SysNewsInformationDao;
import com.ym.mec.cms.dal.dao.SysNewsTypeDao;
import com.ym.mec.cms.dal.entity.SysNewsInformation;
import com.ym.mec.cms.dal.entity.SysNewsType;
import com.ym.mec.cms.dal.entity.SysNewsTypeTree;
import com.ym.mec.cms.service.SysNewsTypeService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class SysNewsTypeServiceImpl extends BaseServiceImpl<Integer, SysNewsType> implements SysNewsTypeService {
    @Autowired
    private SysNewsTypeDao sysNewsTypeDao;
    @Autowired
    private SysNewsInformationDao informationDao;

    @Override
    public BaseDAO<Integer, SysNewsType> getDAO() {
        return sysNewsTypeDao;
    }

    @Override
    public List<SysNewsTypeTree> queryTree(Integer parentId) {
        if (parentId == null) {
            parentId = 0;
        }
        List<SysNewsTypeTree> sysNewsTypeList = queryByParentId(parentId);
        if (sysNewsTypeList != null && sysNewsTypeList.size() > 0) {
            for (SysNewsTypeTree type : sysNewsTypeList) {
                type.setSubTypeList(queryTree(type.getId()));
            }
        }

        return sysNewsTypeList;
    }

    @Override
    public List<SysNewsTypeTree> queryByParentId(Integer parentId) {
        if (parentId == null) {
            parentId = 0;
        }
        return sysNewsTypeDao.queryByParentId(parentId);
    }

    public List<SysNewsType> listWithTree(Integer id, String memo) {
        SysNewsType newsType = sysNewsTypeDao.get(id);
        List<SysNewsType> all = sysNewsTypeDao.findAll(null);

        all.forEach(e -> {
            List<SysNewsInformation> list = informationDao.queryBySubType(e.getId(), memo);
            if (CollectionUtils.isNotEmpty(list)) {
                e.setInformationList(list);
            } else {
                e.setInformationList(informationDao.queryBySubType(e.getId(), null));
            }
        });
        List<SysNewsType> treeMenus = all.stream()
                .filter((e) -> e.getParentId().equals(newsType.getParentId()))
                .map((menu) -> menu.setChildren(getChildren(menu, all)))
                .filter(e -> e.getId().equals(id))
                .collect(Collectors.toList());
        return treeMenus;
    }

    private List<SysNewsType> getChildren(SysNewsType rootMenu, List<SysNewsType> allMenus) {
        List<SysNewsType> childrenList = allMenus.stream().filter(e -> e.getParentId().equals(rootMenu.getId()))
                .map(menu -> menu.setChildren(getChildren(menu, allMenus)))
                .collect(Collectors.toList());
        return childrenList;
    }
}