package com.ms.biz.tool;

import com.alibaba.fastjson.JSON;
import com.doudian.open.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * 调用外部接口工具模板类
 */
@Slf4j
@Component
public class CloudRequestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${cloud.app.key}")
    private String appKey;

    @Value("${cloud.app.secret}")
    private String appSecret;

    /**
     * POST请求
     * @param url
     * @param body
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String executePost(String url, T body) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return executePost(url, body, headers);
    }

    /**
     * POST请求
     * @param url
     * @param body
     * @param headers
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String executePost(String url, T body, HttpHeaders headers) throws Exception {
        return execute("POST", url, body, headers);
    }

    /**
     * GET请求
     * @param url
     * @param body
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String executeGet(String url, T body) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return executeGet(url, body, headers);
    }

    /**
     * GET请求
     * @param url
     * @param body
     * @param headers
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String executeGet(String url, T body, HttpHeaders headers) throws Exception {
        return execute("GET", url, body, headers);
    }

    /**
     * 通用请求
     * @param httpMethod
     * @param url
     * @param body
     * @param headers
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> String execute(String httpMethod, String url, T body, HttpHeaders headers) throws Exception {
        String appKey = "7290512081592305208";
        String appSecret = "d21bf43e-c671-4fa5-b35a-762a9c775129";

        // 添加云平台要求的头部
        String time = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        String sign = SignUtil.sign(appKey, appSecret, url, time, "{}", "v2");
        headers.set("Cloud-Url", url);
        headers.set("Cloud-HttpMethod", httpMethod);
        headers.set("Cloud-AppKey", appKey);
        headers.set("Sign", sign);
        headers.set("Timestamp", time);


        // 构建请求体
        final HttpEntity<T> requestEntity = new HttpEntity<>(body, headers);
        log.info("#executePost request: {}", JSON.toJSONString(requestEntity));

        // 请求地址
        String reqeustUrl = "http://openspi.doudian.ivolces.com/light/spi";
        // 本地开发环境，就不去请求代理地址，直接请求接口
        if(SystemTool.isDevEnv()){
            reqeustUrl = url;
        }

        // 发起请求
//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//        requestFactory.setConnectTimeout(10000); // 设置连接超时时间为5秒
//        requestFactory.setReadTimeout(20000); // 设置读取超时时间为5秒

        final ResponseEntity<byte[]> responseEntity = restTemplate.exchange(reqeustUrl, HttpMethod.POST, requestEntity, byte[].class);
        log.info("#executePost responseEntity: {}", JSON.toJSONString(responseEntity));
        if (Objects.isNull(responseEntity) || responseEntity.getStatusCodeValue() != 200 || StringUtils.isEmpty(responseEntity.getBody())) {
            throw new Exception("#executePost went wrong! ");
        }
        byte[] resp = responseEntity.getBody();
        return new String(resp);
    }
}
