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.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.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.PrintUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BaseRespose;
import com.gingersoft.gsa.cloud.database.bean.Food;
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.request.OrderRequest;
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();
                        break;
                    case 1:
                        printOrder(OpenTableManage.getDefault().getTableBean().getId());
//                        printOrder(OpenTableContract.getDefault().getTableBean().getId());
                        CC.obtainBuilder("Component.Print")
                                .setActionName("printActivity")
                                .addParam("type", 1)//印單
                                .build()
                                .callAsync((cc, result) -> {
                                    if (result.isSuccess()) {
                                        //打印成功
                                        mRootView.printSuccess();
                                    }
                                });
                        //打印
                        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() {
        OrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(request));
        mModel.createOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .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()) {
                            mRootView.sendSuccess();
                            mRootView.showMessage("送單成功");
                            mAppManager.killActivity(MealStandActivity.class);
                            mRootView.killMyself();
                        } else {
                            mRootView.showMessage("送單失敗");
                        }
                    }
                });
    }

    private void addOrderFood() {
        List<OrderDetail> foods = MyOrderManage.getInstance().getOrderFoodList();
        List<OrderDetail> newFoods = new ArrayList<>();
        for (OrderDetail food : foods) {
            if (food.isNew()) {
                newFoods.add(food);
            }
        }
        for (OrderDetail food : newFoods) {
            food.setOrderId(MyOrderManage.getInstance().getOrderId());
        }
        List<OrderBean.OrderDetailsBean> orderBeans = OrderBean.transOrderDetails(newFoods);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(orderBeans));
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(getOrderFoodLists()));
        mModel.addFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .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()) {
                            mRootView.showMessage("送單成功");
                            mRootView.sendSuccess();
//                            mRootView.launchActivity(new Intent(IActivity, MealStandActivity.class));
                        } else {
                            mRootView.showMessage("送單失敗");
                        }
                    }
                });
    }

    public void printOrder(int tableId) {

        RequestBody requestBody = new FormBody.Builder()
                .add("tableId", tableId + "")
                .build();

        mModel.printOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .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")
                                    .setActionName("printActivity")
                                    .addParam("type", 1)//印單
                                    .build()
                                    .callAsync((cc, result) -> {
                                        if (result.isSuccess()) {
                                            //打印成功
                                            mRootView.printSuccess();
                                        }
                                    });
                            //打印
                        } else {
                            mRootView.showMessage("印單失敗!");
                        }
                    }
                });
    }

    public void sendOrder() {
        if (MyOrderManage.getInstance().getOrderId() == -1) {
            createOrder();
        } else {
            addOrderFood();
        }
    }

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

    private OrderRequest getCreateOrderRequest(List<OrderDetail> foodList) {
        OrderRequest request = new OrderRequest();
        request.setOrderDetails(orderDetailBeanToFoodRequest(foodList));
        request.setPerson(OpenTableManage.getDefault().getPeopleNumber());
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        return request;
    }

    private OrderRequest getAddOrderFoodRequest(List<OrderDetail> foodList) {
        OrderRequest request = new OrderRequest();
        request.setOrderDetails(orderDetailBeanToFoodRequest(foodList));
        return request;
    }

    private List<OrderRequest.Request> orderDetailBeanToFoodRequest(List<OrderDetail> foodList) {
        List<OrderRequest.Request> requests = new ArrayList<>();
        if (foodList != null) {
            for (OrderDetail food : foodList) {
                OrderRequest.Request request = new OrderRequest.Request();
                request.setProductName(food.getName());
                request.setProductId(food.getFid());
                request.setNumber(food.getNumber());
                request.setPrice(food.getAmount_price());
                request.setLunchboxPrice(0);
                requests.add(request);
            }
        }
        return requests;
    }


}
