package org.springblade.flow.permission.service;

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

import org.springblade.flow.base.Page;
import org.springblade.flow.permission.entity.Role4FlowEntity;
import org.springblade.flow.permission.mapper.Role4FlowMapper;
import org.springblade.flow.permission.model.role.RoleSelectorVO;
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-07-14 10:57:53
 */
@Service
public class Role4FlowService extends ServiceImpl<Role4FlowMapper, Role4FlowEntity> {

	public List<Role4FlowEntity> getList(Page page) {
		QueryWrapper<Role4FlowEntity> queryWrapper = new QueryWrapper<>();
		if (page.getKeyword() != null) {
			queryWrapper.lambda().and(t -> t.like(Role4FlowEntity::getFullName, page.getKeyword()).or()
					.like(Role4FlowEntity::getRoleAlias, page.getKeyword()));
		}
		queryWrapper.lambda().orderByAsc(Role4FlowEntity::getSort);
		return this.list(queryWrapper);
	}

	public Role4FlowEntity getInfo(String id) {
		QueryWrapper<Role4FlowEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(Role4FlowEntity::getId, id);
		return this.getOne(queryWrapper);
	}

	public List<Role4FlowEntity> getRoleName(List<String> id) {
		List<Role4FlowEntity> roleList = new ArrayList<>();
		if (id.size() > 0) {
			QueryWrapper<Role4FlowEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(Role4FlowEntity::getId, id);
			roleList = this.list(queryWrapper);
		}
		return roleList;
	}

	public List<Role4FlowEntity> getList() {
		return this.list();
	}

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

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

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