package com.yida.data.school.transaction.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.apply.EduProductCategory;
import com.yida.data.school.transaction.mapper.EduProductCategoryMapper;
import com.yida.data.school.transaction.service.EduProductCategoryService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import cn.hutool.core.collection.CollUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@AllArgsConstructor
@Transactional
@Slf4j
@Service
public class EduProductCategoryServiceImpl extends ServiceImpl<EduProductCategoryMapper,
        EduProductCategory> implements EduProductCategoryService {

    @Override
    public List<EduProductCategory> getCategoryTree() {
        List<EduProductCategory> all = list();
        return CollUtil.isNotEmpty(all) ? buildTree(null, all) : null;
    }

    @Override
    public void saveCategory(EduProductCategory category) {
        saveOrUpdate(category);
    }

    @Override
    public void delCategoryBatch(List<Long> ids) {
        List<EduProductCategory> list = list(Wrappers.<EduProductCategory>lambdaQuery()
                .in(EduProductCategory::getParentId, ids));
        if (CollUtil.isNotEmpty(list)) {
            delCategoryBatch(list.stream().map(x -> x.getId()).collect(Collectors.toList()));
        }
        removeByIds(ids);
    }

    private List<EduProductCategory> buildTree(List<EduProductCategory> parentList,
                                               List<EduProductCategory> categoryList) {
        List<EduProductCategory> finish = new ArrayList<>();
        List<EduProductCategory> notFinish = new ArrayList<>();
        if (CollUtil.isEmpty(parentList)) {
            parentList = categoryList.stream().filter(x -> x.getParentId() == 0).collect(Collectors.toList());
        }
        for (EduProductCategory parent : parentList) {
            Iterator<EduProductCategory> iterator = categoryList.iterator();
            while (iterator.hasNext()) {
                EduProductCategory category = iterator.next();
                if (parent.getId().equals(category.getParentId())) {
                    parent.getChild().add(category);
                    finish.add(category);
                    iterator.remove();
                }
            }
        }
        if (CollUtil.isNotEmpty(finish)) {
            buildTree(finish, categoryList);
        }
        return parentList;
    }
}
