package com.philisense.rdgo.viewModel;

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

import com.google.gson.Gson;
import com.philisense.rdgo.bean.MyOutBoxBean;
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.OrderSubmitRequestBean;
import com.philisense.rdgo.bean.request.PileInfoRequestBean;
import com.philisense.rdgo.bean.request.pile;
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.PileBoxBean;
import com.philisense.rdgo.bean.response.PileInfoBean;
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.ui.putOut.PutOutOrderActivity;
import com.philisense.rdgo.util.Constant;
import com.philisense.rdgo.util.TreeNodeInsertSubscribe;
import com.philisense.rdgo.view.OrderBoxViewHolder;
import com.philisense.rdgo.view.OrderViewHolder;
import com.unnamed.b.atv.model.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.functions.Function;
import io.reactivex.schedulers.Schedulers;

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

public class PutOutOrderViewModel {

    private Context context;
    private TreeNode root;

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

    public boolean enableEdit;

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

        completeAvailable = Observable.combineLatest(new Observable[]{Observable.create(new TreeNodeInsertSubscribe((PutOutOrderActivity) context))}, new Function<Object, Boolean>() {
            @Override
            public Boolean apply(Object o) throws Exception {
                for (TreeNode node : root.getChildren()) {
                    OrderViewHolder.OrderInfo data = (OrderViewHolder.OrderInfo) node.getValue();
                    if (data.getBoxNum() > 0) {
                        return false;
                    }
                }
                return true;
            }
        });
    }

    public Boolean getnum() {

        for (TreeNode node : root.getChildren()) {
            OrderViewHolder.OrderInfo data = (OrderViewHolder.OrderInfo) node.getValue();
            if (data.getBoxNum() > 0) {
                return false;
            }
        }
        return true;


    }

    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.setAccount(userDb.getAccount() == null ? "" : userDb.getAccount());
        requestBean.setBoxId(boxId);

        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() {

                    }
                });
    }

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

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

                    }

                    @Override
                    public void onNext(PileInfoBean value) {
                        if (value.getSuccess() == 0) {
                            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 getpileBox(String pileID, RequestImpl<PileBoxBean> listener) {


        pile p = new pile();
        p.setPileId(pileID);
        HttpClient.Builder.getBaseService()
                .getPileBox(p)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PileBoxBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(PileBoxBean value) {
                        if (value.getSuccess() == 0) {
                            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() {

                    }
                });
    }

    public void submitOrder(Map<String, TreeNode> nodeMap, String orderId, Map<String, MyOutBoxBean> myList, int n, RequestImpl<BaseBean> listener) {

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

                ACache aCache = ACache.get(context);

                UserDb userDb = DBFactory.getUserInfo(context);

                OrderSubmitRequestBean submitRequestBean = new OrderSubmitRequestBean();

                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));

                // 人员信息
                OrderSubmitRequestBean.LastUpdatedByBean userBean = new OrderSubmitRequestBean.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<String> pils = new ArrayList<>();
                List<String> boxes = new ArrayList<>();

//
                if (n == 1) {
                    for (TreeNode node : nodeMap.values()) {
                        // 1、提取root分支，获取数据
                        OrderViewHolder viewHolder = (OrderViewHolder) node.getViewHolder();
                        OrderViewHolder.OrderInfo data = viewHolder.getData();
                        if (data.getBoxNum() != 0) {
                            // 如果还没有装满，则返回 false
                            listener.loadFailed(new OError(1, " 配送单没装满"));
                            return;
                        }

                    }
                } else {
                    for (TreeNode node : nodeMap.values()) {
                        // 1、提取root分支，获取数据
                        OrderViewHolder viewHolder = (OrderViewHolder) node.getViewHolder();
                        OrderViewHolder.OrderInfo data = viewHolder.getData();
                        if (data.getBoxNum() > 0) {
                            // 如果还没有装满，则返回 false
                            listener.loadFailed(new OError(1, " 配送单没装满"));
                            return;
                        }

                    }
                }

                if (myList != null) {

                    for (Map.Entry entry : myList.entrySet()) {

                        MyOutBoxBean bean = (MyOutBoxBean) entry.getValue();
                        if (bean.getBoxId().length() > 2 && "xn".equals(bean.getBoxId().substring(0, 2))) {
                            continue;
                        }
                        String pileId = bean.getPileId();
                        String boxId = bean.getBoxId();
                        boolean b = bean.getPileAdd();

                        if (!pils.contains(pileId) && b) {
                            pils.add(pileId);
                        }

                        if (!boxes.contains(boxId) && !b) {
                            boxes.add(boxId);
                        }


                    }

                }

                submitRequestBean.setPileList(pils);
                submitRequestBean.setBoxList(boxes);
//                System.out.println("pppppp"+pils.size()+","+boxes.size());
                e.onNext(submitRequestBean);
                e.onComplete();
            }
        });

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

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

                        HttpClient.Builder.getBaseService()
                                .sendOutBound(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(value);
                                        } else if (value.getSuccess() == 7) {
                                            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() {

                                    }
                                });


                    }
                });

    }


}
