package com.aegis.knowledge.service.impl;

import com.aegis.knowledge.domain.KnowledgeCategory;
import com.aegis.knowledge.mapper.KnowledgeCategoryMapper;
import com.aegis.knowledge.service.IKnowledgeCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * 知识库分类 Service 实现
 */
@Service
public class KnowledgeCategoryServiceImpl extends ServiceImpl<KnowledgeCategoryMapper, KnowledgeCategory> implements IKnowledgeCategoryService {

    @Override
    public List<KnowledgeCategory> listTree() {
        // 查询所有未删除的分类
        LambdaQueryWrapper<KnowledgeCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KnowledgeCategory::getDelFlag, "0");
        wrapper.orderByAsc(KnowledgeCategory::getSortOrder);
        List<KnowledgeCategory> allCategories = this.list(wrapper);

        // 构建树形结构
        return buildTree(allCategories, null);
    }

    @Override
    public List<KnowledgeCategory> listByParentId(Long parentId) {
        LambdaQueryWrapper<KnowledgeCategory> wrapper = new LambdaQueryWrapper<>();
        if (parentId == null) {
            wrapper.isNull(KnowledgeCategory::getParentId);
        } else {
            wrapper.eq(KnowledgeCategory::getParentId, parentId);
        }
        wrapper.eq(KnowledgeCategory::getDelFlag, "0");
        wrapper.orderByAsc(KnowledgeCategory::getSortOrder);
        return this.list(wrapper);
    }

    /**
     * 构建树形结构
     */
    private List<KnowledgeCategory> buildTree(List<KnowledgeCategory> allCategories, Long parentId) {
        List<KnowledgeCategory> result = new ArrayList<>();
        for (KnowledgeCategory category : allCategories) {
            Long catParentId = category.getParentId();
            if ((parentId == null && catParentId == null) || 
                (parentId != null && parentId.equals(catParentId))) {
                // 递归查找子分类
                List<KnowledgeCategory> children = buildTree(allCategories, category.getId());
                if (children != null && !children.isEmpty()) {
                    category.setChildren(children);
                }
                result.add(category);
            }
        }
        return result;
    }
}