package com.gxwebsoft.ai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.ai.mapper.AiCloudDocMapper;
import com.gxwebsoft.ai.service.AiCloudDocService;
import com.gxwebsoft.ai.entity.AiCloudDoc;
import com.gxwebsoft.ai.param.AiCloudDocParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

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

/**
 * AI云文档目录表Service实现
 *
 * @author yc
 */
@Service
public class AiCloudDocServiceImpl extends ServiceImpl<AiCloudDocMapper, AiCloudDoc> implements AiCloudDocService {

    @Override
    public PageResult<AiCloudDoc> pageRel(AiCloudDocParam param) {
        PageParam<AiCloudDoc, AiCloudDocParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<AiCloudDoc> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<AiCloudDoc> listRel(AiCloudDocParam param) {
        List<AiCloudDoc> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<AiCloudDoc, AiCloudDocParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public AiCloudDoc getByIdRel(Integer id) {
        AiCloudDocParam param = new AiCloudDocParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public List<AiCloudDoc> getSelfAndChildren(Integer docId) {
        // 查询所有未删除的目录
        AiCloudDocParam param = new AiCloudDocParam();
        param.setDeleted(0);
        List<AiCloudDoc> allDocs = this.listRel(param);
        
        // 查找指定目录
        AiCloudDoc targetDoc = allDocs.stream()
                .filter(doc -> doc.getId().equals(docId))
                .findFirst()
                .orElse(null);
        
        if (targetDoc == null) {
            return new ArrayList<>();
        }
        
        // 递归获取所有子孙目录
        List<AiCloudDoc> result = new ArrayList<>();
        result.add(targetDoc);
        getChildrenRecursive(allDocs, targetDoc.getId(), result);
        
        return result;
    }

    /**
     * 递归获取所有子目录
     *
     * @param allDocs 所有目录列表
     * @param parentId 父目录ID
     * @param result 结果列表
     */
    private void getChildrenRecursive(List<AiCloudDoc> allDocs, Integer parentId, List<AiCloudDoc> result) {
        List<AiCloudDoc> children = allDocs.stream()
                .filter(doc -> parentId.equals(doc.getParentId()))
                .collect(Collectors.toList());
        
        for (AiCloudDoc child : children) {
            result.add(child);
            getChildrenRecursive(allDocs, child.getId(), result);
        }
    }
}
