/*
 *      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.springblade.modules.system.service.impl;


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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import org.springblade.common.cache.DictCache;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.cache.SysCache;
import org.springblade.common.cache.UserCache;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.DictEnum;
import org.springblade.common.utils.DigestUtil;
import org.springblade.core.constant.BladeConstant;
import org.springblade.core.constant.TokenConstant;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Post;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserApp;
import org.springblade.modules.system.entity.UserDept;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.entity.UserOauth;
import org.springblade.modules.system.entity.UserOther;
import org.springblade.modules.system.entity.UserWeb;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IPostService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserDeptService;
import org.springblade.modules.system.service.IUserOauthService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.service.normal.DataPermissionService;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
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 IRoleService roleService;
//	private final BladeTenantProperties tenantProperties;
	private final DataPermissionService dataPermissionService;

	private final IDeptService deptService;
	private final IPostService postService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(User user) {
//		if (StrUtil.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 = JSON.parseObject(decrypt, Tenant.class).getAccountNumber();
//			}
			Long 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()));
		}
		if (StrUtil.isNotBlank(user.getPhone())){
			long count = this.count(Wrappers.<User>lambdaQuery().eq(User::getPhone, user.getPhone()));
			if (count > 0){
				throw new ServiceException("该手机号已注册请更换手机号!");
			}
		}
		//.eq(User::getTenantId, tenantId)
		Long userCount = baseMapper.selectCount(Wrappers.<User>query().lambda()
				.eq(User::getAccount, user.getAccount())
				.eq(User::getTenantId, tenantId));
		if (userCount > 0 && Func.isEmpty(user.getId())) {
			throw new ServiceException(StrUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return save(user) && submitUserDept(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUser(User user) {
		String tenantId = user.getTenantId();
		Long 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(StrUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}
		return updateUserInfo(user) && submitUserDept(user);
	}

	@Override
	public boolean updateUserInfo(User user) {
		user.setPassword(null);
		if (StrUtil.isNotBlank(user.getPhone())) {
			long count = this.count(Wrappers.<User>lambdaQuery().eq(User::getPhone, user.getPhone())
					.ne(User::getId, user.getId()));
			if (count > 0){
				throw new ServiceException("该手机号已注册请更换手机号!");
			}
		}

		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) && dataPermissionService.doUpdateDept(user.getId(), deptIdList);
	}

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

	@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, String password) {
		User user = baseMapper.login(account, password);
		return buildUserInfo(user);
	}

	@Override
	public UserInfo userInfo(String tenantId, String account, String password, UserEnum userEnum) {
		User user = baseMapper.login(account, password);
		return userInfo(user, userEnum);
	}
	
	@Override
	public UserInfo userInfo(String tenantId, String openId) {
		//.eq(User::getTenantId, tenantId)
		User user = baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getOpenId, openId).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		return userInfo(user, UserEnum.APP);
	}

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

	@Override
	public UserInfo userInfo(User user, UserEnum userEnum) {
		if (ObjectUtil.isEmpty(user)) {
			return null;
		}
		UserInfo userInfo = new UserInfo();
		userInfo.setUser(user);

		// 根据每个用户平台，建立对应的detail表，通过查询将结果集写入到detail字段
		String birthDayStr = user.getBirthday() != null ? DateUtil.format(user.getBirthday(), "yyyy-MM-dd") : "";
		Kv detail = Kv.create().set("type", userEnum.getName()).set(TokenConstant.PT_SEX, user.getSex()).set(TokenConstant.PT_BIRTHDAY, birthDayStr);
		//查询blade_role的角色ID
		if(Func.isNotBlank(user.getRoleId())) {
			List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
			userInfo.setRoles(roleAlias);
			List<String> roleNames = roleService.getRoleNames(user.getRoleId());
			detail.set(TokenConstant.PT_ROLE_NAME, String.join(",", roleNames));
		}
		//查询blade_dept表的dept_code第三方集成ID值
		if(Func.isNotBlank(user.getDeptId())) {
			List<Dept> deptList = deptService.listByIds(Func.toLongList(user.getDeptId()));
			if(CollectionUtil.isNotEmpty(deptList)){
				String thirdDeptCodes = deptList.stream().map(Dept::getDeptCode).collect(Collectors.joining(","));
				String deptNames = deptList.stream().map(Dept::getDeptName).collect(Collectors.joining(","));
				userInfo.setThridDeptId(thirdDeptCodes);
				detail.set(TokenConstant.PT_DEPT_NAME, deptNames);
			}
		}
		//查询blade_post表的post_code第三方集成ID值
		if(Func.isNotBlank(user.getPostId())) {
			List<Post> postList = postService.listByIds(Func.toLongList(user.getPostId()));
			if(CollectionUtil.isNotEmpty(postList)){
				String thirdPostCodes = postList.stream().map(Post::getPostCode).collect(Collectors.joining(","));
				String postNames = postList.stream().map(Post::getPostName).collect(Collectors.joining(","));
				userInfo.setThridPostId(thirdPostCodes);
				detail.set(TokenConstant.PT_POST_NAME, postNames);
			}
		}
		//设置第三方用户ID值blade_user的code值
		userInfo.setThridUserId(user.getCode());
		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 boolean grant(String userIds, String roleIds) {
		User user = new User();
		user.setRoleId(roleIds);
		boolean ret = this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
		if(ret) { //更新权限组
			List<Long> roleIdList = Func.toLongList(roleIds);
			List<Long> userIdList = Func.toLongList(userIds);
			userIdList.forEach(userId -> dataPermissionService.doUpdateRole(userId, roleIdList));
		}
		return ret;
	}

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


	@Override
	public boolean resetPasswordV2(String userIds, String newPassword) {
		User user = new User();
		user.setPassword(DigestUtil.encrypt(newPassword));
		user.setUpdateTime(new Date());
		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.copyProperties(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() || StrUtil.isBlank(user.getTenantId())) {
//				user.setTenantId(AuthUtil.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(Func.join(SysCache.getRoleNames(user.getRoleId())));
			user.setDeptName(Func.join(SysCache.getDeptNames(user.getDeptId())));
			user.setPostName(Func.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);
		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<User> selectUserIdListByDeptId(Long deptId) {
		return baseMapper.selectUserIdListByDeptId(deptId);
	}

	@Override
	public List<User> selectUserIdListByRoleId(Long roleId) {
		return baseMapper.selectUserIdListByRoleId(roleId);
	}

	@Override
	public List<User> selectUserIdListByDeptIdList(List<Long> deptIdList) {
		return baseMapper.selectUserIdListByDeptIdList(deptIdList);
	}

	@Override
	public List<User> userInfoListByIds(List<String> userIds) {
		return baseMapper.selectBatchIds(userIds);
	}

	@Override
	public UserInfo login(String account, String password) {
		User user = baseMapper.login(account, password);
		return buildUserInfo(user);
	}

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

	@Override
	public UserInfo loginByWx(String openId) {
		User user = baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getOpenId, openId).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		return userInfo(user, UserEnum.APP);
	}
}
