package com.zzwtec.third.config.restful;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.zzwtec.third.utils.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * create by Jomchen on 2018/11/30
 */
@Configuration
public class RestfulConfig {

    @Bean
    public RestTemplate getRestful() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // fastJsonConfig.setSerializerFeatures(); 此处屏蔽以免 生成签名 和 传递签名不一致的签名失败问题
        fastConverter.setSupportedMediaTypes(
                Arrays.asList(MediaType.APPLICATION_JSON_UTF8)
        );

        RestTemplate restTemplate = new RestTemplateBuilder()
                .additionalMessageConverters(fastConverter)
                .setConnectTimeout(60000)
                .setReadTimeout(120000)
                .build();
        return restTemplate;
    }

    /**
     * 获取一个请求头，此请求头不能用单例，因为每次请求的头信息的 sign 不一样
     * 否则会引起签名错误
     */
    public static HttpHeaders getHttpHeaders(
            String key,
            String value) throws BizException {

        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
            throw new BizException("500", "请求头信息有误");
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(
                HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON_UTF8_VALUE
        );
        httpHeaders.add(key, value);
        return httpHeaders;
    }

    public static HttpHeaders getHttpHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(
                HttpHeaders.CONTENT_TYPE,
                MediaType.APPLICATION_JSON_UTF8_VALUE
        );
        return httpHeaders;
    }

}
