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.Page;
import org.springblade.flow.base.Pagination;
import org.springblade.flow.base.vo.ListVO;
import org.springblade.flow.base.vo.PageListVO;
import org.springblade.flow.base.vo.PaginationVO;
import org.springblade.flow.database.exception.DataException;
import org.springblade.flow.model.login.PcUserVO;
import org.springblade.flow.permission.entity.OrganizeEntity;
import org.springblade.flow.permission.entity.PositionEntity;
import org.springblade.flow.permission.entity.Role4FlowEntity;
import org.springblade.flow.permission.entity.UserDept4Flow;
import org.springblade.flow.permission.entity.UserEntity;
import org.springblade.flow.permission.model.user.ImUserListVo;
import org.springblade.flow.permission.model.user.PaginationUser;
import org.springblade.flow.permission.model.user.UserAllModel;
import org.springblade.flow.permission.model.user.UserAllVO;
import org.springblade.flow.permission.model.user.UserIdListVo;
import org.springblade.flow.permission.model.user.UserIdModel;
import org.springblade.flow.permission.model.user.UserInfoVO;
import org.springblade.flow.permission.model.user.UserListVO;
import org.springblade.flow.permission.model.user.UserSelectorModel;
import org.springblade.flow.permission.model.user.UserSelectorVO;
import org.springblade.flow.permission.service.OrganizeService;
import org.springblade.flow.permission.service.PositionService;
import org.springblade.flow.permission.service.Role4FlowService;
import org.springblade.flow.permission.service.User4FlowService;
import org.springblade.flow.permission.service.UserDept4FlowService;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.JsonUtilEx;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.util.UploaderUtil;
import org.springblade.flow.util.UserProvider;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 数据处理
 *
 * @author william
 * @date 2022-07-14 10:57:53
 */
@Api(tags = "用户管理", value = "Users")
@RequestMapping("/paas/permission/Users")
@RestController
@SuppressWarnings("rawtypes")
public class User4FlowController {
	@Autowired
	private User4FlowService userService;

	@Autowired
	private OrganizeService organizeService;

	@Autowired
	private UserDept4FlowService userDeptService;

	@Autowired
	private Role4FlowService roleService;

	@Autowired
	private PositionService positionService;

	@Autowired
	private UserProvider userProvider;

	/**
	 * 获取用户登录信息
	 *
	 * @return
	 */
	@ApiOperation("获取用户登录信息")
	@GetMapping("/CurrentUser")
	public ActionResult<PcUserVO> currentUser() {
		PcUserVO pcUserVO = userProvider.getCurrentUser();
		if (pcUserVO == null) {
			return ActionResult.fail("获取登录用户信息失败");
		}
		return ActionResult.success(pcUserVO);
	}

	/**
	 * 获取用户列表
	 *
	 * @param pagination
	 * @return
	 */
	@ApiOperation("获取用户列表")
	@GetMapping
	public ActionResult<PageListVO<UserListVO>> getList(PaginationUser pagination) {
		List<OrganizeEntity> organizeList = organizeService.getList().stream()
				.filter(t -> "0".equals(String.valueOf(t.getIsDeleted()))).collect(Collectors.toList());
		List<OrganizeEntity> dataAll = JsonUtil.getJsonToList(
				ListToTreeUtil.treeWhere(pagination.getOrganizeId(), organizeList), OrganizeEntity.class);
		List<String> organizeIds = dataAll.stream().map(t -> t.getId()).collect(Collectors.toList());
		organizeIds.add(pagination.getOrganizeId());
		pagination.setOrganizeId(String.join(",", organizeIds));
		List<UserEntity> data = userService.getList(pagination, pagination.getOrganizeId());
		List<UserListVO> list = new ArrayList<>();
		for (UserEntity entity : data) {
			UserListVO user = JsonUtil.getJsonToBean(entity, UserListVO.class);
			// 部门名称
			OrganizeEntity organize = organizeService.getInfo(entity.getOrganizeId());
			if (organize != null && StringUtil.isNotEmpty(organize.getFullName())) {
				user.setDepartment(organize.getFullName());
			}
			list.add(user);
		}
		PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
		return ActionResult.page(list, paginationVO);
	}

	/**
	 * 获取用户列表
	 *
	 * @return
	 */
	@ApiOperation("获取所有用户列表")
	@GetMapping("/All")
	public ActionResult<ListVO<UserAllVO>> getAllUsers(Pagination pagination) {
		List<UserAllModel> uservo = userService.getAll().stream()
				.filter(t -> !StringUtil.isEmpty(pagination.getKeyword())
						? t.getRealName().toLowerCase().contains(pagination.getKeyword())
								|| t.getAccount().toLowerCase().contains(pagination.getKeyword())
						: t.getRealName() != null)
				.collect(Collectors.toList());
		List<UserAllVO> user = JsonUtil.getJsonToList(uservo, UserAllVO.class);
		ListVO vo = new ListVO();
		vo.setList(user);
		return ActionResult.success(vo);
	}

