package com.gingersoft.gsa.cloud.common.utils.okhttpUtils;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.config.OkHttpConfig;
import com.gingersoft.gsa.cloud.common.config.globalconfig.applyOptions.intercept.HeadersInterceptor;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.jess.arms.http.log.RequestInterceptor;
import com.jess.arms.utils.DeviceUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2019/1/10
 * 修订历史：2019/1/10
 * 描述：
 */
public class OkHttp3Utils {

    private static volatile OkHttpClient mOkHttpClient;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static void getOkHttpClient() {
        if (mOkHttpClient == null) {
            synchronized (OkHttp3Utils.class) {
                if (mOkHttpClient == null) {
                    mOkHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(OkHttpConfig.REQUEST_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(OkHttpConfig.REQUEST_TIMEOUT, TimeUnit.SECONDS)
                            .addInterceptor(new HeadersInterceptor())
                            .addInterceptor(new RequestInterceptor())
                            .build();

                }
            }
        }
    }

    public static Observable<String> get(String reqUrl) {
        getOkHttpClient();
        return Observable.create(emitter -> {
            //构建请求体
            Request.Builder RequestBuilder = new Request.Builder();
            RequestBuilder.url(reqUrl);// 添加URL地址
            Request request = RequestBuilder.build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    emitter.onError(e);
                    emitter.onComplete();
                    call.cancel();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    emitter.onNext(str);
                    emitter.onComplete();
                    call.cancel();
                }
            });
        });
    }

    public static Observable<String> post(String reqUrl, RequestBody requestBody) {
        getOkHttpClient();
        return Observable.create(emitter -> {
            //构建请求体
            Request.Builder RequestBuilder = new Request.Builder();
            RequestBuilder.url(reqUrl);// 添加URL地址
            RequestBuilder.post(requestBody);
            Request request = RequestBuilder.build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
                    emitter.onError(e);
                    emitter.onComplete();
                    call.cancel();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    emitter.onNext(str);
                    emitter.onComplete();
                    call.cancel();
                }
            });
        });
    }

    /**
     * 上传文件
     *
     * @param reqUrl   URL地址
     * @param file_key 上传文件的关键字
     * @param files    文件
     * @param params   用戶ID,日誌類型
     */
    public static Observable<String> sendFileMultipart(String reqUrl, String file_key, List<File> files, HashMap<String, String> params) {
        getOkHttpClient();
        return Observable.create(emitter -> {
            MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
            multipartBodyBuilder.setType(MultipartBody.FORM);
            //遍历map中所有参数到builder
            if (params != null) {
                for (String key : params.keySet()) {
                    multipartBodyBuilder.addFormDataPart(key, params.get(key));
                }
            }
            //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
            if (files != null) {
                for (int i = 0; i < files.size(); i++) {
                    multipartBodyBuilder.addFormDataPart(file_key, files.get(i).getName(), RequestBody.create(MEDIA_TYPE_PNG, files.get(i)));
                }
            }
            //构建请求体
            RequestBody requestBody = multipartBodyBuilder.build();

            Request.Builder RequestBuilder = new Request.Builder();
            RequestBuilder.url(reqUrl);// 添加URL地址
            RequestBuilder.post(requestBody);
            Request request = RequestBuilder.build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
//                    emitter.onError(e);
                    emitter.onComplete();
                    call.cancel();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    emitter.onNext(str);
                    emitter.onComplete();
                    call.cancel();
                }
            });
        });
    }

    /**
     * 上传多张图片及参数
     *
     * @param reqUrl  URL地址
     * @param params  参数
     * @param pic_key 上传图片的关键字
     * @param files   图片文件
     */
    public static Observable<String> sendImageMultipart(String reqUrl, HashMap<String, String> params, String pic_key, List<File> files) {
        getOkHttpClient();
        return Observable.create(emitter -> {
            MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
            multipartBodyBuilder.setType(MultipartBody.FORM);
            //遍历map中所有参数到builder
            if (params != null) {
                for (String key : params.keySet()) {
                    multipartBodyBuilder.addFormDataPart(key, params.get(key));
                }
            }

            //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
            if (files != null) {
                for (int i = 0; i < files.size(); i++) {
                    multipartBodyBuilder.addFormDataPart(pic_key + i, files.get(i).getName(), RequestBody.create(MEDIA_TYPE_PNG, files.get(i)));
                }
            }
            //构建请求体
            RequestBody requestBody = multipartBodyBuilder.build();

            Request.Builder RequestBuilder = new Request.Builder();
            RequestBuilder.url(reqUrl);// 添加URL地址
            RequestBuilder.post(requestBody);
            Request request = RequestBuilder.build();

            mOkHttpClient.newCall(request).enqueue(new Callback() {

                @Override
                public void onFailure(Call call, IOException e) {
//                    emitter.onError(e);
                    e.printStackTrace();
                    emitter.onComplete();
                    call.cancel();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    emitter.onNext(str);
                    emitter.onComplete();
                    call.cancel();
                }
            });
        });
    }



    /**
     * 心跳接口報錯，推送給相關人員
     * 版本,時間,RP_HD001,Gingersoft,GS1,26ErrorMsg:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     */
    public static void noticePersonnel(String errCode, String pushContent) {
        String restaurantInfo = DeviceUtils.getVersionName(GsaCloudApplication.getAppContext()) + "|" + DeviceUtils.getVersionCode(GsaCloudApplication.getAppContext()) +
                "--" + TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT) +
                "--CODE：" + errCode +
                "--餐廳:" + RestaurantInfoManager.newInstance().getBrandName() +
                "--" + RestaurantInfoManager.newInstance().getRestaurantName() +
                "--ID：" + RestaurantInfoManager.newInstance().getRestaurantId() +
                "--用戶：" + UserContext.newInstance().getMemberName() + "|" + UserContext.newInstance().getMemberId() +
                "--原因：" + pushContent;
        RequestBody requestBody = new FormBody.Builder()
                .add("code", errCode)//錯誤碼
                .add("shopId", RestaurantInfoManager.newInstance().getGsPosShopId())
                .add("source", GsaCloudApplication.getAppName() + "")//錯誤來源
                .add("pushContent", restaurantInfo)//推送內容
                .add("version", DeviceUtils.getVersionName(GsaCloudApplication.getAppContext()))//系統版本
                .build();
        OkHttp3Utils.post(HttpsConstans.ROOT_URL + "/member-web/api/monitor/pushAlarm", requestBody)
                .subscribeOn(Schedulers.io()).subscribe();
    }

}
