package com.zkjc.common.utils;

import android.text.TextUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;

import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class DataToNetUtil {
    @NotNull
    public static Request getJmRequest(Request request, Charset charset) {
        HttpUrl url = request.url();
        //http://192.168.3.138:8089/interface/login   //@get @delete 时候需要拼接在请求地址后面  ?userName=xiaoming&userPassword=12345
        String scheme = url.scheme();//  http  https
        String host = url.host();//   192.168.3.138
        int port = url.port();//   8089
        String path = url.encodedPath();//  /interface/login
        String method = request.method().toLowerCase().trim();//请求方式例如：get delete put post
        String originalPath = scheme + "://" + host + ":" + port + path;
        //如果请求方式是Get或者Delete，此时请求数据是拼接在请求地址后面的
        // @get @delete 时候需要拼接在请求地址后面  ?userName=xiaoming&userPassword=12345
        if (method.equals("get") || method.equals("delete")) {
            String query = url.encodedQuery();// query 是获取到的拼接字符串 类似 userName=xiaoming&userPassword=12345
            /*如果有请求数据 则加密*/
            if (query != null) {
                String encryptQuery = null;
                try {
                    encryptQuery = AesEncryptUtil.encryptWth(query);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //拼接加密后的url，参数字段自己跟后台商量，这里我用param，后台拿到数据先对param进行解密，解密后的数据就是请求的数据
                String newUrl = originalPath + "?" + encryptQuery;
                //构建新的请求
                request = request.newBuilder().url(newUrl).build();
            }
        } else {
            //不是Get和Delete请求时，则请求数据在请求体中
            RequestBody requestBody = request.body();
            //判断类型
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);

            }


            // 获取请求的数据
            Buffer buffer = new Buffer();
            try {
                requestBody.writeTo(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String requestData = null;
            try {
                requestData = URLDecoder.decode(buffer.readString(charset).trim(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //这里调用加密的方法，自行修改
//            String encryptData = AESUtils.encrypt("xxxxxxxxxxxxxxxx", requestData);
            String encryptData = AesEncryptUtil.encryptWth(requestData);
            //构建新的请求体
           /* Map<String,String> map=new HashMap<>();
            map.put("requestData",encryptData);*/

            RequestBody newRequestBody = RequestBody.create(contentType, encryptData);
            //构建新的requestBuilder
            Request.Builder newRequestBuilder = request.newBuilder();
            //根据请求方式构建相应的请求
            switch (method) {
                case "post":
                    newRequestBuilder.post(newRequestBody);
                    break;
                case "put":
                    newRequestBuilder.put(newRequestBody);
                    break;
                default:
                    break;
            }
            request = newRequestBuilder.build();

        }
        return request;
    }

    @NotNull
    public static Response getProcessResponse(Response response, ResponseBody responseBody) throws IOException {
        //获取bodyString
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }

        String bodyString = buffer.clone().readString(charset);
        if (!TextUtils.isEmpty(bodyString)){
            //我这里是base64解码  具体情况自己定义
            //base64解码
            String responseData = null;
            try {
//                 responseData = AesEncryptUtil.decryptFormBase64ToString(bodyString, "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm");
                 responseData = AesEncryptUtil.decryptNew(bodyString);
               // responseData = AesEncryptUtil.decrypt(bodyString, "O2BEeIv399qHQNhD6aGW8R8DEj4bqHXm");
            } catch (Exception e) {
                e.printStackTrace();
            }

            //生成新的ResponseBody
            ResponseBody newResponseBody = ResponseBody.create(contentType, responseData);
            //response
            response = response.newBuilder().body(newResponseBody).build();
            System.out.println("解密后数据: " + responseData);

           /* if (message.contains("token失效")){
                Activity currentActivity = AppManager.getAppManager().getCurrentActivity();
                intent.setClass(currentActivity, LoginActivity.class);

            currentActivity.startActivity(intent);
            currentActivity.finish();
            }*/
        }

        return response;
    }

}
