package org.jeecg.modules.oroqen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.oroqen.entity.OroqenProductCategory;
import org.jeecg.modules.oroqen.mapper.OroqenProductCategoryMapper;
import org.jeecg.modules.oroqen.service.IOroqenProductCategoryService;
import org.springframework.stereotype.Service;

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

/**
 * @Description: 产品分类
 * @Author: jeecg-boot
 * @Date: 2025-01-08
 * @Version: V1.0
 */
@Service
public class OroqenProductCategoryServiceImpl extends ServiceImpl<OroqenProductCategoryMapper, OroqenProductCategory> implements IOroqenProductCategoryService {

    @Override
    public List<OroqenProductCategory> getCategoryTree() {
        QueryWrapper<OroqenProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("sort_order", "create_time");
        List<OroqenProductCategory> allCategories = this.list(queryWrapper);
        
        return buildTree(allCategories, null);
    }

    @Override
    public List<OroqenProductCategory> getChildrenByParentId(String parentId) {
        QueryWrapper<OroqenProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("sort_order", "create_time");
        return this.list(queryWrapper);
    }

    @Override
    public boolean checkCategoryCodeExists(String categoryCode, String excludeId) {
        QueryWrapper<OroqenProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_code", categoryCode);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return this.count(queryWrapper) > 0;
    }

    /**
     * 构建树形结构
     */
    private List<OroqenProductCategory> buildTree(List<OroqenProductCategory> allCategories, String parentId) {
        List<OroqenProductCategory> result = new ArrayList<>();
        
        List<OroqenProductCategory> children = allCategories.stream()
                .filter(category -> {
                    if (parentId == null) {
                        return category.getParentId() == null || "".equals(category.getParentId());
                    } else {
                        return parentId.equals(category.getParentId());
                    }
                })
                .collect(Collectors.toList());
        
        for (OroqenProductCategory category : children) {
            List<OroqenProductCategory> childList = buildTree(allCategories, category.getId());
            category.setChildren(childList);
            result.add(category);
        }
        
        return result;
    }
}