package org.springblade.flow.permission.service;

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

import org.springblade.flow.base.entity.ModuleEntity;
import org.springblade.flow.base.mapper.ModuleMapper;
import org.springblade.flow.model.login.MenuTreeVO;
import org.springblade.flow.util.JsonUtil;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 
 * @author william
 * @date 2022年8月4日 上午10:35:06
 */
@Service
public class ModuleServicePlatomix extends ServiceImpl<ModuleMapper, ModuleEntity> {

	public List<MenuTreeVO> getTreeList() {
		QueryWrapper<ModuleEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().orderByAsc(ModuleEntity::getSortCode);
		List<ModuleEntity> list = this.list(queryWrapper);
		List<MenuTreeVO> treeList = JsonUtil.getJsonToList(JSON.toJSONString(list), MenuTreeVO.class);
		treeList = buildTree(treeList);
		return treeList;
	}

	private List<MenuTreeVO> buildTree(List<MenuTreeVO> list) {
		List<MenuTreeVO> treeList = new ArrayList<>();
		for (MenuTreeVO item : list) {
			if ("-1".equalsIgnoreCase(item.getParentId())) {
				treeList.add(this.buildChildren(item, list));
			}
		}
		return treeList;
	}

	private MenuTreeVO buildChildren(MenuTreeVO parent, List<MenuTreeVO> list) {
		for (MenuTreeVO item : list) {
			if (item.getParentId().equalsIgnoreCase(parent.getId())) {
				if (parent.getChildren() == null) {
					parent.setChildren(new ArrayList<>());
				}
				parent.getChildren().add(this.buildChildren(item, list));
				parent.setHasChildren(true);
			}
		}
		return parent;
	}

}
