package com.ruoyi.api.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.api.service.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Http工具包
 */
@Component
public final class HttpUtil {
    private static RestTemplate restTemplate;
    private static ITokenService tokenService;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        HttpUtil.restTemplate = restTemplate;
    }

    @Autowired
    public void setTokenService(ITokenService tokenService) {
        HttpUtil.tokenService = tokenService;
    }

    /**
     * 发送post请求：带请求头
     *
     * @param data
     * @param url
     * @return
     */
    public static ResponseEntity<String> sendPostWithHeaders(String url, String data) {
        HttpHeaders headers = getDefaultHeaders();
        JSONObject jsonObject = JSONObject.parseObject(data);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
        return restTemplate.postForEntity(url, httpEntity, String.class);
    }

    /**
     * 发送delete请求：带请求头
     *
     * @param data
     * @param url
     * @return
     */
    public static ResponseEntity<String> sendDeleteWithHeaders(String url, String data) {
        HttpHeaders headers = getDefaultHeaders();
        JSONObject jsonObject = JSONObject.parseObject(data);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
        return restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
    }

    /**
     * 获取默认请求头
     *
     * @return
     */
    private static HttpHeaders getDefaultHeaders() {
        String token = null;
        try {
            token = tokenService.getToken();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json;charset=UTF-8");
        headers.set("x-token", token);
        return headers;
    }
}
