package com.friday.tooldriver.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.Map;
import java.util.Objects;

/**
 * @Author YaoYao
 * @Date Created In 11:55 2022/12/20
 * @Description OKHttp客户端
 * @Modified By
 */

@Slf4j
@Service
public class OkHttpService {

    @Autowired
    private OkHttpClient okHttpClient;

    private static final MediaType BODY_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType FORM_DATA = MediaType.parse("multipart/form-data");

    public TaieHttpResponse doRequest(HttpMethod method, String url, Map<String, Object> headers, String requestBody) {
        TaieHttpResponse response;
        switch (method){
            case GET:
                response = syncGet(url, headers);
                break;
            case POST:
                response = syncPost(url, headers, requestBody);
                break;
            case PUT:
                response = syncPut(url, headers, requestBody);
                break;
            case DELETE:
                response = syncDelete(url, headers, requestBody);
                break;
            case PATCH:
                response = syncPatch(url, headers, requestBody);
                break;
            default:
                return TaieHttpResponse.builder()
                        .success(false)
                        .message("不支持的请求类型")
                        .build();
        }
        return response;
    }

    public TaieHttpResponse doFormRequest(HttpMethod method, String url, Map<String, Object> headers, File file, String fileKey) {
        return syncPostFile(url, headers, file, fileKey);
    }

    private TaieHttpResponse syncGet(String url, Map<String, Object> headerMap) {
        Request request = buildGetRequest(url, headerMap);
        return curl(request);
    }

    public TaieHttpResponse syncDownload(String url, Map<String, Object> headerMap, String destFileDir, String destFileName) {
        Request request = buildGetRequest(url, headerMap);
        return curlDownload(request, destFileDir, destFileName);
    }

    private Request buildGetRequest(String url, Map<String, Object> headerMap) {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (String headerKey : headerMap.keySet()) {
                builder.addHeader(headerKey, (String) headerMap.get(headerKey));
            }
        }
        request = builder.build();
        return request;
    }


    private TaieHttpResponse syncPost(String url, Map<String, Object> headerMap, String requestBody) {
        return curlSyncPost(url, headerMap, RequestBody.create(BODY_JSON, requestBody));
    }

    private TaieHttpResponse syncPostFile(String url, Map<String, Object> headerMap, File file, String fileKey) {
        RequestBody fileBody = RequestBody.create(FORM_DATA, file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(fileKey, file.getName(), fileBody)
                .build();
        return curlSyncPost(url, headerMap, requestBody);
    }

    private TaieHttpResponse curlSyncPost(String url, Map<String, Object> headerMap, RequestBody requestBody) {
        Request request;
        final Request.Builder builder = new Request.Builder()
                .url(url)
                .post(requestBody);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (String headerKey : headerMap.keySet()) {
                builder.addHeader(headerKey, (String) headerMap.get(headerKey));
            }
        }
        request = builder.build();
        return curl(request);
    }

    private TaieHttpResponse syncPut(String url, Map<String, Object> headerMap, String requestBody) {
        RequestBody body = RequestBody.create(BODY_JSON, requestBody);
        Request request;
        final Request.Builder builder = new Request.Builder()
                .url(url)
                .put(body);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (String headerKey : headerMap.keySet()) {
                builder.addHeader(headerKey, (String) headerMap.get(headerKey));
            }
        }
        request = builder.build();
        return curl(request);
    }

    private TaieHttpResponse syncDelete(String url, Map<String, Object> headerMap, String requestBody) {
        RequestBody body = RequestBody.create(BODY_JSON, requestBody);
        Request request;
        final Request.Builder builder = new Request.Builder()
                .url(url)
                .delete(body);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (String headerKey : headerMap.keySet()) {
                builder.addHeader(headerKey, (String) headerMap.get(headerKey));
            }
        }
        request = builder.build();
        return curl(request);
    }

    private TaieHttpResponse syncPatch(String url, Map<String, Object> headerMap, String requestBody) {
        RequestBody body = RequestBody.create(BODY_JSON, requestBody);
        Request request;
        final Request.Builder builder = new Request.Builder()
                .url(url)
                .patch(body);
        if (!CollectionUtils.isEmpty(headerMap)) {
            for (String headerKey : headerMap.keySet()) {
                builder.addHeader(headerKey, (String) headerMap.get(headerKey));
            }
        }
        request = builder.build();
        return curl(request);
    }

    private TaieHttpResponse curl(Request request){
        TaieHttpResponse taieHttpResponse = TaieHttpResponse.builder().success(false).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            if(Objects.nonNull(response)){
                taieHttpResponse.setHttpRetCode(response.code());
                taieHttpResponse.setMessage(response.message());
                taieHttpResponse.setSuccess(response.isSuccessful());
                if(response.isSuccessful() && Objects.nonNull(response.body())){
                    taieHttpResponse.setResult(response.body().string());
                } else if(Objects.nonNull(response.body())){
                    InputStream inputStream = response.body().source().inputStream();
                    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while((len = inputStream.read(buffer)) != -1){
                        bytesOut.write(buffer, 0, len);
                    }
                    taieHttpResponse.setResult(bytesOut.toString());
                    bytesOut.close();
                    inputStream.close();
                }
            } else {
                taieHttpResponse.setMessage("http请求返回体为空");
            }
        } catch (Exception e) {
            log.error("http请求异常", e);
            taieHttpResponse.setMessage(e.getMessage());
        }
        return taieHttpResponse;
    }

    public TaieHttpResponse curlDownload(Request request, final String destFileDir, final String destFileName) {
        TaieHttpResponse taieHttpResponse = TaieHttpResponse.builder().success(false).build();
        // 异步请求
        Response response;
        InputStream is = null;
        byte[] buf = new byte[4096];
        int len = 0;
        FileOutputStream fos = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                is = response.body().byteStream();
                fos = new FileOutputStream(file);
                int size;
                long total = response.body().contentLength();
                while ((size = is.read(buf)) != -1) {
                    len += size;
                    fos.write(buf, 0, size);
                    int process = (int) Math.floor(((double) len / total) * 100);
                    log.info("下载进度" + process);
                }
                fos.flush();
                taieHttpResponse.setSuccess(true);
            } else {
                taieHttpResponse.setMessage(response.message());
            }
        } catch (IOException e) {
            log.error("OKHttp下载文件异常", e);
            taieHttpResponse.setMessage(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return taieHttpResponse;
    }
}
