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

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

import com.billy.cc.core.component.CC;
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.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) {
                switch (position) {
                    case 0:
                        //送單
                        sendOrder(false);
                        break;
                    case 1:
                        //打印
                        sendOrder(true);
                        break;
                    case 2:
                        //結賬
                        mRootView.startActivityForResult(OrderContentActivity.BILL_CODE, OrderPayActivity.class, null);
                        break;
                }
            }
        });
        mOrderTopFunctionAdapter.setOnItemClickListener((datasBean, position) -> {

        });
    }

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

    private 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()) {
                            if (info.getData() != null) {
                                setOrderId((Double) info.getData());
                            }
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId());
                            } else {
                                mRootView.sendSuccess();
                                mRootView.showMessage("送單成功");
                                printSendOrder(getOrderFoodLists());
                                mAppManager.killActivity(MealStandActivity.class);
                                mRootView.killMyself();
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId());
                            } else {
                                mRootView.showMessage("送單失敗");
                            }
                        }
                    }
                });
    }

    private 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());
                            } else {
                                mRootView.showMessage("送單成功");
                                printSendOrder(foodLists);
                                mRootView.sendSuccess();
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId());
                            } else {
                                if(!hasNesOrderFoods()){
                                    //TODO 未新增食品點擊送單 後台不讓過直接提示即可
                                    mRootView.showMessage("送單成功");
                                    printSendOrder(foodLists);
                                    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()
                .callAsync((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());
                    if (result.isSuccess()) {
                        //打印成功
                    }
                });


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

    public void printOrder(int tableId) {
        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()) {
                         CC.obtainBuilder("Component.Print")
                                    .addParam("type", 1)//印單
                                    .setActionName("printActivity")
                                    .build()
                                    .callAsync((cc, result) -> {
                                        Log.e("error", "是否成功打印：" + result.isSuccess());
                                        if (result.isSuccess()) {
                                            //打印成功
                                            mRootView.printSuccess();
                                        } else {
                                            mRootView.printSuccess();
                                            mRootView.showMessage("打印失敗!");
                                        }
                                    });
                            //打印
                        } else {
                            mRootView.showMessage("印單失敗!");
                        }
                    }
                });
    }

    /**
     * 送單
     *
     * @param isPrint 印單先調用送單接口
     */
    public void sendOrder(boolean isPrint) {
        if (MyOrderManage.getInstance().getOrderId() == -1) {
            createOrder(isPrint);
        } else {
            addOrderFood(isPrint);
        }
    }

//    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;
//    }


}
