package com.philisense.rdgo.viewModel;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.request.BoxInfoRequestBean;
import com.philisense.rdgo.bean.request.OrderDetailRequestBean;
import com.philisense.rdgo.bean.request.OrderReplaceSubmitRequestBean;
import com.philisense.rdgo.bean.request.OrderSubmitRequestBean;
import com.philisense.rdgo.bean.response.BaseBean;
import com.philisense.rdgo.bean.response.BoxInfoBean;
import com.philisense.rdgo.bean.response.OrderDetailBean;
import com.philisense.rdgo.bean.response.WarehouseBean;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.UserDb;
import com.philisense.rdgo.http.HttpClient;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.http.cache.ACache;
import com.philisense.rdgo.util.Constant;
import com.unnamed.b.atv.model.TreeNode;

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

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by shaop on 2017/12/18.
 */

public class OutReplaceOrderViewModel {

    private Context context;
    private TreeNode root;

    public Observable<Boolean> completeAvailable;
    public OrderDetailBean orderDetailBean;
    public List<OrderSubmitRequestBean> requestBeanList;

    public boolean enableEdit;

    public OutReplaceOrderViewModel(Context context) {
        this.context = context;
        requestBeanList = new ArrayList<>();
        orderDetailBean = new OrderDetailBean();


    }

    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public void getOrderDetail(String orderId, RequestImpl<OrderDetailBean> listener) {
        UserDb userDb = DBFactory.getUserInfo(context);
        OrderDetailRequestBean requestBean = new OrderDetailRequestBean();
        requestBean.setAccessToken(ACache.get(context).getAsString(Constant.ACCESSTOKEN));
        requestBean.setSendId(orderId);
        requestBean.setAccount(userDb.getAccount() == null ? "" : userDb.getAccount());


        HttpClient.Builder.getBaseService()
                .getOrderDetail(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderDetailBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(OrderDetailBean value) {
                        if (value.getSuccess() == 0) {
                            enableEdit = value.getData().getStatus() == 0;
                            orderDetailBean = value;
                            listener.loadSuccess(value);
                        }else {
                            listener.loadFailed(new OError(value.getSuccess(),value.getMessage()));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.loadFailed(new OError(Constant.SystemErrorCode, e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取箱信息
     * @param listener 返回接口
     */
    public void getBoxInfo(String boxId, RequestImpl<BoxInfoBean> listener) {
        UserDb userDb = DBFactory.getUserInfo(context);
        BoxInfoRequestBean requestBean = new BoxInfoRequestBean();
        requestBean.setAccessToken(ACache.get(context).getAsString(Constant.ACCESSTOKEN));
        requestBean.setBoxId(boxId);
        requestBean.setAccount(userDb.getAccount() == null ? "" : userDb.getAccount());

        HttpClient.Builder.getBaseService()
                .getBoxInfo(requestBean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BoxInfoBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BoxInfoBean value) {
                        if (value.getSuccess() == 0) {


                            listener.loadSuccess(value);



                        }else {
                            Log.e("tag",value.getMessage());
                            listener.loadFailed(new OError(value.getSuccess(),value.getMessage()));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("tag",e.getMessage());
                        listener.loadFailed(new OError(Constant.SystemErrorCode,e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



    public void getWarehouse(RequestImpl<List<WarehouseBean.ListBean>> listener) {
        ACache aCache = ACache.get(context);

        HttpClient.Builder.getBaseService()
                .getWarehouse(aCache.getAsString(Constant.ACCESSTOKEN))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WarehouseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(WarehouseBean value) {
                        listener.loadSuccess(value.getList());
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.loadFailed(new OError(Constant.SystemErrorCode, e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void submitOrder(List<BoxInfoBean.DataBean> myAdd, List<BoxInfoBean.DataBean> myDelte, String orderId, RequestImpl<String> listener) {


        Observable<OrderReplaceSubmitRequestBean> observer = Observable.create(new ObservableOnSubscribe<OrderReplaceSubmitRequestBean>() {
            @Override
            public void subscribe(ObservableEmitter<OrderReplaceSubmitRequestBean> e) throws Exception {

                ACache aCache = ACache.get(context);

                UserDb userDb = DBFactory.getUserInfo(context);

                OrderReplaceSubmitRequestBean submitRequestBean = new OrderReplaceSubmitRequestBean();

                submitRequestBean.setAccount(userDb.getAccount() == null ? "": userDb.getAccount());
                submitRequestBean.setSendId(orderId);
                submitRequestBean.setName(userDb.getName() == null ? "" : userDb.getName());
                submitRequestBean.setType(orderDetailBean.getData().getType()); // 获取出库类型
                submitRequestBean.setWarehouse(userDb.getWarehouse());
//                submitRequestBean.setWarehouseCode(userDb.getWarehouseCode());
                submitRequestBean.setAccessToken(aCache.getAsString(Constant.ACCESSTOKEN));

                // 人员信息
                OrderReplaceSubmitRequestBean.LastUpdatedByBean userBean = new OrderReplaceSubmitRequestBean.LastUpdatedByBean();
                userBean.setAccount(userDb.getAccount());
                userBean.setFactory(userDb.getFactory());
                userBean.setIDCard(userDb.getIDCard());
                userBean.setLine(userDb.getLine());
                userBean.setPerson(userDb.getName());
                userBean.setSex(userDb.getSex());
                userBean.setWarehouse(userDb.getWarehouse());

                submitRequestBean.setLastUpdatedBy(userBean);

                List<OrderReplaceSubmitRequestBean.AddList> adds = new ArrayList<>();
                List<OrderReplaceSubmitRequestBean.DelList> dels = new ArrayList<>();
                int a=myAdd.size();
                for(int i=0;i<a;i++){
                    OrderReplaceSubmitRequestBean.AddList bean=new OrderReplaceSubmitRequestBean.AddList();
                    bean.setBoxId(myAdd.get(i).getBoxId());
                    bean.setPileId(myAdd.get(i).getPileId());
                    adds.add(bean);
                }



                int b=myDelte.size();
                for(int i=0;i<b;i++){
                    OrderReplaceSubmitRequestBean.DelList bean=new OrderReplaceSubmitRequestBean.DelList();
                    bean.setBoxId(myDelte.get(i).getBoxId());
                    bean.setPileId(myDelte.get(i).getPileId());
                    dels.add(bean);
                }



                submitRequestBean.setAddList(adds);
                submitRequestBean.setDelList(dels);


                e.onNext(submitRequestBean);
                e.onComplete();
            }
        });

        observer.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<OrderReplaceSubmitRequestBean>() {
                    @Override
                    public void accept(OrderReplaceSubmitRequestBean orderSubmitRequestBean) throws Exception {

                        Gson g = new Gson();
                        Log.e("tag",g.toJson(orderSubmitRequestBean));
                        System.out.println(g.toJson(orderSubmitRequestBean));

                        HttpClient.Builder.getBaseService()
                                .OutReplaceBound(orderSubmitRequestBean)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<BaseBean>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(BaseBean value) {
                                        if (value.getSuccess() == 0) {
                                            listener.loadSuccess("成功");
                                        }else {
                                            listener.loadFailed(new OError(value.getSuccess(), value.getMessage()));
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        listener.loadFailed(new OError(Constant.SystemErrorCode, e.getMessage()));
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });


                    }
                });

    }


}
