package com.xunqi.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.common.utils.PageUtils;
import com.xunqi.common.utils.Query;
import com.xunqi.gulimall.product.dao.PmsCategoryDao;
import com.xunqi.gulimall.product.entity.PmsCategoryEntity;
import com.xunqi.gulimall.product.service.PmsCategoryService;
import org.springframework.stereotype.Service;

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


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类以及子分类，以树形结构展示
     *
     * @return 分类列表
     */
    @Override
    public List<PmsCategoryEntity> listWithTree() {
        // 查询所有的分类
        List<PmsCategoryEntity> list = list();
        return list.stream()
                .filter(entity -> entity.getParentCid().equals(0L))
                .peek(entity -> entity.setChildren(getChildren(entity, list)))
                .sorted(Comparator.comparingInt(PmsCategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    private List<PmsCategoryEntity> getChildren(PmsCategoryEntity entity, List<PmsCategoryEntity> list) {
        List<PmsCategoryEntity> voList = new ArrayList<>();

        for (PmsCategoryEntity category : list) {
            if (entity.getParentCid().equals(category.getParentCid())) {
                voList.add(category);
            }
        }

        return voList;

    }
}