package org.springblade.flow.permission.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.springblade.flow.base.ActionResult;
import org.springblade.flow.base.Pagination;
import org.springblade.flow.base.vo.ListVO;
import org.springblade.flow.database.exception.DataException;
import org.springblade.flow.permission.entity.OrganizeEntity;
import org.springblade.flow.permission.entity.UserEntity;
import org.springblade.flow.permission.model.organize.OrganizeDepartInfoVO;
import org.springblade.flow.permission.model.organize.OrganizeDepartListVO;
import org.springblade.flow.permission.model.organize.OrganizeDepartSelectorListVO;
import org.springblade.flow.permission.model.organize.OrganizeInfoVO;
import org.springblade.flow.permission.model.organize.OrganizeListVO;
import org.springblade.flow.permission.model.organize.OrganizeModel;
import org.springblade.flow.permission.model.organize.OrganizeSelectorVO;
import org.springblade.flow.permission.model.organize.OrganizeTreeVO;
import org.springblade.flow.permission.service.OrganizeService;
import org.springblade.flow.permission.service.User4FlowService;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.JsonUtilEx;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.util.treeutil.ListToTreeUtil;
import org.springblade.flow.util.treeutil.SumTree;
import org.springblade.flow.util.treeutil.newtreeutil.TreeDotUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 *  数据处理
 *
 * @author william
 * @date   2022-07-14 10:57:52
 */
@Api(tags = "部门管理", value = "Organize")
@RequestMapping("/paas/Organize")
@RestController
public class OrganizeController {
	@Autowired
	private OrganizeService organizeService;

	@Autowired
	private User4FlowService userService;

