package com.ltgk.catches.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltgk.catches.domain.dto.QueryTpAquaticDictReq;
import com.ltgk.catches.domain.entity.TpAquaticDict;
import com.ltgk.catches.mapper.TpAquaticDictMapper;
import com.ltgk.catches.service.ITpAquaticDictService;
import com.ltgk.common.utils.StringUtils;
import org.springframework.stereotype.Service;

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


/**
 * 水产品字典Service业务层处理
 *
 * @author Qi ChengBin
 * @date 2025-01-08
 */
@Service
public class TpAquaticDictServiceImpl extends ServiceImpl<TpAquaticDictMapper, TpAquaticDict> implements ITpAquaticDictService {

    /**
     * 查询水产品字典树形结构数据
     *
     * @param queryTpAquaticDictReq: 水产品字典查询参数
     * @return java.util.List<com.ltgk.catches.domain.entity.TpAquaticDict>
     * @author Qi ChengBin
     * @date 2025/1/8 11:26
     */
    @Override
    public List<TpAquaticDict> findTpAquaticDictTreeList(QueryTpAquaticDictReq queryTpAquaticDictReq) {

        List<TpAquaticDict> tpAquaticDictList = this.lambdaQuery()
                .like(StringUtils.isNotBlank(queryTpAquaticDictReq.getKeyWord()), TpAquaticDict::getDictName, queryTpAquaticDictReq.getKeyWord())
                .orderByDesc(TpAquaticDict::getCreateAt)
                .list();

        List<TpAquaticDict> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tpAquaticDictList)) {
            for (TpAquaticDict parent : tpAquaticDictList) {
                List<TpAquaticDict> children = new ArrayList<>();
                for (TpAquaticDict child : tpAquaticDictList) {
                    if (parent.getId().equals(child.getParentId())) {
                        children.add(child);
                    }
                }
                children = children.stream().sorted(Comparator.comparing(TpAquaticDict::getSort)).collect(Collectors.toList());
                parent.setChildDictList(children);
                resultList.add(parent);
            }
            resultList = resultList.stream().filter(f -> f.getParentId().equals("0")).sorted(Comparator.comparing(TpAquaticDict::getSort)).collect(Collectors.toList());
        }
        return resultList;
    }
}
