package com.cmeeting.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.map.MapUtil;
import com.cmeeting.constant.CategoryConstant;
import com.cmeeting.pojo.SysUserSyncCategory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hongdongbao
 */
public class CategoryTreeUtil<T> {

    public static final String ALL = "all";
    public static final String ROOT = "ROOT";
    public static final String NAME = "全部";


    public List<Tree<String>> build(List<T> qaCategory) {
        List<TreeNode<String>> nodeList = new ArrayList<>();
        for (T t : qaCategory) {
            nodeList.add(getTreeNode(t));
        }
        return TreeUtil.build(nodeList, CategoryConstant.ROOT_ID);
    }

    private TreeNode<String> getTreeNode(T data) {
        TreeNode<String> treeNode = new TreeNode<>();
        BeanUtil.copyProperties(data, treeNode);
        HashMap<String, Object> extra = MapUtil.newHashMap();
        if (data instanceof SysUserSyncCategory) {
            SysUserSyncCategory category = (SysUserSyncCategory) data;
            treeNode.setId(category.getDeptId());
            extra.put("path", category.getPath());
            extra.put("categoryId", category.getId());
            extra.put("parentId", category.getParentId());
            extra.put("sortNo", category.getSortNo());
        } else {
            // TODO 新的分类
        }
        treeNode.setExtra(extra);
        return treeNode;
    }

    /**
     * 根据分类id和parentId的map集合获取分类id和path的map集合
     *
     * @param deptIdAndPatentIdMap 分类id和parentId的map集合
     * @return 分类id和path的map集合
     */
    public static Map<String, String> getPathMap(Map<String, String> deptIdAndPatentIdMap) {
        Map<String, String> pathMap = new HashMap<>();
        for (String deptId : deptIdAndPatentIdMap.keySet()) {
            String path = getPath(deptIdAndPatentIdMap, deptId);
            pathMap.put(deptId, path);
        }
        return pathMap;
    }

    /**
     * 获取 分类的path
     * @param deptIdAndPatentIdMap
     * @param deptId
     * @return path
     */
    public static String getPath(Map<String, String> deptIdAndPatentIdMap, String deptId) {
        if (deptIdAndPatentIdMap.containsKey(deptId)) {
            return getPath(deptIdAndPatentIdMap, deptIdAndPatentIdMap.get(deptId)) + CategoryConstant.ROOT_PATH + deptId;
        } else {
            return "";
        }
    }
}
