package com.kxs.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.kxs.common.core.constant.CacheConstants;
import com.kxs.common.core.constant.CommonConstants;
import com.kxs.common.core.constant.SecurityConstants;
import com.kxs.common.core.constant.enums.ErrorTypeEnum;
import com.kxs.common.core.util.R;
import com.kxs.common.core.util.RetOps;
import com.kxs.common.security.model.KxsUser;
import com.kxs.system.api.dto.UserDTO;
import com.kxs.system.api.dto.UserInfo;
import com.kxs.system.api.feign.RemoteUserService;
import com.kxs.system.api.model.SysUser;
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.Primary;
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 org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 继承 oauth2 security实现类登录
 * </p>
 *
 * @author 没秃顶的码农 hccake
 */
@Slf4j
@Primary
@RequiredArgsConstructor
@Service
public class KxsUserDetailsServiceImpl implements KxsUserDetailsService {

	private final RemoteUserService remoteUserService;

	private final CacheManager cacheManager;

	/**
	 * 用户名密码登录
	 * @param username 用户名
	 * @return 用户详细信息
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
		if (cache != null && cache.get(username) != null) {
			return (KxsUser) Objects.requireNonNull(cache.get(username)).get();
		}

		UserDTO userDTO = new UserDTO();
		userDTO.setUsername(username);
		R<UserInfo> result = remoteUserService.info(userDTO, SecurityConstants.FROM_IN);

		UserInfo info = RetOps.of(result)
			.getData()
			.orElseThrow(() -> new UsernameNotFoundException(ErrorTypeEnum.USER_NOT_FOUND.getDescription()));
		UserDetails userDetails = getUserDetails(info);

		if (cache != null) {
			cache.put(username, userDetails);
		}
		return userDetails;
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE;
	}

	/**
	 * 获取用户详细信息
	 * @param info 用户信息
	 * @return UserDetails
	 */
	private UserDetails getUserDetails(UserInfo info) {
		if (info == null) {
			throw new UsernameNotFoundException("用户不存在");
		}

		Set<String> dbAuthsSet = new HashSet<>();

		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
			// 获取资源
			dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

		}

		Collection<GrantedAuthority> authorities = AuthorityUtils
			.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();

		// 构造security用户
		return new KxsUser(user.getUserId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
				user.getPhone(), true, true, true, StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL),
				authorities);
	}

}
