package com.glxp.mipsdl.service.basic;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glxp.mipsdl.entity.basic.RelCodeDetail;
import com.glxp.mipsdl.dao.basic.RelCodeDetailMapper;

@Service
public class RelCodeDetailService extends ServiceImpl<RelCodeDetailMapper, RelCodeDetail> {
    /**
     * 获取下级所有码
     *
     * @return
     */
    public List<RelCodeDetail> getAllNext(String code) {
        RelCodeDetail relCodeDetail = this.baseMapper.selectOne(
                new LambdaQueryWrapper<RelCodeDetail>().eq(RelCodeDetail::getCurCode, code)
        );
        if(Objects.isNull(relCodeDetail)){
            relCodeDetail = new RelCodeDetail();
            relCodeDetail.setCurCode(code);
        }
        List<RelCodeDetail> list = new ArrayList<>();
        list.add(relCodeDetail);
        fetchAllChildren(code, list);

        return list;
    }

    private void fetchAllChildren(String code, List<RelCodeDetail> list) {
        List<RelCodeDetail> relCodeDetails = this.baseMapper.selectList(
                new LambdaQueryWrapper<RelCodeDetail>().eq(RelCodeDetail::getParentCode, code));

        if (CollUtil.isNotEmpty(relCodeDetails)) {
            list.addAll(relCodeDetails);
            for (RelCodeDetail relCodeDetail : relCodeDetails) {
                fetchAllChildren(relCodeDetail.getCurCode(), list);
            }
        }
    }


}
