package com.cslg.ppa.common.utils;

import com.cslg.ppa.common.okhttp.MyOkHttpClient;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zsq
 * @version 1.0
 * @date 2021/3/31 11:06
 */
public class HttpUtils {


    /**okhttp 实例**/
    private static OkHttpClient client = MyOkHttpClient.client;

    /**解析键值对正则**/
    public static final Pattern PAT_KEY_VALUE = Pattern.compile("[\\w]*=[\\w,/]*");


    public static String doGet(String url, Map<String, String> params,String cookie) {
        Request.Builder reqBuild = new Request.Builder()
                .addHeader("Cookie", cookie);
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * get请求
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, String> params) {
        Request.Builder reqBuild = new Request.Builder()
                .addHeader("Cookie", "_ga=GA1.1.1951344733.1721120989; _ga_TPFW0KPXC1=GS1.1.1721122799.2.0.1721122799.0.0.0; ua_id=lYVPBmbUB2Br9v5GAAAAANySKCt88vpelcEXZ-NfgB4=; wxuin=54469110938579; mm_lang=zh_CN; cert=DwPjsGtL0kB9wndBHqxn27g_A5ieSRxR; uuid=319a730f894e4db1d1ef0bc81f39a062; rand_info=CAESIDLoBwjXI/3LC0I9nd7JfKtXh56j+87f7ZscLgnKB6Pt; slave_bizuin=3932387393; data_bizuin=3932387393; bizuin=3932387393; data_ticket=YYzYTHhGCnGFvgiXfO2BSeDzN/jWRTMdSZ//2DKDOuD1zNhewApnIwX5ruHTNtvs; slave_sid=MldNcXc0QnRfYVdkWWVKbHZBdEx1WUlHbkh1UWN0N3lTOVpmZUhoMEhjR3lJaUVGVkR1U0ZBa2dVSmVGRG0xeFV6R0tHU1d0NU1MOWQ3djc1MjRpeVM1S2xNRE1yQktIeTNmdmptSkF5aEQyQV9ZYnYyc2tRSkh4MHZIcnkxSjlPSXByZUphS1VTWDdGOUY4; slave_user=gh_292dda35ab06; xid=f4e6941e8d1019c71e230139c5bae238; _clck=3932387393|1|fy9|0; _clsk=1ly0zby|1754532579853|5|1|mp.weixin.qq.com/weheat-agent/payload/record");
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * post表单提交
     * @return
     */
    public static String doPost(String url, Map<String, String> params) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null) {
            params.forEach(formBuilder::addEncoded);
        }

        Request request = new Request.Builder()
                .url(url)
                .post(formBuilder.build())
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * get请求，返回流
     * @param url
     * @param params
     * @return
     */
    public static InputStream doGetStream(String url, Map<String, String> params) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }

            if (response.body() == null) {
                throw new RuntimeException("返回内容body为空");
            }

            return response.body().byteStream();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 字符解析成键值对参数
     * @return
     */
    public static Map<String, String> parseQueryParams (String path) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(path)) {
            Matcher matcher = PAT_KEY_VALUE.matcher(path);
            while (matcher.find()) {
                String group = matcher.group(0);
                String[] split = group.split("=");
                if (split.length > 1) {
                    map.put(split[0], split[1]);
                } else {
                    map.put(split[0], "");
                }
            }
        }

        return map;
    }

}
