package com.gingersoft.gsa.cloud.table.mvp.presenter;

import android.app.Application;
import android.graphics.Color;
import android.view.View;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.aspectj.XClickUtil;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderContentContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BaseRespose;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.AddOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.CreateOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderPayActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderTopFunctionAdapter;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.RxLifecycleUtils;

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

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/09/2020 19:23
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class OrderContentPresenter extends BaseOrderPresenter<OrderContentContract.Model, OrderContentContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderContentActivity IActivity;

    private OrderTopFunctionAdapter mOrderTopFunctionAdapter;
    private List<Function> mFunctionList = new ArrayList<>();

    private Function[] functions = {
            new Function("送單", Color.parseColor("#FFFFFF"), Color.parseColor("#008131"), 24),
            new Function("印單", Color.parseColor("#FFFFFF"), Color.parseColor("#FF8E04"), 24),
            new Function("結賬", Color.parseColor("#FFFFFF"), Color.parseColor("#DC0000"), 24),
    };

    @Inject
    public OrderContentPresenter(OrderContentContract.Model model, OrderContentContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderContentActivity) rootView;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void initAdapter() {
        if (mOrderTopFunctionAdapter == null) {
            mOrderTopFunctionAdapter = new OrderTopFunctionAdapter(IActivity, mFunctionList);
            mRootView.setTopFunctionAdapter(mOrderTopFunctionAdapter);
        }
        mRootView.setFoodAdapter(mSelectMealAdapter);
    }

    public void initOrderTopFunctionListener() {
        mOrderTopFunctionAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
                if (XClickUtil.isFastDoubleClick(view, 1000)) {
                    return;
                }
                switch (position) {
                    case 0:
                        //送單
                        sendOrder(false);
                        break;
                    case 1:
                        //印單
                        if (getFoodCount() == 0) {
                            showTipDialog(IActivity, "沒有食品，不能印單");
                            return;
                        }
                        if (hasNesOrderFoods()) {
                            //有未送單食品先送單
                            sendOrder(true);
                        } else {
                            // 沒有未送單食品，將之前的食品列表清空
                            MyOrderManage.getInstance().getNewFoodList().clear();
                            printOrder(OpenTableManage.getDefault().getTableBean().getId(), false);
                        }
                        break;
                    case 2:
                        //結賬
                        mRootView.startActivityForResult(OrderContentActivity.BILL_CODE, OrderPayActivity.class, null);
                        break;
                }
            }
        });
        mOrderTopFunctionAdapter.setOnItemClickListener((datasBean, position) -> {

        });
    }

    public void initTopFunctionData() {
        mFunctionList.addAll(Arrays.asList(functions));
    }

    protected void createOrder(boolean isPrint) {
        CreateOrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        mModel.createOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            if (info.getData() != null) {
                                setOrderId((Double) info.getData());
                            }
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.sendSuccess();
                                mRootView.showMessage("送單成功");
                                printSendOrder(getOrderFoodLists());
                                mAppManager.killActivity(MealStandActivity.class);
                                mRootView.killMyself();
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.showMessage("送單失敗");
                            }
                        }
                    }
                });
    }

    protected void addOrderFood(boolean isPrint) {
        List<OrderDetail> foodLists = getOrderFoodLists();
        for (OrderDetail food : foodLists) {
            food.setOrderId(MyOrderManage.getInstance().getOrderId());
        }
        AddOrderRequest addOrderRequest = getAddOrderRequest(foodLists);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(addOrderRequest));
        String json = GsonUtils.GsonString(addOrderRequest);
        mModel.addFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.showMessage("送單成功");
                                printSendOrder(foodLists);
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                //TODO 未新增食品點擊送單 後台不讓過直接提示即可，不調用打印
                                if (!hasNesOrderFoods()) {
                                    //TODO 未新增食品點擊送單 後台不讓過直接提示即可
                                    mRootView.showMessage("送單成功");
//                                    mRootView.sendSuccess();
                                } else {
                                    mRootView.showMessage("送單失敗");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 送單
     */
    private void printSendOrder(List<OrderDetail> newFoods) {
        MyOrderManage.getInstance().setNewFoodList(newFoods);
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam("type", 3)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    mRootView.sendSuccess();
                });


        //打印上菜紙
//        CC.obtainBuilder("Component.Print")
//                .setActionName("printActivity")
//                .addParam("NewFoods", newFoods)
//                .addParam("type", 0)
//                .build()
//                .callAsyncCallbackOnMainThread((cc, result) -> {
//                    if (result.isSuccess()) {
//                        //打印成功
//                        mRootView.killMyself();
//                    }
//                });
    }

    public void printOrder(int tableId, boolean isSend) {
        RequestBody requestBody = new FormBody.Builder()
                .add("tableId", tableId + "")
                .build();
        mModel.printOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose info) {
                        if (info != null && info.isSuccess()) {
                            //打印
                            printOrder();
                        } else {
                            mRootView.showMessage("印單失敗!");
                            if (isSend) {
                                //印單失敗但提交新食品成功,更新一遍訂單數據
                                loadOrder(MyOrderManage.getInstance().getOrderId());
                            }
                        }
                    }
                });
    }


    private void printOrder() {
        CC.obtainBuilder("Component.Print")
                .addParam("type", 1)//印單
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    if (result.isSuccess()) {
                        //打印成功，接著打印廚房單
                        mRootView.showMessage("打印成功!");
                    } else {
                        mRootView.showMessage("打印失敗!");
                    }
                    //不管打印是否成功，都需要退出當前頁面
                    mRootView.printSuccess();
                });
    }

    public void loadOrder(int orderId) {
        mModel.loadOrder(orderId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null && info.getData().getOrderDetails() != null) {
                                OpenTableManage.getDefault().setPeopleNumber(info.getData().getPerson());
                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(info.getData()));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));
                                orderFoodList.clear();
                                orderFoodList.addAll(orderDetailList);
                            }
                            mSelectMealAdapter.notifyDataSetChanged();
                            mSelectMealAdapter.setIndex();
                        } else {
                        }
                    }
                });
    }

//    private void printOrder() {
//        CC.obtainBuilder("Component.Print")
//                .setActionName("showPrintActivity")
//                .build()
//                .call();
//    }

//    protected CreateOrderRequest getCreateOrderRequest(List<OrderDetail> foodList) {
//        CreateOrderRequest request = new CreateOrderRequest();
//        request.setOrderDetailMap(orderDetailBeanToFoodRequest(foodList));
//        request.setPerson(OpenTableManage.getDefault().getPeopleNumber());
//        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
//        return request;
//    }

//    private List<OrderBean.OrderDetailsBean> orderDetailBeanToFoodRequest(List<OrderDetail> foodList) {
//        List<OrderBean.OrderDetailsBean> requests = new ArrayList<>();
//        if (foodList != null) {
//            for (OrderDetail food : foodList) {
//                OrderBean.OrderDetailsBean request = new OrderBean.OrderDetailsBean();
//                request.setProductName(food.getProductName());
//                request.setProductId(food.getId());
//                request.setNumber(food.getNumber());
//                request.setPrice(food.getPrice());
//                request.setLunchboxPrice(0);
//                requests.add(request);
//            }
//        }
//        return requests;
//    }


}
