package api;

import com.fasterxml.jackson.core.type.TypeReference;
import com.sunyard.chsm.model.R;
import com.sunyard.chsm.param.AppTokenReq;
import com.sunyard.chsm.param.AppTokenResp;
import com.sunyard.chsm.utils.JsonUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author liulu
 * @since 2024/12/17
 */
public abstract class BaseTest {

    protected static final String ak = "216205d408130d83d13c5072305b8b65";
    protected static final String sk = "ae64515d1d5adec2cc6ae8726d0c1bbc";
    protected static final String server = "http://127.0.0.1:8900";
    protected static final RestTemplate restTemplate;
    protected static final String token;

    static {
        AppTokenReq req = new AppTokenReq();
        req.setAppKey(ak);
        req.setHmac(sk);
        req.setRandom(System.currentTimeMillis());

        RequestEntity<byte[]> request = RequestEntity.post(server + "/appUser/getAppTokenTest")
                .contentType(MediaType.APPLICATION_JSON)
                .body(JsonUtils.toJsonBytes(req));
        ResponseEntity<String> response = new RestTemplate().exchange(request, String.class);
        try {
            R<AppTokenResp> r = JsonUtils.objectMapper()
                    .readValue(response.getBody(), new TypeReference<R<AppTokenResp>>() {
                    });
            token = r.getResult().getToken();
            restTemplate = new RestTemplateBuilder()
                    .rootUri(server)
                    .defaultHeader("Authorization", "Bearer " + token)
                    .defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
                    .build();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected static <T> T execute(String url, Object req, Class<T> tClass) {
        try {
            RequestEntity<byte[]> request = RequestEntity.post("/appUser/getAppTokenTest")
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("Authorization", "Bearer " + token)
                    .body(JsonUtils.toJsonBytes(req));

            byte[] res = restTemplate.postForObject(url, JsonUtils.toJsonBytes(req), byte[].class);
            R<T> r = JsonUtils.objectMapper()
                    .readValue(res, new TypeReference<R<T>>() {
                    });
            return r.getResult();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
