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

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

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.bean.BaseRespose;
import com.gingersoft.gsa.cloud.base.bean.FoodBean;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.meal.R;
import com.gingersoft.gsa.cloud.meal.mvp.model.bean.request.SendOrderRequest;
import com.gingersoft.gsa.cloud.meal.mvp.model.constant.MealConstant;
import com.gingersoft.gsa.cloud.meal.mvp.model.manage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.ViewUtils;
import com.gingersoft.gsa.cloud.meal.mvp.model.bean.OrderDetail;
import com.gingersoft.gsa.cloud.meal.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.meal.mvp.ui.adapter.meal.FoodAdapter;
import com.gingersoft.gsa.cloud.meal.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.meal.mvp.ui.adapter.meal.SelectMealAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

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.Request;
import okhttp3.RequestBody;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.meal.mvp.contract.MealStandContract;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:17
 * <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 MealStandPresenter extends BasePresenter<MealStandContract.Model, MealStandContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private MealStandActivity IActivity;

    //订单数据管理类
    private MyOrderManage myOrderManage;

    private SelectMealAdapter mSelectMealAdapter;
    private FoodAdapter mFoodAdapter;

    //当前选择的食品数据
//    private SparseArray<OrderDetail.DatasBean> getOrderFoodLists() = new SparseArray<>();
    //食品种类数据
    private List<Food> mFoodGroupList = new ArrayList<>();
    //食品数据
    private List<Food> mFoodList = new ArrayList<>();

    private boolean RvMealClicked;

    @Inject
    public MealStandPresenter(MealStandContract.Model model, MealStandContract.View rootView) {
        super(model, rootView);
        this.IActivity = (MealStandActivity) rootView;

        myOrderManage = MyOrderManage.getInstance();
    }

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


    public void initOrderBefore() {

        // 无帐单号
//        if (GSAApplication.tableContract.getOrderid() == -1) {
//            if (GSAApplication.androidSetting.isOrder_InputPax()) {
//                // 选择人数
//                mRootView.showChoosePeopleNumDialog(false);
//            }
//            //设置开台时间
//            GSAApplication.tableContract.setDt_createtime(new Date());
//        }
//        if (GSAApplication.tableContract.getMember() != null) {
//            GSAApplication.tableContract.setMember(null);
//        }

        //获取订单数据
//        loadOrderList(GSAApplication.tableContract.getOrderid(), false);
    }

    public void initMealData() {

        List<Food> foodGroupList = mModel.queryDB_FoodGroupList();

        if (foodGroupList != null && foodGroupList.size() > 0) {

            IActivity.initFoodGroupView(foodGroupList);

            changedMealByParentId(foodGroupList.get(0).getId());
        }
    }

    public void initAdapter() {
        if (mSelectMealAdapter == null) {
            mSelectMealAdapter = new SelectMealAdapter(IActivity, myOrderManage.getOrderFoodList(), this);
            mRootView.setSelectFoodAdapter(mSelectMealAdapter);
        }
        myOrderManage.setSelectMealAdapter(mSelectMealAdapter);
        if (mFoodAdapter == null) {
            mFoodAdapter = new FoodAdapter(IActivity, mFoodList);
            mRootView.setFoodAdapter(mFoodAdapter);
        }
    }

    public void initItemClickListener() {
        mSelectMealAdapter.setOnItemClickListener(new SelectMealAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(Food datasBean, int position) {

                mRootView.recordOperat(true);

                RvMealClicked = true;

            }
        });
        mFoodAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(Food datasBean, int position) {

                mRootView.recordOperat(true);

                if (!foodConditionFilter(datasBean)) {
                    return;
                }

                RvMealClicked = false;

                datasBean.setNumber(1);
                mSelectMealAdapter.addFoodItem(datasBean);
            }
        });
    }


    public void loadOrder(String account, String pwd) {

        RequestBody requestBody = new FormBody.Builder()
                .add("userName", account.trim() + "")
                .add("passWord", pwd.trim() + "")
                .build();

        mModel.loadOrder(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()) {

                        } else {
                        }
                    }
                });
    }

    public void sendOrder() {
        List<SendOrderRequest> foods = getSendOrderRequest(getOrderFoodLists());
        mModel.sendOrder(foods)
                .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()) {
                            mRootView.showMessage("送單成功");
                        } else {
                            mRootView.showMessage("送單失敗");
                        }
                    }
                });
    }

    public void addOrderFood(String account, String pwd) {

        RequestBody requestBody = new FormBody.Builder()
                .add("userName", account.trim() + "")
                .add("passWord", pwd.trim() + "")
                .build();

        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<BaseRespose>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseRespose info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.showMessage("送單成功");
                        } else {
                            mRootView.showMessage("送單失敗");
                        }
                    }
                });
    }

    public void deleteFood(long id) {

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

        mModel.deleteFood(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()) {
                            mRootView.showMessage("刪除成功");
                        } else {
                            mRootView.showMessage("刪除失敗");
                        }
                    }
                });
    }


    private void deleteWithOrderedFoodById(Long id) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitle("溫馨提示");
        dialogBuilder.setMessage("是否確認刪除該食品?");
        dialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
                deleteFood(id);
            }
        });
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create(R.style.QMUI_Dialog).show();
    }

    /**
     * 刪除食品
     *
     * @param deleteStyle 1=點擊刪除、2=長按刪除
     */
    public void deleteFoodItem(int deleteStyle) {

        Food deleteFood = getOrderFoodLists().get(mSelectMealAdapter.getSelect_position());

        if (!deleteFood.isNew()) {
            //TODO 刪除已下單食品
            deleteWithOrderedFoodById(deleteFood.getId());
        } else {
            if (deleteStyle == 2) {
                mSelectMealAdapter.removeAllNewFoodItem();
            } else {
                mSelectMealAdapter.removeFoodItem();
            }
        }
    }

    public void changedMealByParentId(long parentId) {
        List<Food> foodList = mModel.queryDB_FoodList(parentId);
        if (foodList != null) {
            mFoodList.clear();
            mFoodList.addAll(foodList);
            //根据Item个数显示每一行的个数
            mRootView.setFoodRecycleSpanCount(mFoodList.size());
            mFoodAdapter.notifyDataSetChanged();
        }
        mRootView.showViewModeVisibility(MealConstant.food_ViewMode, MealConstant.food_group_ViewMode);
    }

    /**
     * 设置当前食品还可最多选几份
     *
     * @param foodBean
     */
    public boolean setUserMaxQty(Food foodBean) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            Food orderFood = getOrderFoodLists().get(i);
            if (orderFood.getId() == foodBean.getId()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }

