package cn.sikey.tools.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: qin
 * @Date: 2025/3/26
 * @Description: OkHttpUtil
 */
@Slf4j
@Component
public class OkHttpUtil {

    @Resource
    private OkHttpClient okHttpClientHttps;

    /**
     * get
     *
     * @param deviceId 设备编码
     * @param url      请求的url
     * @param queries  请求的参数，在浏览器？后面的数据，没有可以传null
     * @param header   请求header
     * @return
     */
    public Response get(String deviceId, String url, Map<String, Object> queries, String header) throws IOException {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && !queries.isEmpty()) {
            boolean firstFlag = true;
            Iterator<Map.Entry<String, Object>> iterator = queries.entrySet().iterator();
            iterator(sb, firstFlag, iterator);
        }
        Request request = new Request.Builder().addHeader("Authorization", header).addHeader("X-Request-ID", deviceId).url(sb.toString()).build();
        return okHttpClientHttps.newCall(request).execute();
    }

    private void iterator(StringBuffer sb, boolean firstFlag, Iterator<Map.Entry<String, Object>> iterator) {
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            if (firstFlag) {
                sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                firstFlag = false;
            } else {
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && !params.keySet().isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        return getString(responseBody, request);
    }

    private String getString(String responseBody, Request request) {
        try (Response response = okHttpClientHttps.newCall(request).execute()) {
            int status = response.code();
            if (response.isSuccessful()) {
                assert response.body() != null;
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post error: {1}", e);
        }
        return responseBody;
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public String getForHeader(String url, Map<String, Object> queries) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && !queries.isEmpty()) {
            boolean firstFlag = true;
            Iterator<Map.Entry<String, Object>> iterator = queries.entrySet().iterator();
            iterator(sb, firstFlag, iterator);
        }
        Request request = new Request.Builder().addHeader("key", "value").url(sb.toString()).build();
        try (Response response = okHttpClientHttps.newCall(request).execute()) {
            int status = response.code();
            if (response.isSuccessful()) {
                assert response.body() != null;
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 get error: {1}", e);
        }
        return responseBody;
    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public String postJsonParams(String url, String jsonParams) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return getString(responseBody, request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public String postXmlParams(String url, String xml) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        return getString(responseBody, request);
    }
}
