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

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.graphics.Color;
import android.print.PrintManager;
import android.util.Log;
import android.view.View;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult;
import com.billy.cc.core.component.IComponentCallback;
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.PrinterManger.PrinterManager;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableContract;
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.gingersoft.gsa.cloud.ui.dialog.LoadingDialog;
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 com.qmuiteam.qmui.widget.popup.QMUIPopup;

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(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<Food> foods = MyOrderManage.getInstance().getOrderFoodList();
        List<Food> newFoods = new ArrayList<>();
        for (Food food : foods) {
            if (food.getIsNew()) {
                newFoods.add(food);
            }
        }
        for (Food 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<Food> foodList) {
        OrderRequest request = new OrderRequest();
        request.setOrderDetails(foodBeanToFoodRequest(foodList));
        request.setPerson(OpenTableContract.getDefault().getTableBean().getPeopleNumber());
        request.setTableId(OpenTableContract.getDefault().getTableBean().getId());
        return request;
    }

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

    private List<OrderRequest.Request> foodBeanToFoodRequest(List<Food> foodList) {
        List<OrderRequest.Request> requests = new ArrayList<>();
        for (Food food : foodList) {
            OrderRequest.Request request = new OrderRequest.Request();
            request.setProductName(food.getFoodName());
            request.setProductId(food.getId());
            request.setNumber(food.getNumber());
            request.setPrice(food.getPrice());
            request.setLunchboxPrice(0);
            requests.add(request);
        }
        return requests;
    }


}
