package com.ruoyi.liandao.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.query.LambdaQueryWrapperX;
import com.ruoyi.liandao.domain.ArticleType;
import com.ruoyi.liandao.dto.articleType.ArticleTypeAddReqDto;
import com.ruoyi.liandao.dto.articleType.ArticleTypeEditReqDto;
import com.ruoyi.liandao.dto.articleType.ArticleTypeListReqDto;
import com.ruoyi.liandao.mapper.ArticleTypeMapper;
import com.ruoyi.liandao.service.ArticleTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author admin
 * @description 针对表【ld_article_type(文章类型配置)】的数据库操作Service实现
 * @createDate 2024-03-14 10:51:08
 */
@Service
@DataSource(DataSourceType.MASTER)
public class ArticleTypeServiceImpl extends ServiceImpl<ArticleTypeMapper, ArticleType>
        implements ArticleTypeService {

    @Autowired
    private ArticleTypeMapper articleTypeMapper;

    @Override
    public List<Tree<Long>> getList(ArticleTypeListReqDto dto) {
        List<ArticleType> list = articleTypeMapper.getList(dto.getName());
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("orderNum");
        return TreeUtil.build(list, 0L, treeNodeConfig, (obj, tree) -> {
            tree.setId(obj.getId());
            tree.setParentId(obj.getParentId());
            tree.setName(obj.getName());
            tree.setWeight(obj.getOrderNum());
        });
    }

    @Override
    public void add(ArticleTypeAddReqDto dto) {
        ArticleType articleType = Convert.convert(ArticleType.class, dto);
        save(articleType);
    }

    @Override
    public void edit(ArticleTypeEditReqDto dto) {
        ArticleType articleType = Convert.convert(ArticleType.class, dto);
        updateById(articleType);
    }

    @Override
    public List<Long> getChildTypeIdList(Long articleTypeId) {
        if(articleTypeId==null){
            return null;
        }
        List<Long> result = new ArrayList<>();
        result.add(articleTypeId);
        List<ArticleType> articleTypeList = list(new LambdaQueryWrapperX<ArticleType>()
                .eq(ArticleType::getParentId, articleTypeId));
        if(CollUtil.isNotEmpty(articleTypeList)){
            for (ArticleType articleType : articleTypeList) {
                List<Long> childTypeIdList = getChildTypeIdList(articleType.getId());
                result.addAll(childTypeIdList);
            }
        }
        return result;
    }


}




