package cc.smtweb.framework.core.mvc.service;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwMap;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Akmm at 2022/3/2 19:44
 * 列表服务
 */
@Slf4j
public abstract class AbstractTreeHandler<T> extends AbstractHandler {
    //树过滤
    public R filter() {
        return R.success(buildFilter());
    }

    //构建过滤数据
    public List<SwMap> buildFilter() {
        List<T> rows = filterData();
        return buildNodes(rows, true);
    }

    //下拉数据
    public R data() {
        return R.success(buildData());
    }

    //构建
    public List<SwMap> buildData() {
        List<T> rows = getChildren(params.readLong("parent_id"));
        return buildNodes(rows, params.readBool("lazy"));
    }

    //搜索
    protected abstract List<T> filterData();

    //获取指定节点的下级节点
    protected abstract List<T> getChildren(long id);

    protected List<T> getChildren(T bean) {
        return getChildren(getId(bean));
    }

    //根据bean，构建treenode
    protected List<SwMap> buildNodes(List<T> rows, boolean lazy) {
        List<SwMap> listRet = new ArrayList<>();
        if (rows == null || rows.isEmpty()) {
            return listRet;
        }
        for (T row : rows) {
            SwMap node = new SwMap();
            node.put("id", getId(row));
            node.put("text", getText(row));
            List<T> children = getChildren(row);
            node.put("leaf", children == null || children.isEmpty());
            node.put("bean", row);
            buildNode(node, row);
            listRet.add(node);
            if (!lazy && !node.containsKey("children")) {
                List<SwMap> list = buildNodes(children, lazy);
                node.put("children", list);
            }
        }
        return listRet;
    }

    //根据bean，构建treenode
    protected void buildNode(SwMap node, T bean) {
    }

    protected abstract long getId(T bean);

    protected abstract String getText(T bean);
}
