package com.gree.mall.miniapp.utils;

import org.apache.commons.lang3.StringUtils;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class HttpUtils {

    private static HttpUtils httpUtils;
    private OkHttpClient okHttpClient;

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private HttpUtils() {
        okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder().
                connectTimeout(60, TimeUnit.SECONDS).
                readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS);

    }

    //创建 单例模式（OkHttp官方建议如此操作）
    public static HttpUtils getInstance() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    static private Request.Builder getGetBuilder(String url, Map<String, String> params, Map<String, String> heads) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();

        if (params != null) {
            for (String key : params.keySet()) {
                urlBuilder.addQueryParameter(key, params.get(key));
            }
        }


        reqBuild.url(urlBuilder.build());
        if (heads != null) {
            for (String key : heads.keySet()) {
                reqBuild.addHeader(key, heads.get(key));
            }
        }

        return reqBuild;
    }






    static public String requestGet(String url, Map<String, String> params, Map<String, String> heads) throws RemoteServiceException {
        Request.Builder reqBuild = getGetBuilder(url, params, heads);
        Request req = reqBuild.build();

        try {
            Response response = OkHttpUtil.execute(req);
            //判断请求是否成功
            if (response.isSuccessful()) {
                String content = response.body().string();
                logger.info("GET Response" + content);
                return content;
                //打印服务端返回结果
            } else {
                String content = response.body().string();
                logger.info("ERROR Response" + content);
                throw new RemoteServiceException(response.code(), response.message());
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
            throw new RemoteServiceException(505, e.getMessage());
        }
    }

    static public String requestGetYB(String url, Map<String, String> params, Map<String, String> heads, Callback callback) {
        Request.Builder reqBuild = getGetBuilder(url, params, heads);
        Request req = reqBuild.build();

        try {
            OkHttpUtil.enqueue(req, callback);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
        }
        return "ok";
    }


    static private Request.Builder getBodyBuilder(String url, String json, Map<String, String> heads) {
        logger.info("requestPostBody url:" + url);
        logger.info("body:" + json);
        MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSONType, json);
        Request.Builder builder = new Request.Builder();

        builder.url(url);

        if (heads != null) {
            for (String key : heads.keySet()) {
                if(heads.get(key) != null && !heads.get(key).equals("null")) {
                    builder.addHeader(key, heads.get(key));
                }
            }
        }
        builder.post(body);
        return builder;
    }

    static private Request.Builder getFormBuilder(String url, Map<String, Object> params, Map<String, String> heads) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();

        logger.info("form url:" + url);
        logger.info("params:" + params.toString());

        try {
            if (params != null) {
                for (String key : params.keySet()) {
                    if (params.get(key) != null) {
                        bodyBuilder.add(key, params.get(key).toString());
                    } else {
                        bodyBuilder.add(key, "");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println(e);
        }

        RequestBody body = bodyBuilder.build();
        Request.Builder builder = new Request.Builder();

        if (heads != null) {
            for (String key : heads.keySet()) {

                builder.addHeader(key, heads.get(key));
            }
        }
        builder.url(url);
        builder.post(body);

        return builder;

    }


    static public String requestPostBody(String url, String json, Map<String, String> heads) throws RemoteServiceException {


        Request.Builder builder = getBodyBuilder(url,json,heads);
        Request req = builder.build();

        try {
            Response response = OkHttpUtil.execute(req);
            logger.error(response.toString());
            if (response.isSuccessful()) {


                String returnString = response.body().string();

                logger.info("success " + returnString);

                return returnString;
                //打印服务端返回结果

            } else {

                logger.error("failure: " + response.body().string());

                throw new RemoteServiceException(response.code(), response.message());
            }
            //throw   new ApiException(response.code(),response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(HttpUtils.class.getName(), e);
            throw new RemoteServiceException(505, e.getMessage());
        }

    }

    static public String requestPostBodyYB(String url, String json, Map<String, String> heads, Callback cb) {
        Request.Builder builder = getBodyBuilder(url,json,heads);
        Request req = builder.build();
        try {
            OkHttpUtil.enqueue(req, cb);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    static public String requestPostForm(String url, Map<String, Object> params, Map<String, String> heads) throws RemoteServiceException {



        Request.Builder builder = getFormBuilder(url,params,heads);
        Request req = builder.build();

        try {
            Response response = OkHttpUtil.execute(req);
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new RemoteServiceException(response.code(), response.message());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RemoteServiceException(505, e.getMessage());
        }
    }


//    新创建积分商品二维码路径


}