	/**
	 * IM通讯获取用户接口
	 *
	 * @param pagination
	 * @return
	 */
	@ApiOperation("IM通讯获取用户")
	@GetMapping("/ImUser")
	public ActionResult<PageListVO<ImUserListVo>> getAllImUserUsers(Pagination pagination) {
		List<UserEntity> data = userService.getList(pagination, "");
		List<UserAllModel> userList = userService.getAll();
		List<ImUserListVo> list = new ArrayList<>();
		for (UserEntity entity : data) {
			ImUserListVo user = JsonUtil.getJsonToBean(entity, ImUserListVo.class);
			user.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
			UserAllModel ImUserListVo = userList.stream().filter(t -> t.getId().equals(entity.getId())).findFirst()
					.orElse(new UserAllModel());
			user.setDepartment(ImUserListVo.getDepartment());
			list.add(user);
		}
		PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
		return ActionResult.page(list, paginationVO);
	}

	/**
	 * 获取用户下拉框列表
	 *
	 * @return
	 */
	@ApiOperation("获取用户下拉框列表")
	@GetMapping("/Selector")
	public ActionResult<ListVO<UserSelectorVO>> selector() {
		List<OrganizeEntity> allOrganizeData = organizeService.getList();
		List<OrganizeEntity> organizeData = organizeService.getList().stream()
				.filter(t -> "0".equals(String.valueOf(t.getIsDeleted()))).collect(Collectors.toList());
		List<UserEntity> userData = userService.getList().stream()
				.filter(t -> "1".equals(String.valueOf(t.getEnabledMark()))).collect(Collectors.toList());
		List<UserSelectorModel> treeList = JsonUtil.getJsonToList(organizeData, UserSelectorModel.class);
		for (UserSelectorModel entity1 : treeList) {
			if ("department".equals(entity1.getType())) {
				entity1.setIcon("icon-ym icon-ym-tree-department1");
			} else if ("company".equals(entity1.getType())) {
				entity1.setIcon("icon-ym icon-ym-tree-organization3");
			}
		}
		for (UserEntity entity : userData) {
			UserSelectorModel treeModel = new UserSelectorModel();
			treeModel.setId(entity.getId());
			treeModel.setParentId(entity.getOrganizeId());
			treeModel.setFullName(entity.getRealName() + "/" + entity.getAccount());
			treeModel.setType("user");
			treeModel.setIcon("icon-ym icon-ym-tree-user2");
			treeList.add(treeModel);
		}
		List<SumTree<UserSelectorModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
		List<UserSelectorVO> listvo = JsonUtil.getJsonToList(trees, UserSelectorVO.class);
		List<OrganizeEntity> entities = allOrganizeData.stream()
				.filter(t -> "0".equals(String.valueOf(t.getIsDeleted())) && "0".equals(t.getParentId()))
				.collect(Collectors.toList());
		Iterator<UserSelectorVO> iterator = listvo.iterator();
		while (iterator.hasNext()) {
			UserSelectorVO userSelectorVO = iterator.next();
			for (OrganizeEntity entity : entities) {
				if (entity.getId().equals(userSelectorVO.getParentId())) {
					iterator.remove();// 使用迭代器的删除方法删除
				}
			}
		}
		ListVO vo = new ListVO();
		vo.setList(listvo);
		return ActionResult.success(vo);
	}

