package com.xwkj.jcjcgz.mvp.model.api;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.hjq.toast.ToastUtils;
import com.jess.arms.utils.ArmsUtils;
import com.xwkj.jcjcgz.mvp.model.api.service.ApiService;
import com.xwkj.jcjcgz.mvp.model.entity.AddressEntity;
import com.xwkj.jcjcgz.mvp.model.entity.BaseNetEntity;
import com.xwkj.jcjcgz.mvp.model.entity.BusEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ReqToBus {
    private Context context;
    /*  private String reqKey;
      private String reqValue;
      private String dataObjId;*/
    private SharedPreferences sp;
    private static ReqToBus reqToBus;
    private CommonInterFace interFace;

    //初始化
    public static synchronized ReqToBus getInstance() {
        if (reqToBus == null) {
            synchronized (ReqToBus.class) {
                if (reqToBus == null) {
                    reqToBus = new ReqToBus();
                }
            }
        }
        return reqToBus;
    }

    public ReqToBus init(Context context) {
        this.context = context;
        sp = context.getSharedPreferences("sys", Context.MODE_PRIVATE);
        return this;
    }

    public void getRequestV2(Object reqValue, CommonInterFace interFace) {
        // String url = "http://192.168.0.63:8090/jlyqfk/request/getData";
        // String dataObjId="220000000000-3-0100-74b66b22b1524937ac713c10489a55fc";
        String dataObjId = "220000000000-3-0100-5262bf9ccd72456e802fe9a0b77097e5";
        //正式环境

        String resourceList = sp.getString("resourceList", "[{\n" +
                "\"resourceRegionalismCode\":\"120000000000\",\n" +
                "\"resourceAddress\":\"http://192.168.0.10/zf/transpond/request\",\n" +
                "\"resourceId\":\"220000000000-3-0100-5262bf9ccd72456e802fe9a0b77097e5\",\"resourceServiceType\":\"10\"\n" +
                "}\n" +
                "]");
        List<AddressEntity> list = JSONObject.parseArray(resourceList, AddressEntity.class);
        String url = "";
        String resourceRegionalismCode = "";
        for (int i = 0; i < list.size(); i++) {
            AddressEntity addressEntity = list.get(i);
            if (addressEntity.getResourceId().trim().equals(dataObjId.trim())) {
                url = addressEntity.getResourceAddress();
                resourceRegionalismCode = addressEntity.getResourceRegionalismCode();

            }
        }
        String str = new Gson().toJson(reqValue);
        String requstJson = getRequstJson1(url, str, dataObjId, resourceRegionalismCode);
        System.out.println("dssd" + requstJson);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                requstJson
        );
        ArmsUtils.obtainAppComponentFromContext(context).repositoryManager()
                .obtainRetrofitService(ApiService.class).getNetWork(url, requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    addDispose(disposable);//在订阅时必须调用这个方法,不然Activity退出时可能内存泄漏
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<JsonObject>(ArmsUtils.obtainAppComponentFromContext(context).rxErrorHandler()) {
                    @Override
                    public void onNext(JsonObject jsonObject) {
                        try {
                            String json = jsonObject.toString();
                            BusEntity busEntity = new Gson().fromJson(json, BusEntity.class);
                            String code = busEntity.getCode();
                            if (code.equals("200")) {
                                String value = busEntity.getData().getDataList().get(0).getFieldValues().get(0).getValue();

                                interFace.onSuccess(value);
                            } else {
                                ToastUtils.show(busEntity.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        interFace.onError(t);

                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        interFace.onFinsh();

                    }
                });

    }

    public void getRequest(String url, Object reqValue, String dataObjId, CommonInterFace interFace) {

        //正式环境

        String resourceList = sp.getString("resourceList", "");
        List<AddressEntity> list = JSONObject.parseArray(resourceList, AddressEntity.class);
        /*String url = "";*/
        String resourceRegionalismCode = "";
        for (int i = 0; i < list.size(); i++) {
            AddressEntity addressEntity = list.get(i);
            if (addressEntity.getResourceId().trim().equals(dataObjId.trim())) {
                url = addressEntity.getResourceAddress();
                resourceRegionalismCode = addressEntity.getResourceRegionalismCode();

            }
        }
        String str = new Gson().toJson(reqValue);
        String requstJson = getRequstJson1(url, str, dataObjId, resourceRegionalismCode);
        System.out.println("dssd" + requstJson);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                requstJson
        );
        ArmsUtils.obtainAppComponentFromContext(context).repositoryManager()
                .obtainRetrofitService(ApiService.class).getNetWork(url, requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    addDispose(disposable);//在订阅时必须调用这个方法,不然Activity退出时可能内存泄漏
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<JsonObject>(ArmsUtils.obtainAppComponentFromContext(context).rxErrorHandler()) {
                    @Override
                    public void onNext(JsonObject jsonObject) {
                        String json = jsonObject.toString();
                        BusEntity busEntity = new Gson().fromJson(json, BusEntity.class);
                        String code = busEntity.getCode();
                        if (code.equals("200")) {
                            String value = busEntity.getData().getDataList().get(0).getFieldValues().get(0).getValue();

                            interFace.onSuccess(value);
                        } else {
                            ToastUtils.show(busEntity.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        interFace.onError(t);

                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        interFace.onFinsh();

                    }
                });

    }

    private CompositeDisposable mCompositeDisposable;

    public void addDispose(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);//将所有 Disposable 放入集中处理
    }


    public void unDispose() {

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();//保证 Activity 结束时取消所有正在执行的订阅
        }
    }

    public static String getRequstJson1(String reqKey, String reqValue, String dataObjId, String resourceRegionalismCode) {

        BaseNetEntity entity = new BaseNetEntity();
        entity.setMessageId(UUID.randomUUID().toString());
        entity.setVersion("1.0");
        BaseNetEntity.ParameterBean parameter = new BaseNetEntity.ParameterBean();
        BaseNetEntity.ParameterBean.ConditionBean condition = new BaseNetEntity.ParameterBean.ConditionBean();
        condition.setLogicalOperate("and");
        List<BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
        BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean keyValueListBean = new BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean();
        keyValueListBean.setKey("params");
        keyValueListBean.setRelationOperator("=");
        keyValueListBean.setValue(reqValue);
        list.add(keyValueListBean);
        condition.setKeyValueList(list);
        parameter.setCondition(condition);
        parameter.setDataObjId(dataObjId);
        parameter.setFields("data");
        parameter.setNetworkCode("3");
        List<BaseNetEntity.ParameterBean.OrderByBean> data = new ArrayList<>();
        parameter.setOrderBy(data);
        BaseNetEntity.ParameterBean.PageBean page = new BaseNetEntity.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(1);
        parameter.setPage(page);
        parameter.setRegionalismCode(resourceRegionalismCode);
        entity.setParameter(parameter);
        String json = new GsonBuilder().disableHtmlEscaping().create().toJson(entity).toString();
        return json;
    }

    public static String getRequstJson(String reqKey, Object reqValue, String dataObjId, String resourceRegionalismCode) {

        BaseNetEntity entity = new BaseNetEntity();
        entity.setMessageId(UUID.randomUUID().toString());
        entity.setVersion("1.0");
        BaseNetEntity.ParameterBean parameter = new BaseNetEntity.ParameterBean();
        BaseNetEntity.ParameterBean.ConditionBean condition = new BaseNetEntity.ParameterBean.ConditionBean();
        condition.setLogicalOperate("and");
        List<BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
        BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean keyValueListBean = new BaseNetEntity.ParameterBean.ConditionBean.KeyValueListBean();
        keyValueListBean.setKey("params");
        keyValueListBean.setRelationOperator("=");
        keyValueListBean.setValue(reqValue);
        list.add(keyValueListBean);
        condition.setKeyValueList(list);
        parameter.setCondition(condition);
        parameter.setDataObjId(dataObjId);
        parameter.setFields("data");
        parameter.setNetworkCode("3");
        List<BaseNetEntity.ParameterBean.OrderByBean> data = new ArrayList<>();
        parameter.setOrderBy(data);
        BaseNetEntity.ParameterBean.PageBean page = new BaseNetEntity.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(1);
        parameter.setPage(page);
        parameter.setRegionalismCode(resourceRegionalismCode);
        entity.setParameter(parameter);
        String json = new GsonBuilder().disableHtmlEscaping().create().toJson(entity).toString();
        return json;
    }
}
