package com.xunhong.erp.turbo.rbac.app.executor.query;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.xunhong.erp.turbo.api.rbac.dto.qry.RoleMenuTreeQry;
import com.xunhong.erp.turbo.rbac.domain.entity.Menu;
import com.xunhong.erp.turbo.rbac.domain.entity.RoleMenu;
import com.xunhong.erp.turbo.rbac.domain.gateway.RoleMenuGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RequiredArgsConstructor
public class UserMenuQryExe {
	private final RoleMenuGateway roleMenuGateway;

	public List<Tree<Long>> execute(RoleMenuTreeQry roleMenuTreeQry) {
		List<RoleMenu> roleMenuList = roleMenuGateway.list(roleMenuTreeQry);

		TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
		treeNodeConfig.setWeightKey("sort");
		treeNodeConfig.setIdKey("menuId");
		treeNodeConfig.setParentIdKey("pid");
		treeNodeConfig.setNameKey("name");
		treeNodeConfig.setChildrenKey("routes");
		treeNodeConfig.setDeep(5);

		return TreeUtil.build(roleMenuList, null, treeNodeConfig, (roleMenu, tree) -> {
			Menu menu = roleMenu.getMenu();
			tree.setId(roleMenu.getMenuId());
			tree.setParentId(menu.getPid());
			tree.setWeight(menu.getSort());
			tree.setName(menu.getName());
			// 扩展属性 ...
			tree.putExtra("path", menu.getPath());
			tree.putExtra("platformId", menu.getPlatformId());
			tree.putExtra("hideInMenu", menu.getHideInMenu());
			tree.putExtra("type", menu.getType());
			tree.putExtra("component", menu.getComponent());
			tree.putExtra("icon", menu.getIcon());
			tree.putExtra("iconColor", menu.getIconColor());
			tree.putExtra("bgColorClass", menu.getBgColorClass());
		});
	}
}
