package com.goldenwater.slgc.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.goldenwater.slgc.domain.DocCate;
import com.goldenwater.slgc.mapper.DocCateMapper;
import com.goldenwater.slgc.service.DocCateService;

/** 文档分类 业务实现 */
@Service
public class DocCateServiceImpl implements DocCateService {
    @Autowired
    private DocCateMapper docCateMapper;

    @Override
    public List<DocCate> selectDocCateList(DocCate docCate) {
        return docCateMapper.selectDocCateList(docCate);
    }

    @Override
    public DocCate selectDocCateById(String cateId) {
        return docCateMapper.selectDocCateById(cateId);
    }

    @Override
    public int deleteDocCateByIds(String[] cateIds) {
        int rows = 0;
        for (String cateId : cateIds) {
            rows += deleteRecursive(cateId);
        }
        return rows;
    }

    private int deleteRecursive(String cateId) {
        int rows = 0;
        List<DocCate> subList = docCateMapper.findSubList(cateId);
        for (DocCate sub : subList) {
            rows += deleteRecursive(sub.getCateId());
        }
        rows += docCateMapper.deleteDocCateById(cateId);
        return rows;
    }

    @Override
    public int insertDocCate(DocCate docCate) {
        return docCateMapper.insertDocCate(docCate);
    }

    @Override
    public int updateDocCate(DocCate docCate) {
        return docCateMapper.updateDocCate(docCate);
    }

    @Override
    public List<DocCate> getTree() {
        List<DocCate> allList = docCateMapper.selectDocCateList(new DocCate());
        List<DocCate> tree = new ArrayList<>();
        for (DocCate node : allList) {
            if (node.getCatePid() == null || node.getCatePid().isEmpty()) {
                node.setName(node.getCateName());
                buildChildren(node, allList);
                tree.add(node);
            }
        }
        return tree;
    }

    private void buildChildren(DocCate parent, List<DocCate> allList) {
        List<DocCate> children = new ArrayList<>();
        for (DocCate node : allList) {
            if (parent.getCateId().equals(node.getCatePid())) {
                node.setName(node.getCateName());
                buildChildren(node, allList);
                children.add(node);
            }
        }
        parent.setChildren(children);
    }

    @Override
    public List<DocCate> findSubList(String catePid) {
        return docCateMapper.findSubList(catePid);
    }
}