//        String User_Qty = foodBean.getOR_Qty();
//        if (!User_Qty.equals("") && !User_Qty.equals("售罄") && !User_Qty.equals("暫停")) {
//            int maxQty = Integer.parseInt(User_Qty);
//            if (maxQty > 0) {
//                int Currrent_OR__Qty = maxQty - currentSelectNumber;
//                if (Currrent_OR__Qty < 1) {
//                    foodBean.setCurrrent_OR_Qty("售罄");
//                    return false;
//                } else {
//                    foodBean.setCurrrent_OR_Qty(Currrent_OR__Qty + "");
//                }
//            }
//        }
        return true;
    }

    /**
     * 添加食品条件过滤
     * 1：售罄、最大选择数
     * 2：是否需要会员积分
     * 3：
     */
    public boolean foodGroupConditionFilter(Food foodBean, boolean init) {

        if (init) {
            return true;
        }

//        String User_Qty = foodBean.getOR_Qty();
//        if (!TextUtils.isEmpty(User_Qty)) {
//            TitleDialog.showTitledialog(IActivity, foodBean.getName()
//                            + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停(Comm.pause)"),
//                    "", LanguageUtils.get_language_system(IActivity, "comm.ok", "ok(comm.ok)"), "", null);
//            return false;
//        }

        return true;
    }

    private boolean foodConditionFilter(Food foodBean) {

        int isSold = foodBean.getIsSold();
        if (isSold == 1) {
            new QMUITipDialog.Builder(IActivity)
                    .setTipWord("已售罄(Comm.sold)")
                    .create(true);
            return false;
        }

//        String User_Qty = foodBean.getCurrrent_OR_Qty();
//
//        if (!TextUtils.isEmpty(User_Qty)) {
//            if (User_Qty.equals("售罄") || User_Qty.equals("暫停")) {
//                TitleDialog.showTitledialog(IActivity, foodBean.getName()
//                                + LanguageUtils.get_language_system(IActivity, "Comm.pause", "已暫停(Comm.pause)"),
//                        "", LanguageUtils.get_language_system(IActivity, "comm.ok", "ok(comm.ok)"), "", null);
//                return false;
//            }
//        }
//
//        if (GSAApplication.tableContract.getMember() == null) {
//            //当前食品需要会员积分
//            if (foodBean.getPointsRedeem() > 0) {
//                mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "unused_members_can.not.order.food", "積分食品，未使用會員，不可點選") + "\"" + foodBean.getName() + "\"");
//                return false;
//            }
//        } else {
//            if (GSAApplication.tableContract.getMember().getDatas() != null) {
//                //如果没有会员，则pointsadd=5是加5分  pointsredeem=5是減5分
//                //當一張臺號沒有會員登錄時判定積分為0 不能為負數
//                //	此時call pointsredeem=5  的食物   不給過
//                //點選pointsadd=5的食物  0+5 是正數  這個給過
//                if (foodBean.getPointsRedeem() > 0 && GSAApplication.tableContract.getMember().getDatas().getData().getMemberPoint() < foodBean.getPointsRedeem()) {
//                    mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "insufficient.points.can.not.selected", "積分食品，會員積分不足，不可點選") + "\"" + foodBean.getName() + "\"");
//                    return false;
//                }
//            }
//        }

        return true;
    }


    /**
     * @return
     */
    private boolean isCreateOrder() {
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            Food orderFood = getOrderFoodLists().get(i);
            if (!orderFood.isNew())
                return false;
        }

        return true;
    }

    private List<SendOrderRequest> getSendOrderRequest(List<Food> foodList) {
        List<SendOrderRequest> sendOrderRequestList = new ArrayList<>();
        for (int i = 0; i < foodList.size(); i++) {
            Food food = foodList.get(i);
            SendOrderRequest request = new SendOrderRequest(food.getId(), food.getFoodName(), food.getPrice(), 0, food.getNumber());
            sendOrderRequestList.add(request);
        }
        return sendOrderRequestList;
    }


    public Food getOrderFoodById(long id) {
        for (int i = 0; i < mFoodList.size(); i++) {
            Food foodBean = mFoodList.get(i);
            if (id == foodBean.getId()) {
                return foodBean;
            }
        }
        return null;
    }


    public List<Food> getOrderFoodLists() {
        return myOrderManage.getOrderFoodList();
    }

    public boolean isRvMealClicked() {
        return RvMealClicked;
    }

    public void setRvMealClicked(boolean rvMealClicked) {
        RvMealClicked = rvMealClicked;
    }
}
