package com.dhcc.finance.scheduled;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.dhcc.common.constant.SysConstants;
import com.google.common.collect.ImmutableList;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Oauth2AccessTokenTask {

	public final static long refreshTime = 1000 * 60 * 3;
    
    @Autowired
    private RestTemplate loadBalancedRestTemplate;
    
    @Autowired
	ClientCredentialsResourceDetails clientCredentialsResourceDetails;
    
    /**
     * 
     * @Title: reloadApiToken
     * @Description: 刷新Token
     * @author chenrui
     * @date 2019年9月17日 下午5:50:01
     * @modifyLog：
     */
    @Scheduled(fixedDelay = refreshTime)
    public void reloadApiToken() {
    	try {
        	OAuth2AccessToken oAuth2AccessToken = loadOAuth2AccessToken();
        	System.setProperty( SysConstants.SECURITY_AUTH_TOKEN, oAuth2AccessToken.getValue());
        } catch (Exception e) {
            log.info("\r\n服务端令牌加载异常:{}", e);
        }
    }

    /**
     * 
     * @Title: loadOAuth2AccessToken
     * @Description: 
     * @return OAuth2AccessToken
     * @author chenrui
     * @date 2019年9月16日 下午3:01:51
     * @modifyLog：
     */
    private OAuth2AccessToken loadOAuth2AccessToken() {
        /*String param = "?grant_type="+grantType+"&client_id="+clientId+"&client_secret="+clientSecret;*/
    	String param = "?grant_type=" + clientCredentialsResourceDetails.getGrantType();
    	HttpEntity<String> request = new HttpEntity<String>(getHeaders());
    	try {
    		ResponseEntity<OAuth2AccessToken> response = loadBalancedRestTemplate.exchange(clientCredentialsResourceDetails.getAccessTokenUri() + param, HttpMethod.POST, request, OAuth2AccessToken.class);
    		if( response != null ) {
    			log.info("\r\n当前服务器令牌:\r\n{}", response.getBody());
    			return response.getBody();
    		}
    	}catch (HttpClientErrorException e) {
			throw e;
		}
    	return null;
    }
   
    /**
     * 
     * @Title: getHeaders
     * @Description: 
     * @return HttpHeaders
     * @author chenrui
     * @date 2019年9月16日 下午3:01:48
     * @modifyLog：
     */
    private HttpHeaders getHeaders(){
    	HttpHeaders headers = new HttpHeaders();
    	headers.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON_UTF8));
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        
        String plainClientCredentials = new StringBuilder().append(clientCredentialsResourceDetails.getClientId()).append(":").append(clientCredentialsResourceDetails.getClientSecret()).toString();
    	String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));  	
    	headers.add(HttpHeaders.AUTHORIZATION, "Basic " + base64ClientCredentials);
    	
    	return headers;
    }
}
