package com.yutou.okhttp;


import com.alibaba.fastjson2.JSONObject;

import okhttp3.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PostRequestParams implements IRequestParam {
    @Override
    public Request getRequest(HashMap<String, String> map, Request request) {
        if (request.body() instanceof FormBody) {
            FormBody.Builder bodyBuilder = new FormBody.Builder();
            FormBody formBody = (FormBody) request.body();

            for (int i = 0; i < formBody.size(); i++) {
                bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
            }
            for (String key : map.keySet()) {
                bodyBuilder.addEncoded(key, String.valueOf(map.get(key)));
            }
            formBody = bodyBuilder.build();
            request = request.newBuilder().post(formBody).build();
        } else if (request.body() != null) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),toUrlParams(map));
            request = request.newBuilder().post(request.body())
                    .post(requestBody).build();
        }
        return request;
    }

    public static String toUrlParams(JSONObject json) {
        StringBuilder string = new StringBuilder();
        Set<String> keys = json.keySet();
        for (String key : keys) {
            try {
                string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    string.append("&").append(URLEncoder.encode(key,"UTF-8")).append("=");
                    //    string += "&" + key + "=";
                } catch (Exception e1) {
                    string.append("&").append(key).append("=");
                }
            }
        }

        string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
        return string.toString();
    }

    public static String toUrlParams(Map<String, String> map) {
        if(map.isEmpty()){
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (String key : map.keySet()) {
            builder.append(key).append("=").append(map.get(key)).append("&");
        }
        return builder.substring(0, builder.length() - 1);
    }
}