package com.wzj.soopin.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzj.soopin.goods.convert.ProductCategoryConvert;
import com.wzj.soopin.goods.domain.entity.ProductCategory;
import com.wzj.soopin.goods.domain.vo.ProductCategoryVO;
import com.wzj.soopin.goods.mapper.ProductCategoryMapper;
import com.wzj.soopin.goods.service.ProductCategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * 商品分类Service业务层处理
 *
 * @author zcc
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {

    private final ProductCategoryConvert convert;

    @Override
    public List<ProductCategoryVO> tree(Wrapper<ProductCategory> wrapper) {
        List<ProductCategory> list = this.list(wrapper);
        return list.stream().filter(item -> item.getParentId() == 0).map(item -> {
            ProductCategoryVO productCategoryVO = convert.toVO(item);
            productCategoryVO.setChildren(
                list.stream().filter(child -> Objects.equals(child.getParentId(), item.getId()))
                    .map(convert::toVO)
                    .collect(Collectors.toList())
            );

            return productCategoryVO;
        }).toList();
    }


}