	/**
	 * 获取组织列表
	 *
	 * @param pagination
	 * @return
	 */
	@ApiOperation("获取组织列表")
	@GetMapping
	public ActionResult<ListVO<OrganizeListVO>> getList(Pagination pagination) {
		List<OrganizeEntity> data = organizeService.getList();
		List<OrganizeEntity> dataAll = data;
		List<OrganizeEntity> list = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data, dataAll),
				OrganizeEntity.class);
		list = list.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
		List<OrganizeModel> oraganizeList = JsonUtil.getJsonToList(list, OrganizeModel.class);
		List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(oraganizeList);
		List<OrganizeListVO> listVO = JsonUtil.getJsonToList(trees, OrganizeListVO.class);

		if (!StringUtil.isEmpty(pagination.getKeyword())) {
			listVO = listVO.stream()
					.filter(t -> t.getFullName().toLowerCase().contains(pagination.getKeyword())
							|| t.getEnCode().toLowerCase().contains(pagination.getKeyword()))
					.collect(Collectors.toList());
		}
		ListVO<OrganizeListVO> vo = new ListVO<>();
		vo.setList(listVO);
		return ActionResult.success(vo);
	}

	/**
	 * 获取组织下拉框列表
	 *
	 * @return
	 */
	@ApiOperation("获取组织下拉框列表")
	@GetMapping("/Selector")
	public ActionResult<ListVO<OrganizeSelectorVO>> getSelector(Pagination pagination) {
		List<OrganizeEntity> allList = organizeService.getList();
		List<OrganizeEntity> data = allList.stream().filter(t -> "0".equals(String.valueOf(t.getIsDeleted())))
				.collect(Collectors.toList());
		List<OrganizeEntity> dataAll = data;
		if (!StringUtil.isEmpty(pagination.getKeyword())) {
			data = data.stream().filter(t -> t.getFullName().contains(pagination.getKeyword())
					|| t.getEnCode().contains(pagination.getKeyword())).collect(Collectors.toList());
		}
		List<OrganizeEntity> list = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data, dataAll),
				OrganizeEntity.class);
		list = list.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
		List<OrganizeModel> models = JsonUtil.getJsonToList(list, OrganizeModel.class);
		for (OrganizeModel model : models) {
			model.setIcon("icon-ym icon-ym-tree-organization3");
		}
		List<OrganizeModel> modelAll = new ArrayList<>();
		modelAll.addAll(models);
		List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(modelAll);
		List<OrganizeSelectorVO> listVO = JsonUtil.getJsonToList(trees, OrganizeSelectorVO.class);

		// 将子节点全部删除
		Iterator<OrganizeSelectorVO> iterator = listVO.iterator();
		while (iterator.hasNext()) {
			OrganizeSelectorVO oraganizeSelectorVO = iterator.next();
			if (!"-1".equals(oraganizeSelectorVO.getParentId()) && !"0".equals(oraganizeSelectorVO.getParentId())) {
				iterator.remove();
			}
		}
		ListVO<OrganizeSelectorVO> vo = new ListVO<>();
		vo.setList(listVO);
		return ActionResult.success(vo);
	}

	/**
	 * 组织树形
	 *
	 * @return
	 */
	@ApiOperation("获取组织/公司树形")
	@GetMapping("/Tree")
	public ActionResult<ListVO<OrganizeTreeVO>> tree() {
		List<OrganizeEntity> allList = organizeService.getList();
		List<OrganizeEntity> list = allList.stream().filter(t -> "0".equals(String.valueOf(t.getIsDeleted())))
				.collect(Collectors.toList());
		list = list.stream().filter(t -> "company".equals(t.getCategory())).collect(Collectors.toList());
		List<OrganizeModel> models = JsonUtil.getJsonToList(list, OrganizeModel.class);
		for (OrganizeModel model : models) {
			model.setIcon("icon-ym icon-ym-tree-organization3");
		}
		List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(models);
		List<OrganizeTreeVO> listVO = JsonUtil.getJsonToList(trees, OrganizeTreeVO.class);
		// 将子节点全部删除
		Iterator<OrganizeTreeVO> iterator = listVO.iterator();
		while (iterator.hasNext()) {
			OrganizeTreeVO orananizeTreeVO = iterator.next();
			if (!"-1".equals(orananizeTreeVO.getParentId())) {
				iterator.remove();
			}
		}
		ListVO<OrganizeTreeVO> vo = new ListVO<>();
		vo.setList(listVO);
		return ActionResult.success(vo);
	}

	/**
	 * 获取组织信息
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("获取组织信息")
	@GetMapping("/{id}")
	public ActionResult<OrganizeInfoVO> info(@PathVariable("id") String id) throws DataException {
		OrganizeEntity entity = organizeService.getInfo(id);
		OrganizeInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, OrganizeInfoVO.class);
		return ActionResult.success(vo);
	}

	/**
	 * 获取部门列表
	 *
	 * @param companyId
	 * @return
	 */
	@ApiOperation("获取部门列表")
	@GetMapping("/{companyId}/Department")
	public ActionResult<ListVO<OrganizeDepartListVO>> getListDepartment(@PathVariable("companyId") String companyId,
			Pagination pagination) {
		List<OrganizeEntity> dataAll = organizeService.getList();
		String parentId = dataAll.stream().filter(t -> t.getId().equals(companyId)).findFirst()
				.orElse(new OrganizeEntity()).getId();
		List<OrganizeEntity> data = new ArrayList<>();
		// 将部门之下的子集搜索出来
		List<OrganizeEntity> dataCopy = dataAll.stream().filter(t -> "department".equals(t.getCategory()))
				.collect(Collectors.toList());
		for (OrganizeEntity entity : dataCopy) {
			List<OrganizeEntity> data1 = new ArrayList<>();
			data1.add(entity);
			String id = JsonUtil.getJsonToList(ListToTreeUtil.treeWhere(data1, dataAll), OrganizeEntity.class).stream()
					.filter(t -> companyId.equals(t.getId())).findFirst().orElse(new OrganizeEntity()).getId();
			if (parentId.equals(id)) {
				data.add(entity);
			}
		}
		if (!StringUtil.isEmpty(pagination.getKeyword())) {
			data = data.stream().filter(t -> t.getFullName().contains(pagination.getKeyword())
					|| t.getEnCode().contains(pagination.getKeyword())).collect(Collectors.toList());
		}
		List<OrganizeModel> models = JsonUtil.getJsonToList(data, OrganizeModel.class);

//        给部门经理赋值
		for (OrganizeModel model : models) {
			if (!StringUtil.isEmpty(model.getManager())) {
				UserEntity entity = userService.getById(model.getManager());
				if (entity != null) {
					model.setManager(entity.getRealName() + "/" + entity.getAccount());
				}
			}
		}
		List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(models);
		// 去掉子公司的部门
		trees = trees.stream().filter(t -> parentId.equals(t.getParentId())).collect(Collectors.toList());
		List<OrganizeDepartListVO> listvo = JsonUtil.getJsonToList(trees, OrganizeDepartListVO.class);
		ListVO<OrganizeDepartListVO> vo = new ListVO<>();
		vo.setList(listvo);
		return ActionResult.success(vo);
	}

	/**
	 * 获取部门下拉框列表
	 *
	 * @return
	 */
	@ApiOperation("获取部门下拉框列表")
	@GetMapping("/Department/Selector")
	public ActionResult<ListVO<OrganizeDepartSelectorListVO>> getListDepartment() {
		List<OrganizeEntity> allList = organizeService.getList();
		List<OrganizeEntity> data = allList.stream().filter(t -> "0".equals(String.valueOf(t.getIsDeleted())))
				.collect(Collectors.toList());
		List<OrganizeModel> models = JsonUtil.getJsonToList(data, OrganizeModel.class);
		for (OrganizeModel model : models) {
			if ("department".equals(model.getType())) {
				model.setIcon("icon-ym icon-ym-tree-department1");
			} else if ("company".equals(model.getType())) {
				model.setIcon("icon-ym icon-ym-tree-organization3");
			}
		}
		List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(models);
		List<OrganizeDepartSelectorListVO> listVO = JsonUtil.getJsonToList(trees, OrganizeDepartSelectorListVO.class);

		// 将子节点全部删除
		Iterator<OrganizeDepartSelectorListVO> iterator = listVO.iterator();
		while (iterator.hasNext()) {
			OrganizeDepartSelectorListVO organizeDepartSelectorListVO = iterator.next();
			if (!"-1".equals(organizeDepartSelectorListVO.getParentId())) {
				iterator.remove();
			}
		}

		ListVO<OrganizeDepartSelectorListVO> vo = new ListVO<>();
		vo.setList(listVO);
		return ActionResult.success(vo);
	}

	/**
	 * 获取部门信息
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("获取部门信息")
	@GetMapping("/Department/{id}")
	public ActionResult<OrganizeDepartInfoVO> infoDepartment(@PathVariable("id") String id) throws DataException {
		OrganizeEntity entity = organizeService.getInfo(id);
		OrganizeDepartInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, OrganizeDepartInfoVO.class);
		return ActionResult.success(vo);
	}
}
