package org.security.auth.granter;

import lombok.extern.slf4j.Slf4j;
import org.security.auth.config.XYunProperties;
import org.security.auth.constant.AuthConstant;
import org.security.auth.service.BladeUserDetails;
import org.security.auth.service.IXYunAuthService;
import org.security.auth.utils.TokenUtil;
import org.security.system.user.entity.User;
import org.security.system.user.entity.UserInfo;
import org.security.system.user.feign.IUserClient;
import org.security.desk.xyun.res.AuthToken;
import org.security.desk.xyun.res.AuthUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 第三方登录认证类
 *
 * @author Arlex
 */
@Slf4j
public class XYunTokenGranter extends AbstractTokenGranter {
	private static final String GRANT_TYPE = "xyun";

	private final IUserClient userClient;
	private final XYunProperties xYunProperties;
	private final IXYunAuthService xYunService;

	protected XYunTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
							   OAuth2RequestFactory requestFactory, IUserClient userClient, XYunProperties xYunProperties,
							   IXYunAuthService xYunService) {
		super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.userClient = userClient;
		this.xYunProperties = xYunProperties;
		this.xYunService = xYunService;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		log.info(">>>>>> 香云端认证开始；appId：" + xYunProperties.getAppId() + "secret：" + xYunProperties.getAppSecret());
		// 请求头租户信息
		HttpServletRequest request = WebUtil.getRequest();
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);
		Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		String ticket = parameters.get("ticket");
		log.info(">>>>>> 当前ticket：" + ticket);
		if (null == ticket) {
			throw new InvalidGrantException("香云登录失败，ticket为空！");
		}
		R<AuthToken> tokenRes = xYunService.getAccessToken();
		if (!tokenRes.isSuccess()) {
			throw new InvalidGrantException(tokenRes.getMsg());
		}

		R<AuthUser> userRes = xYunService.getUserInfo(ticket, tokenRes.getData().getAccessToken());
		if (!userRes.isSuccess()) {
			throw new InvalidGrantException("香云登录失败，错误信息：" + userRes.getMsg());
		}
		AuthUser authUser = userRes.getData();
		log.info(">>>>>> 获得香云user成功：" + authUser.toString());

		R<UserInfo> clientUser = userClient.userInfo(TokenUtil.DEFAULT_TENANT_ID, authUser.getJobNo());
		if (!clientUser.isSuccess() || null == clientUser.getData() || null == clientUser.getData().getUser()) {
			throw new InvalidGrantException("香云登录失败，获取平台用户信息失败，工号：" + authUser.getJobNo());
		}
		User user = clientUser.getData().getUser();
		log.info(">>>>>> 查询平台user成功：" + user.getId() + ";" + user.getName());
		Kv detail = clientUser.getData().getDetail();
		detail.set("xYunAccessToken", tokenRes.getData().getAccessToken());
		detail.set("xYunRefreshToken", tokenRes.getData().getRefreshToken());
		BladeUserDetails bladeUserDetails = new BladeUserDetails(user.getId(), tenantId,
			clientUser.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(),
			user.getPostId(), user.getRoleId(), Func.join(clientUser.getData().getRoles()),
			Func.toStr(user.getAvatar(), TokenUtil.DEFAULT_AVATAR),
			user.getName(), authUser.getJobNo(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true,
			true, true,
			AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(clientUser.getData().getRoles())));

		log.info(">>>>>> 开始组装认证数据，关闭密码校验");
		log.info(">>>>>> 生成userAuth");
		Authentication userAuth = new UsernamePasswordAuthenticationToken(bladeUserDetails, null, bladeUserDetails.getAuthorities());
		log.info(">>>>>> setDetails");
		((AbstractAuthenticationToken) userAuth).setDetails(parameters);
		log.info(">>>>>> 组装storedOAuth2Request");
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
		log.info(">>>>>> 开始组装认证数据，关闭密码校验");

		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}

}
