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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.http.util.HttpUtil;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.nh.factory.common.EzTemplateBase;
import org.springblade.modules.nh.factory.saj.resp.SajRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

import java.util.Map;

@Service
@AllArgsConstructor
public class SajApiRestTemplate extends EzTemplateBase {

    public static String appId = "VH_dTjpujU4";
	private String appSecret = "bpRNe3ChgQ6SiqLc0hnDV6ukujU4PB16aNyr91VJRNrkdTjpLCArYpYjXjKiZhxx";

	@Autowired
	private BladeRedis redis;

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

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

	@Override
	public <T> T get(String url, Map<String, ?> uriVariables, ParameterizedTypeReference<T> responseType) throws RestClientException {
		HttpHeaders headers = new HttpHeaders();
		HttpHeaders httpHeaders = HttpHeaders.writableHttpHeaders(headers);
		callSajHeaders(url, uriVariables, httpHeaders);
		HttpEntity<String> entity = new HttpEntity<>(null, httpHeaders);
		T t = super.exchange(url, HttpMethod.GET, entity, responseType, uriVariables).getBody();
		if(t instanceof SajRet){
			SajRet ret = (SajRet) t;
			if(ret.getCode()==200010){
				if(!redis.exists("saj_access_token_count")){
					redis.del("saj_access_token");
					redis.setEx("saj_access_token_count",1,60L);
					return get(url, uriVariables, responseType);
				}
			}
		}
		return t;
	}

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

    private <K> void callSajHeaders(String url, Map<String, ?> param, HttpHeaders headers) {
        headers.set("accessToken", getAccessToken());
        headers.set("clientSign", CommonUtil.genSign(param));
        headers.set("content-language", "zh_CN");
    }

	private String getAccessToken() {
		String accessToken = redis.get("saj_access_token");
		if (StringUtil.isBlank(accessToken)) {
			// access_token not exists or expired
			Map<String, Object> paramMap = Maps.newHashMap();
			paramMap.put("appId", appId);
			paramMap.put("appSecret", appSecret);
			String accessTokenUrl = "https://developer.saj-electric.cn/prod-api/open/api/access_token";
			String resp = HttpUtil.get(accessTokenUrl, paramMap);
			JSONObject json = JSON.parseObject(resp);
			if(json.getIntValue("code")==200){
				JSONObject data = json.getJSONObject("data");
				accessToken = data.getString("access_token");
//				accessTokenExpires = data.getIntValue("expires");
				if(StringUtil.isNotBlank(accessToken)){
					redis.setEx("access_token",accessToken,3600L);
				}
			}
		}
		return accessToken;
	}


	public static void main(String[] args) {
		SajApiRestTemplate restTemplate = new SajApiRestTemplate();
		System.out.println(restTemplate.getAccessToken());
	}
}
