package test.com.leanwo;

import java.text.SimpleDateFormat;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Restful 资源类
 * @author YangZhiJie
 *
 */
public class BaseRestTemplateTest {

    private static ThreadLocal<String> tokenThreadLocal = new ThreadLocal<String>();
    
    public static void setToken(String token) {
        tokenThreadLocal.set(token);
    }
    
	/**
	 * 获取API地址
	 * @param api
	 * @return
	 */
	public String getProdogServerApiUrl(String api) {
		return "http://127.0.0.1:83" + api;
	}
	
	/**
	 * 获取请求头
	 * @return
	 */
	public HttpHeaders getHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        String token = tokenThreadLocal.get();
       // headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		headers.add("token", token);
		return headers;
	}
	

	/**
	 * 获取请求
	 * @param token
	 * @return
	 */
	public HttpEntity getHttpEntity() {
		HttpHeaders httpHeaders = getHttpHeaders();
		HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);
		return httpEntity;
	}

	/**
	 * 获取请求头
	 * @return
	 */
	public HttpHeaders getFormHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		headers.add("account", "2");
        String token = tokenThreadLocal.get();
		headers.add("token", token);
		return headers;
	}
	
	/**
	 * 获取RestTemplate
	 * @return
	 */
	public RestTemplate getRestTemplate() {
		RestTemplate restTemplate = new RestTemplate();		
		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
		 //设置日期格式  
        ObjectMapper objectMapper = new ObjectMapper();         
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        objectMapper.setDateFormat(simpleDateFormat);  
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

		restTemplate.getMessageConverters().set(0, mappingJackson2HttpMessageConverter);
		return restTemplate;
	}
}
