package com.zksy.dispatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.dispatch.domain.DisPlanCategory;
import com.zksy.dispatch.dto.DisPlanCategoryPageDTO;
import com.zksy.dispatch.mapper.DisPlanCategoryMapper;
import com.zksy.dispatch.service.DisPlanCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class DisPlanCategoryServiceImpl extends ServiceImpl<DisPlanCategoryMapper, DisPlanCategory>
        implements DisPlanCategoryService {

    @Override
    public Page<DisPlanCategory> findByPage(DisPlanCategoryPageDTO dto) {
        Page<DisPlanCategory> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<DisPlanCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dto.getLabel() != null && !dto.getLabel().isEmpty(), DisPlanCategory::getLabel, dto.getLabel());
        wrapper.eq(dto.getParentId() != null, DisPlanCategory::getParentId, dto.getParentId());
        wrapper.orderByAsc(DisPlanCategory::getSortOrder);
        return this.page(page, wrapper);
    }

    @Override
    public List<DisPlanCategory> getCategoryTree() {
        List<DisPlanCategory> all = this.list(new LambdaQueryWrapper<DisPlanCategory>()
                .orderByAsc(DisPlanCategory::getSortOrder));
        // 查找顶级节点（parentId为null或0）
        List<DisPlanCategory> roots = all.stream()
                .filter(c -> c.getParentId() == null || c.getParentId() == 0L)
                .collect(Collectors.toList());
        // 递归构建子节点
        for (DisPlanCategory root : roots) {
            buildChildren(root, all);
        }
        return roots;
    }

    private void buildChildren(DisPlanCategory parent, List<DisPlanCategory> all) {
        List<DisPlanCategory> children = all.stream()
                .filter(c -> parent.getId().equals(c.getParentId()))
                .collect(Collectors.toList());
        parent.setChildren(children);
        for (DisPlanCategory child : children) {
            buildChildren(child, all);
        }
    }
}
