package com.lutao.cloud.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.lutao.cloud.admin.api.dto.UserInfo;
import com.lutao.cloud.admin.api.entity.SysUser;
import com.lutao.cloud.admin.api.feign.RemoteUserService;
import com.lutao.cloud.common.core.constant.CacheConstants;
import com.lutao.cloud.common.core.constant.CommonConstants;
import com.lutao.cloud.common.core.constant.SecurityConstants;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.common.security.exception.UserLockException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 用户详细信息
 *
 *
 */
@Slf4j
@RequiredArgsConstructor
@Configuration
public class CloudUserDetailsServiceImpl implements CloudUserDetailsService{

	private final RemoteUserService remoteUserService;

	private final CacheManager cacheManager;

	/**
	 * redis
	 */
	private final RedisTemplate redisTemplate;

	/**
	 * 用户密码登录
	 * @param username 用户名
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username){
		String loginCountKey = String.format("user:error:count:%s",username);
		BoundValueOperations valueOps = redisTemplate.boundValueOps(loginCountKey);
		Long count = valueOps.increment(0);
		Long ttl = valueOps.getExpire();
		if (ttl.equals(-1)) {
			valueOps.expire(600, TimeUnit.SECONDS);
		} else {
			valueOps.expire(ttl,TimeUnit.SECONDS);
		}
		log.info("username:{}  登录次数:{}",username,count);
		if (count >= 5) {
			throw new UserLockException("登录错误次数超过5次，账号锁定10分钟",null);
		}
		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
		if (cache != null && cache.get(username) != null){
			return cache.get(username, CloudUser.class);
		}

		MessageInfo<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
		CloudUser userDetails = getUserDetails(result);
		cache.put(username, userDetails);
		return userDetails;
	}

	/**
	 * 根据社交登录code 登录
	 * @param inStr TYPE@CODE
	 * @return UserDetails
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserBySocial(String inStr){
		return getUserDetails(remoteUserService.social(inStr, SecurityConstants.FROM_IN));
	}

	/**
	 * 构建UserDetails
	 * @param result 用户信息
	 * @return UserDetails
	 */
	public CloudUser getUserDetails(MessageInfo<UserInfo> result){
		if (result == null || result.getData() == null){
			throw new UsernameNotFoundException("用户不存在");
		}

		UserInfo info = result.getData();
		Set<String> dbAuthsSet = new HashSet<>();
		if (ArrayUtil.isNotEmpty(info.getRoles())){
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
			// 获取资源
			dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();
		boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
		// 构造security用户

		return new CloudUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getTenantId(),
				user.getUsername(), "{cloud}"+user.getPassword(), enabled, true, true,
				!CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities,user.getNickname(),
				user.getEmail(),user.getUserFrom());//,user.getThirdAuthId()
	}

}
