/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.security.system.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.common.constant.CommonConstant;
import org.security.common.constant.TenantConstant;
import org.security.flow.core.enums.CandidateTypeEnum;
import org.security.system.cache.DictCache;
import org.security.system.cache.ParamCache;
import org.security.system.cache.SysCache;
import org.security.system.entity.Role;
import org.security.system.entity.Tenant;
import org.security.system.enums.DictEnum;
import org.security.system.feign.ISysClient;
import org.security.system.user.cache.UserCache;
import org.security.system.user.entity.*;
import org.security.system.user.enums.UserEnum;
import org.security.system.user.excel.UserExcel;
import org.security.system.user.mapper.UserMapper;
import org.security.system.user.service.IUserDeptService;
import org.security.system.user.service.IUserOauthService;
import org.security.system.user.service.IUserService;
import org.security.system.user.vo.UserVO;
import org.security.system.user.wrapper.UserWrapper;
import org.security.system.vo.DeptVO;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static org.security.common.constant.CommonConstant.DEFAULT_PARAM_PASSWORD;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {
	private static final String GUEST_NAME = "guest";

	private final IUserDeptService userDeptService;
	private final IUserOauthService userOauthService;
	private final ISysClient sysClient;
	private final BladeTenantProperties tenantProperties;
	private final UserMapper userMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R submit(User user) {
		if (StringUtil.isBlank(user.getTenantId())) {
			user.setTenantId(BladeConstant.ADMIN_TENANT_ID);
		}
		String tenantId = user.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		if (Func.isNotEmpty(user.getPassword())) {
			user.setPassword(DigestUtil.encrypt(user.getPassword()));
		}

		R<String> checkRoleUserNums = checkRoleUserNums(user.getRoleId(), user.getId());
		if (!checkRoleUserNums.isSuccess()) {
			return checkRoleUserNums;
		}
		Integer userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
		if (userCount > 0 && Func.isEmpty(user.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return R.status(save(user) && submitUserDept(user));
	}

	@Override
	public R userHasRoleAlias(String tenantId, Long userId, String roleAlias) {
		boolean result = false;
		Role roleByAlias = userMapper.getRoleByAlias(roleAlias);
		if (null != roleByAlias) {
			User user = userMapper.userHasRoleAlias(tenantId, userId, roleByAlias.getId());
			if (null != user) {
				result = true;
			}
		}
		return R.data(result);
	}

	private R<String> checkRoleUserNums(String roleIds, Long userId) {
		if (userId == null) {
			return R.success("操作成功");
		}
		List<String> roleIdList = Func.toStrList(roleIds);
		for (String roleId : roleIdList) {
			Role role = userMapper.getRoleById(Long.valueOf(roleId));
			String userNums = role.getUserNums();
			int userRoleNums = countUserByRole(roleId, userId);
			//判断对应角色用户数量是否达到角色限制数量
			//角色配置数量为null/""不限制
			if (StringUtil.isNotBlank(userNums)) {
				if (userRoleNums >= Integer.parseInt(userNums)) {
					return R.fail(StringUtil.format("角色[{}]已达限制数量", role.getRoleName()));
				}
			}
		}

		return R.success("操作成功");
	}

	/**
	 * 根据角色统计该角色人数
	 *
	 * @param roleId 角色ID
	 * @return
	 */
	private int countUserByRole(String roleId, Long userId) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("ROLE_ID", roleId);
		queryWrapper.ne("ID", userId);
		return baseMapper.selectCount(queryWrapper);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateUser(User user) {
		String tenantId = user.getTenantId();
		Integer userCount = baseMapper.selectCount(
			Wrappers.<User>query().lambda()
				.eq(User::getTenantId, tenantId)
				.eq(User::getAccount, user.getAccount())
				.notIn(User::getId, user.getId())
		);
		if (userCount > 0) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		R<String> checkRoleUserNums = checkRoleUserNums(user.getRoleId(), user.getId());
		if (!checkRoleUserNums.isSuccess()) {
			return checkRoleUserNums;
		}
		return R.status(updateUserInfo(user) && submitUserDept(user));
	}

	@Override
	public boolean updateUserInfo(User user) {
		user.setPassword(null);
		return updateById(user);
	}

	private boolean submitUserDept(User user) {
		List<Long> deptIdList = Func.toLongList(user.getDeptId());
		List<UserDept> userDeptList = new ArrayList<>();
		deptIdList.forEach(deptId -> {
			UserDept userDept = new UserDept();
			userDept.setUserId(user.getId());
			userDept.setDeptId(deptId);
			userDeptList.add(userDept);
		});
		userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
		return userDeptService.saveBatch(userDeptList);
	}

	@Override
	public IPage<User> selectUserPage(IPage<User> page, User user, Long deptId, String tenantId) {
		List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
		return page.setRecords(baseMapper.selectUserPage(page, user, deptIdList, tenantId));
	}

	@Override
	public IPage<UserVO> selectUserSearch(UserVO user, Query query) {
		LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
		if (StringUtil.isNotBlank(user.getName())) {
			queryWrapper.like(User::getName, user.getName());
		}
		if (StringUtil.isNotBlank(user.getDeptName())) {
			String deptIds = SysCache.getDeptIdsByFuzzy(AuthUtil.getTenantId(), user.getDeptName());
			if (StringUtil.isNotBlank(deptIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(deptIds);
					ids.forEach(id -> wrapper.like(User::getDeptId, id).or());
				});
			}
		}
		if (StringUtil.isNotBlank(user.getPostName())) {
			String postIds = SysCache.getPostIdsByFuzzy(AuthUtil.getTenantId(), user.getPostName());
			if (StringUtil.isNotBlank(postIds)) {
				queryWrapper.and(wrapper -> {
					List<String> ids = Func.toStrList(postIds);
					ids.forEach(id -> wrapper.like(User::getPostId, id).or());
				});
			}
		}
		IPage<User> pages = this.page(Condition.getPage(query), queryWrapper);
		return UserWrapper.build().pageVO(pages);
	}

	@Override
	public User userByAccount(String tenantId, String account) {
		return baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
	}

	@Override
	public UserInfo userInfo(Long userId) {
		User user = baseMapper.selectById(userId);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account) {
		User user = baseMapper.getUser(tenantId, account);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, UserEnum userEnum) {
		User user = baseMapper.getUser(tenantId, account);
		return buildUserInfo(user, userEnum);
	}

	private UserInfo buildUserInfo(User user) {
		return buildUserInfo(user, UserEnum.WEB);
	}

	private UserInfo buildUserInfo(User user, UserEnum userEnum) {
		if (ObjectUtil.isEmpty(user)) {
			return null;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);
		if (Func.isNotEmpty(user)) {
			R<List<String>> result = sysClient.getRoleAliases(user.getRoleId());
			if (result.isSuccess()) {
				List<String> roleAlias = result.getData();
				userInfo.setRoles(roleAlias);
			}
		}
		// 根据每个用户平台，建立对应的detail表，通过查询将结果集写入到detail字段
		Kv detail = Kv.create().set("type", userEnum.getName());
		if (userEnum == UserEnum.WEB) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else if (userEnum == UserEnum.APP) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				detail.set("ext", query.getUserExt());
			}
		}
		userInfo.setDetail(detail);
		return userInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public UserInfo userInfo(UserOauth userOauth) {
		UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
		UserInfo userInfo;
		if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
			userInfo = this.userInfo(uo.getUserId());
			userInfo.setOauthId(Func.toStr(uo.getId()));
		} else {
			userInfo = new UserInfo();
			if (Func.isEmpty(uo)) {
				userOauthService.save(userOauth);
				userInfo.setOauthId(Func.toStr(userOauth.getId()));
			} else {
				userInfo.setOauthId(Func.toStr(uo.getId()));
			}
			User user = new User();
			user.setAccount(userOauth.getUsername());
			user.setTenantId(userOauth.getTenantId());
			userInfo.setUser(user);
			userInfo.setRoles(Collections.singletonList(GUEST_NAME));
		}
		return userInfo;
	}

	@Override
	public R grant(String userIds, String roleIds) {
		List<String> idList = Func.toStrList(userIds);
		for (String userId : idList) {
			R<String> checkRoleUserNums = checkRoleUserNums(roleIds, Long.valueOf(userId));
			if (!checkRoleUserNums.isSuccess()) {
				return checkRoleUserNums;
			}
		}

		User user = new User();
		user.setRoleId(roleIds);
		return R.status(this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds))));
	}

	@Override
	public boolean resetPassword(String userIds) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
		user.setUpdateTime(DateUtil.now());
		return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
	}

	@Override
	public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
		User user = getById(userId);
		if (!newPassword.equals(newPassword1)) {
			throw new ServiceException("请输入正确的确认密码!");
		}
		if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
			throw new ServiceException("原密码不正确!");
		}
		return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
	}

	@Override
	public boolean removeUser(String userIds) {
		if (Func.contains(Func.toLongArray(userIds), AuthUtil.getUserId())) {
			throw new ServiceException("不能删除本账号!");
		}
		return deleteLogic(Func.toLongList(userIds));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void importUser(List<UserExcel> data, Boolean isCovered) {
		data.forEach(userExcel -> {
			User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
			// 设置用户平台
			user.setUserType(Func.toInt(DictCache.getKey(DictEnum.USER_TYPE, userExcel.getUserTypeName()), 1));
			// 设置部门ID
			user.setDeptId(SysCache.getDeptIds(userExcel.getTenantId(), userExcel.getDeptName()));
			// 设置岗位ID
			user.setPostId(SysCache.getPostIds(userExcel.getTenantId(), userExcel.getPostName()));
			// 设置角色ID
			user.setRoleId(SysCache.getRoleIds(userExcel.getTenantId(), userExcel.getRoleName()));
			// 设置租户ID
			if (!AuthUtil.isAdministrator() || StringUtil.isBlank(user.getTenantId())) {
				user.setTenantId(AuthUtil.getTenantId());
			}
			// 覆盖数据
			if (isCovered) {
				// 查询用户是否存在
				User oldUser = UserCache.getUser(userExcel.getTenantId(), userExcel.getAccount());
				if (oldUser != null && oldUser.getId() != null) {
					user.setId(oldUser.getId());
					this.updateUser(user);
					return;
				}
			}
			// 获取默认密码配置
			String initPassword = ParamCache.getValue(DEFAULT_PARAM_PASSWORD);
			user.setPassword(initPassword);
			this.submit(user);
		});
	}

	@Override
	public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
		List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
		userList.forEach(user -> {
			user.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
			user.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
			user.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
			user.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
		});
		return userList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean registerGuest(User user, Long oauthId) {
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		if (tenant == null || tenant.getId() == null) {
			throw new ServiceException("租户信息错误!");
		}
		UserOauth userOauth = userOauthService.getById(oauthId);
		if (userOauth == null || userOauth.getId() == null) {
			throw new ServiceException("第三方登陆信息错误!");
		}
		user.setRealName(user.getName());
		user.setAvatar(userOauth.getAvatar());
		user.setRoleId(StringPool.MINUS_ONE);
		user.setDeptId(StringPool.MINUS_ONE);
		user.setPostId(StringPool.MINUS_ONE);
		boolean userTemp = this.submit(user).isSuccess();
		userOauth.setUserId(user.getId());
		userOauth.setTenantId(user.getTenantId());
		boolean oauthTemp = userOauthService.updateById(userOauth);
		return (userTemp && oauthTemp);
	}

	@Override
	public boolean updatePlatform(Long userId, Integer userType, String userExt) {
		if (userType.equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userWeb.setId(query.getId());
			}
			userWeb.setUserId(userId);
			userWeb.setUserExt(userExt);
			return userWeb.insertOrUpdate();
		} else if (userType.equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userApp.setId(query.getId());
			}
			userApp.setUserId(userId);
			userApp.setUserExt(userExt);
			return userApp.insertOrUpdate();
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, userId));
			if (ObjectUtil.isNotEmpty(query)) {
				userOther.setId(query.getId());
			}
			userOther.setUserId(userId);
			userOther.setUserExt(userExt);
			return userOther.insertOrUpdate();
		}
	}

	@Override
	public UserVO platformDetail(User user) {
		User detail = baseMapper.selectOne(Condition.getQueryWrapper(user));
		UserVO userVO = UserWrapper.build().entityVO(detail);
		if (userVO.getUserType().equals(UserEnum.WEB.getCategory())) {
			UserWeb userWeb = new UserWeb();
			UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else if (userVO.getUserType().equals(UserEnum.APP.getCategory())) {
			UserApp userApp = new UserApp();
			UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		} else {
			UserOther userOther = new UserOther();
			UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
			if (ObjectUtil.isNotEmpty(query)) {
				userVO.setUserExt(query.getUserExt());
			}
		}
		return userVO;
	}

	@Override
	public List<UserVO> getUserListByDepIds(String deptIds) {
//		List<Long> depIds = Func.toLongList(deptIds);
		List<String> depIds = Func.toStrList(deptIds);
//		Long depId = depIds.get(depIds.size() - 1);
		String depId = depIds.get(depIds.size() - 1);
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(User::getDeptId, depId);
		List<User> userList = this.list(queryWrapper);
		List<UserVO> userVOList = setUserVOS(userList);
		return userVOList;
	}

	@Override
	public List<UserVO> getListByRole(String roleId) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("ROLE_ID", roleId);
		List<User> users = baseMapper.selectList(queryWrapper);
		return Func.copy(users, UserVO.class);
	}

	@Override
	public IPage<UserVO> getUserDeptUserList(Query query) {
		Page<User> page = new Page<>(query.getCurrent(), query.getSize());
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("DEPT_ID", AuthUtil.getDeptId());
		IPage<User> userIPage = baseMapper.selectPage(page, queryWrapper);
		List<User> userList = userIPage.getRecords();
		List<UserVO> voList = userList.stream()
			.map(user -> {
				UserVO userVO = Func.copy(user, UserVO.class);
				userVO.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
				userVO.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
				userVO.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
				userVO.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
				return userVO;
			}).collect(Collectors.toList());
		IPage<UserVO> res = new Page<>();
		res.setRecords(voList);
		res.setCurrent(userIPage.getCurrent());
		res.setSize(userIPage.getSize());
		res.setPages(userIPage.getPages());
		res.setTotal(userIPage.getTotal());
		return res;
	}

	@Override
	public List<UserVO> userData() {
		return baseMapper.userData();
	}

	@Override
	public UserVO getUserByCode(String code) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("code", code);
		User user = baseMapper.selectOne(queryWrapper);
		return BeanUtil.copy(user, UserVO.class);
	}

	@Override
	public List<UserVO> getBranchLeaders(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的分行领导开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.BRANCH_LEADER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找分行领导角色失败！");
			throw new ServiceException("查找分行领导角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		String deptId = user.getDeptId();
		log.info(">>>>>>>>>>>> 获取到参数用户部门:" + deptId);
		R<List<DeptVO>> dept = sysClient.getBranchDeptAll(Long.valueOf(deptId));
		if (!dept.isSuccess()) {
			log.error(">>>>>>>>>>>> 查找分行部门失败！");
			throw new ServiceException("查找分行部门失败！");
		}
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.in(User::getDeptId, dept.getData().stream().map(DeptVO::getId).collect(Collectors.toList()))
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取分行领导结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public boolean removeUserDept(List<String> userIds) {
		return baseMapper.removeUserDept(userIds);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveUserDept(List<UserDept> userDeptList) {
		userDeptList.forEach(item ->{
			UserDept userDept = new UserDept();
			userDept.setUserId(item.getUserId());
			userDept.setDeptId(item.getDeptId());
			userDeptService.save(userDept);
		});
		return false;
	}

	@Override
	public boolean saveUserData(List<User> userList) {
		return this.saveOrUpdateBatch(userList);
	}

	@Override
	public List<UserVO> getHeadLeaders(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的总行领导开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户 " + userId + " 不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.HEAD_LEADER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找总行领导角色失败！");
			throw new ServiceException("查找总行领导角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		// String deptId = user.getDeptId();
		// R<Dept> dept = sysClient.getHeadDept(Long.valueOf(deptId));
		// if (!dept.isSuccess()) {
		// 	throw new ServiceException("查找总行部门失败！");
		// }
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取总行领导结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getHeadSecLeaders(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的总行安全部部门领导开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户 " + userId + " 不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.HEAD_SEC_LEADER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找总行安保部领导角色失败！");
			throw new ServiceException("查找总行安保部领导角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		// String deptId = user.getDeptId();
		// R<Dept> dept = sysClient.getHeadDept(Long.valueOf(deptId));
		// if (!dept.isSuccess()) {
		// 	throw new ServiceException("查找总行部门失败！");
		// }
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取总行安全部部门领导结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getHeadSafers(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的总行安全员开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.HEAD_SAFER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找总行安全员角色失败！");
			throw new ServiceException("查找总行安全员角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		// String deptId = user.getDeptId();
		// R<Dept> dept = sysClient.getHeadDept(Long.valueOf(deptId));
		// if (!dept.isSuccess()) {
		// 	throw new ServiceException("查找总行部门失败！");
		// }
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取总行安全员结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getBranchSafers(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的分行安全员开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.BRANCH_SAFER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找分行安全员角色失败！");
			throw new ServiceException("查找分行安全员角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		String deptId = user.getDeptId();
		log.info(">>>>>>>>>>>> 获取到参数用户部门:" + deptId);
		R<List<DeptVO>> dept = sysClient.getBranchDeptAll(Long.valueOf(deptId));
		if (!dept.isSuccess()) {
			log.error(">>>>>>>>>>>> 查找分行部门失败！");
			throw new ServiceException("查找分行部门失败！");
		}
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.in(User::getDeptId, dept.getData().stream().map(DeptVO::getId).collect(Collectors.toList()))
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取分行安全员结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getSubLeaders(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的支行领导开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.SUB_LEADER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找支行领导角色失败！");
			throw new ServiceException("查找支行领导角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		String deptId = user.getDeptId();
		log.info(">>>>>>>>>>>> 获取到参数用户部门:" + deptId);
		R<List<DeptVO>> dept = sysClient.getSubDeptAll(Long.valueOf(deptId));
		if (!dept.isSuccess()) {
			log.error(">>>>>>>>>>>> 查找支行部门失败！");
			throw new ServiceException("查找支行部门失败！");
		}
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.in(User::getDeptId, dept.getData().stream().map(DeptVO::getId).collect(Collectors.toList()))
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取支行领导结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getSubSafers(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的支行安全员开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.SUB_SAFER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找支行安全员角色失败！");
			throw new ServiceException("查找支行安全员角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		String deptId = user.getDeptId();
		log.info(">>>>>>>>>>>> 获取到参数用户部门:" + deptId);
		R<List<DeptVO>> dept = sysClient.getSubDeptAll(Long.valueOf(deptId));
		if (!dept.isSuccess()) {
			log.error(">>>>>>>>>>>> 查找支行部门失败！");
			throw new ServiceException("查找支行部门失败！");
		}
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.in(User::getDeptId, dept.getData().stream().map(DeptVO::getId).collect(Collectors.toList()))
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取支行安全员结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getDeptLeader(Long userId) {
		log.info(">>>>>>>>>>>> 获取用户id为:" + userId + " 的部门领导开始");
		User user = baseMapper.selectById(userId);
		if (Func.isNull(user)) {
			log.error(">>>>>>>>>>>> 参数用户 " + userId + " 不存在！");
			throw new ServiceException("参数用户不存在！");
		}
		R<String> role = sysClient.getRoleIdsByAlias(user.getTenantId(), CandidateTypeEnum.DEPT_LEADER.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找部门领导角色失败！");
			throw new ServiceException("查找部门领导角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		String deptId = user.getDeptId();
		log.info(">>>>>>>>>>>> 获取到参数用户部门:" + deptId);
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.eq(User::getDeptId, deptId)
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取部门领导结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getHeadSecCenterAll() {
		log.info(">>>>>>>>>>>> 获取总行安保指挥中心全员开始");
		R<String> role = sysClient.getRoleIdsByAlias("000000", CandidateTypeEnum.HEAD_SEC_CENTER_ALL.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找总行安保指挥中心角色失败！");
			throw new ServiceException("查找总行安保指挥中心角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取总行安保指挥中心全员结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getBranchSecCenterAll() {
		log.info(">>>>>>>>>>>> 获取分行安保指挥中心全员开始");
		R<String> role = sysClient.getRoleIdsByAlias("000000", CandidateTypeEnum.BRANCH_SEC_CENTER_ALL.getValue());
		if (!role.isSuccess() || null == role.getData()) {
			log.error(">>>>>>>>>>>> 查找分行安保指挥中心角色失败！");
			throw new ServiceException("查找分行安保指挥中心角色失败！");
		}
		String roleId = role.getData();
		log.info(">>>>>>>>>>>> 获取到角色:" + roleId);
		LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
			.like(User::getRoleId, roleId);
		List<User> leaders = baseMapper.selectList(wrapper);
		log.info(">>>>>>>>>>>> 获取分行安保指挥中心全员结束");
		return UserWrapper.build().listVO(leaders);
	}

	@Override
	public List<UserVO> getSccSafeRoleUser(String deptIds) {
		List<String> depIds = Func.toStrList(deptIds);
		String deptId = depIds.get(depIds.size() - 1);
		//获取该机构的机构层级
		String deptLevel = baseMapper.getDeptLevel(deptId);
		String roleName = null;
		if ("3".equals(deptLevel)){
			roleName = "支行安全员";
		}
		if ("2".equals(deptLevel)){
			roleName = "分行安全员";
		}
		if ("1".equals(deptLevel)){
			roleName = "总行安全员";
		}
		List<User> userList = baseMapper.getAimUserData(roleName,deptId);
		List<UserVO> userVOList = setUserVOS(userList);
		return userVOList;
	}

	@Override
	public List<UserVO> getUserByRoleId(String roleId) {
		List<User> list = this.list(new QueryWrapper<User>().lambda().like(Func.isNotEmpty(roleId), User::getRoleId, roleId));
		return Func.copy(list,UserVO.class);
	}

	@Override
	public List<UserVO> getInspectionSafeRoleUser(String deptIds) {
		if (Func.isNotEmpty(deptIds)){
			deptIds = AuthUtil.getDeptId();
		}
		//获取子级机构id
		List<String> list = baseMapper.getChildDeptIds(deptIds);
		list.add(deptIds);
		//获取相关机构的安全员用户信息
		List<UserVO> userList = baseMapper.getInspectionSafeRoleUser(list);
		return userList;
	}

	@Override
	public List<UserVO> getWorkFilingUsers(String userType) {
		List<UserVO> vos = new ArrayList<>();
		//获取当前登录人的的机构祖级id
		String ancestors = baseMapper.getAncestorsDepts(AuthUtil.getDeptId());
		String s = ancestors.concat(",").concat(AuthUtil.getDeptId());
		List<String> list = Arrays.asList(s.split(","));
		//获取本级及上级的安全员及安全员管理用户
		if (Func.isNotEmpty(userType) && "2".equals(userType)){
			List<String> aimRoleList = getAimRoleIds();
			vos = baseMapper.getAimWorkFilingUser(list,aimRoleList);
			return vos;
		}
		//获取本级及上级的所有用户
		vos = baseMapper.getAllWorkFilingUser(list);
		return vos;
	}

	/**
	 *获取目标角色id
	 */
	private List<String> getAimRoleIds() {
		//目标角色列表
		List<String> roleList = new ArrayList<>();
		roleList.add("安全员");
		//获取该机构的机构层级
		String deptLevel = baseMapper.getDeptLevel(AuthUtil.getDeptId());
		if ("3".equals(deptLevel)){
			roleList.add("支行安全领导");
			roleList.add("分行安全领导");
			roleList.add("总行安全领导");
		}
		if ("2".equals(deptLevel)){
			roleList.add("分行安全领导");
			roleList.add("总行安全领导");
		}
		if ("1".equals(deptLevel)){
			roleList.add("总行安全领导");
		}
		//获取目标角色id
		return baseMapper.getAimRoleListIds(roleList);
	}

	private List<UserVO> setUserVOS(List<User> userList) {
		List<UserVO> userVOList = Func.copy(userList, UserVO.class);
		userVOList.forEach(item -> {
			item.setKey(item.getId());
			item.setValue(item.getRealName());
		});
		return userVOList;
	}

	@Override
	public R getUsersByUserIds(String userIds) {
		List<User> list = this.list(Wrappers.<User>query().lambda().in(User::getId, Func.toLongList(userIds)));
		return R.data(list);
	}
}
