package org.springblade.modules.nh.factory.ginlong;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.http.util.HttpUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.nh.factory.common.EzTemplateBase;
import org.springblade.modules.nh.factory.goodwe.GoodweRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;

@Service
public class GinlongApiRestTemplate extends EzTemplateBase {

	private String redisTokenKey = "GINLONG_TOKEN";

	private String redisIndexKey = "GINLONG_INDEX_KEY";

	@Autowired
	private BladeRedis redis;

    private static final Logger log = LoggerFactory.getLogger(GinlongApiRestTemplate.class);

    public GinlongApiRestTemplate() {
        super(createRestTemplate(createHttpRequestFactory()));
    }

    protected static ClientHttpRequestFactory createHttpRequestFactory() {
        return new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
    }

	@Override
	public <T> T postJson(int index, String url, Object data, ParameterizedTypeReference<T> responseType, Object... uriVariables) {
		try{
			redis.set(redisIndexKey,index);
			T r =  super.postJson(url, data, responseType, uriVariables);
			return r;
		}catch (Exception e){
			logger.error("postJson error:{}", e);
			return null;
		}
	}

    @Override
    protected <K> void callHeaders(String url, String data, HttpHeaders headers) {
		int index = redis.get(redisIndexKey);

        String md5 = GinlongApi.getDigest(data);
        String gmtTime = GinlongApi.getGMTTime();

		String Authorization = null;
		if(index==1){
			Authorization = GinlongApi.getAuthorization(md5, gmtTime, url, "1300386381676623064", "48b6adf9df9546e39176e9b0f020b95c");
		}else if(index==2){
			Authorization = GinlongApi.getAuthorization(md5, gmtTime, url, "1300386381677018069", "d49d515c83634cd5a785ecec7948f11a");
		}else{
			Authorization = GinlongApi.getAuthorization(md5, gmtTime, url, "1300386381676623064", "48b6adf9df9546e39176e9b0f020b95c");
		}
        headers.set("Authorization", Authorization);
        headers.set("Date", gmtTime);
        headers.set("Content-MD5", md5);
		System.out.println(JSON.toJSONString(headers));
    }


//	ginlong:
//	key: 1300386381676623064
//	secret: 48b6adf9df9546e39176e9b0f020b95c
//	锦浪
//	17712135319 nh123456
//	KeyID： 1300386381677018069 KeySecret： d49d515c83634cd5a785ecec7948f11a


	public static void main(String[] args) {

	}
}
