package com.ruoyi.busi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.busi.domain.BusiCategory;
import com.ruoyi.busi.mapper.BusiCategoryMapper;
import com.ruoyi.busi.service.IBusiCategoryService;
import com.ruoyi.busi.vo.BusiCategoryVO;
import com.ruoyi.common.core.domain.DlBaseEntity;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站栏目Service业务层处理
 *
 * @author pqz
 * @date 2025-06-19
 */
@Service
public class BusiCategoryServiceImpl extends ServiceImpl<BusiCategoryMapper, BusiCategory> implements IBusiCategoryService {
    @Autowired
    private BusiCategoryMapper busiCategoryMapper;


    /**
     * 树形结构查询网站栏目
     *
     * @param category {@link BusiCategory}
     * @return java.util.List<com.ruoyi.busi.vo.BusiCategoryVO>
     * @author PQZ
     * @date 14:06 2025/6/23
     **/
    @Override
    public List<BusiCategoryVO> treeCategory(BusiCategory category) {
        //查询全部栏目
        LambdaQueryWrapper<BusiCategory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DlBaseEntity::getDelFlag,0)
                .eq(BusiCategory::getTenantId,category.getTenantId())
                .orderByAsc(DlBaseEntity::getCreateTime);
        if (StringUtils.isEmpty(category.getCatgName())) {
            lambdaQueryWrapper.like(BusiCategory::getCatgName,category.getCatgName());
        }
        List<BusiCategory> list = list(lambdaQueryWrapper);
        return buildCategoryTree(list);
    }


    /**
     * 生成树结构
     * @author PQZ
     * @date 14:11 2025/6/23
     * @param list 网站栏目列表
     * @return java.util.List<com.ruoyi.busi.vo.BusiCategoryVO>
    **/
    private List<BusiCategoryVO> buildCategoryTree(List<BusiCategory> list) {
        // Map存放id到VO的映射
        Map<String, BusiCategoryVO> idToNodeMap = new HashMap<>();
        // 先将所有节点转换为VO，并放入Map
        for (BusiCategory category : list) {
            BusiCategoryVO vo = new BusiCategoryVO();
            BeanUtils.copyProperties(category,vo);
            idToNodeMap.put(vo.getId(), vo);
        }
        List<BusiCategoryVO> roots = new ArrayList<>();
        // 构建树
        for (BusiCategoryVO node : idToNodeMap.values()) {
            String parentId = node.getParentId();
            if (parentId == null || parentId.trim().isEmpty() || !idToNodeMap.containsKey(parentId)) {
                // 根节点
                roots.add(node);
            } else {
                // 作为父节点的子节点
                BusiCategoryVO parent = idToNodeMap.get(parentId);
                parent.getChildren().add(node);
            }
        }
        return roots;
    }
}