	@ApiOperation("获取用户下拉框列表")
	@PostMapping("/ImUser/Selector/{organizeId}")
	public ActionResult selector(@PathVariable("organizeId") String organizeId, @RequestBody Page page) {
		List<UserSelectorVO> jsonToList = new ArrayList<>();
		if (StrUtil.isNotEmpty(organizeId)) {
			if (organizeId.equalsIgnoreCase("-1")) {
				// 返回公司基本信息
				UserSelectorVO userSelectorVO = new UserSelectorVO();
				userSelectorVO.setId("0");
				userSelectorVO.setParentId("-1");
				userSelectorVO.setType("company");
				userSelectorVO.setFullName("联通在线");
				userSelectorVO.setEnabledMark(1);
				userSelectorVO.setIcon("icon-ym icon-ym-tree-organization3");
				userSelectorVO.setHasChildren(true);
				userSelectorVO.setIsLeaf(false);
				jsonToList.add(userSelectorVO);
			} else {
				// 查询部门或者用户
				// 先查部门，没有部门则查用户
				LambdaQueryWrapper<OrganizeEntity> deptWrapper = Wrappers.<OrganizeEntity>lambdaQuery();
				deptWrapper.eq(OrganizeEntity::getParentId, Long.parseLong(organizeId));
				List<OrganizeEntity> deptList = organizeService.list(deptWrapper);
				if (deptList == null || deptList.isEmpty()) {
					// 没有部门，则查询用户
					LambdaQueryWrapper<UserDept4Flow> userDeptWrapper = Wrappers.<UserDept4Flow>lambdaQuery();
					userDeptWrapper.eq(UserDept4Flow::getDeptId, Long.parseLong(organizeId));
					List<UserDept4Flow> userDeptList = userDeptService.list(userDeptWrapper);
					if (userDeptList != null && !userDeptList.isEmpty()) {
						for (UserDept4Flow userDept : userDeptList) {
							Long userId = userDept.getUserId();
							UserEntity user = userService.getById(userId);
							if (user != null) {
								UserSelectorVO userSelectorVO = new UserSelectorVO();
								userSelectorVO.setId(String.valueOf(user.getId()));
								userSelectorVO.setParentId(organizeId);
								userSelectorVO.setType("user");
								userSelectorVO.setFullName(user.getRealName() + "/" + user.getAccount());
								userSelectorVO.setIcon("icon-ym icon-ym-tree-user2");
								userSelectorVO.setIsLeaf(true);
								jsonToList.add(userSelectorVO);
							}
						}
					}
				} else {
					deptList.forEach(dept -> {
						UserSelectorVO userSelectorVO = new UserSelectorVO();
						userSelectorVO.setId(String.valueOf(dept.getId()));
						userSelectorVO.setParentId(String.valueOf(dept.getParentId()));
						userSelectorVO.setType("department");
						userSelectorVO.setFullName(dept.getFullName());
						userSelectorVO.setEnabledMark(1);
						userSelectorVO.setIcon("icon-ym icon-ym-tree-department1");
						if (organizeService.hasChild(organizeId) || organizeService.hasUser(organizeId)) {
							userSelectorVO.setIsLeaf(false);
							userSelectorVO.setHasChildren(true);
							jsonToList.add(userSelectorVO);
						} else {
							userSelectorVO.setIsLeaf(true);
							userSelectorVO.setHasChildren(false);
						}
					});
				}
			}
		}

		return ActionResult.success(Dict.create().set("list", jsonToList));
	}

	/**
	 * 获取用户信息
	 *
	 * @param id 主键值
	 * @return
	 */
	@ApiOperation("获取用户信息")
	@GetMapping("/{id}")
	public ActionResult<UserInfoVO> getInfo(@PathVariable("id") String id) throws DataException {
		UserEntity entity = userService.getInfo(id);
		if (entity != null && !StringUtil.isEmpty(entity.getRoleId())) {
			String[] roledIds = entity.getRoleId().split(",");
			StringBuilder newRoleId = new StringBuilder();
			for (String roleId : roledIds) {
				Role4FlowEntity roleEntity = roleService.getInfo(roleId);
				if (roleEntity != null) {
					newRoleId.append(roleId + ",");
				}
			}
			if (newRoleId.length() == 0) {
				entity.setRoleId("");
			}
			if (newRoleId.length() > 0) {
				entity.setRoleId(newRoleId.substring(0, newRoleId.length() - 1));
			}
		}
		if (entity != null && !StringUtil.isEmpty(entity.getPositionId())) {
			String[] positionIds = entity.getPositionId().split(",");
			StringBuilder newPositionIds = new StringBuilder();
			for (String positionId : positionIds) {
				PositionEntity positionEntity = positionService.getInfo(positionId);
				if (positionEntity != null && positionEntity.getEnabledMark() == 1) {
					newPositionIds.append(positionId + ",");
				}
			}
			if (newPositionIds.length() == 0) {
				entity.setPositionId("");
			}
			if (newPositionIds.length() > 0) {
				entity.setPositionId(newPositionIds.substring(0, newPositionIds.length() - 1));
			}
		}
		entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
		// 去除字段为空字符串
		if (StringUtil.isEmpty(entity.getRoleId())) {
			entity.setRoleId(null);
		}
		if (StringUtil.isEmpty(entity.getPositionId())) {
			entity.setPositionId(null);
		}
		UserInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, UserInfoVO.class);
		return ActionResult.success(vo);
	}

	/**
	 * 获取用户基本信息
	 *
	 * @param userIdModel
	 * @return
	 */
	@ApiOperation("获取用户基本信息")
	@PostMapping("/getUserList")
	public ActionResult getUserList(@RequestBody UserIdModel userIdModel) {
		List<UserIdListVo> list = new ArrayList<>();
		for (String userId : userIdModel.getUserId()) {
			UserEntity entity = userService.getInfo(userId);
			if (entity == null) {
				break;
			}
			UserIdListVo vo = JsonUtil.getJsonToBean(entity, UserIdListVo.class);
			vo.setFullName(entity.getRealName() + "/" + entity.getAccount());
			list.add(vo);
		}
		ListVO listVO = new ListVO();
		listVO.setList(list);
		return ActionResult.success(listVO);
	}

}
