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.CmsCate;
import com.goldenwater.slgc.mapper.CmsCateMapper;
import com.goldenwater.slgc.service.CmsCateService;

/** 内容分类 业务实现 */
@Service
public class CmsCateServiceImpl implements CmsCateService {
    @Autowired
    private CmsCateMapper cmsCateMapper;

    @Override
    public List<CmsCate> selectCmsCateList(CmsCate cmsCate) {
        return cmsCateMapper.selectCmsCateList(cmsCate);
    }

    @Override
    public CmsCate selectCmsCateById(String cateId) {
        return cmsCateMapper.selectCmsCateById(cateId);
    }

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

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

    @Override
    public int insertCmsCate(CmsCate cmsCate) {
        return cmsCateMapper.insertCmsCate(cmsCate);
    }

    @Override
    public int updateCmsCate(CmsCate cmsCate) {
        return cmsCateMapper.updateCmsCate(cmsCate);
    }

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

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

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