package com.ruoyi.api.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.api.constant.yz.ApiEnum;
import com.ruoyi.api.downstream.YzResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class YzResultProcessingUtil {
    private static String url;

    @Value("${downstream.url}")
    public void setUrl(String url) {
        YzResultProcessingUtil.url = url;
    }

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static YzResult getYzResult(ApiEnum apiEnum, Object bo) throws JsonProcessingException {
        objectMapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);

        String data = objectMapper.writeValueAsString(bo);
        System.out.println("data: " + data);

        String realUrl = url + apiEnum.getUrl();
        String method = apiEnum.getMethod().toString();
        ResponseEntity<String> responseEntity = null;

        switch (method) {
            case "GET":
                responseEntity = HttpUtil.sendGetWithHeaders(realUrl, data);
                break;
            case "POST":
                responseEntity = HttpUtil.sendPostWithHeaders(realUrl, data);
                break;
            case "DELETE":
                responseEntity = HttpUtil.sendDeleteWithHeaders(realUrl, data);
                break;
        }

        assert responseEntity != null;
        return objectMapper.readValue(Objects.requireNonNull(responseEntity.getBody()), YzResult.class);
    }
}
