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

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealFineAllContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.meal.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FineItemOneAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FineItemTwoAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.EventBus;

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

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.meal.MealSoldoutActivity.MODIFIER_TYPE;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/19/2020 22:15
 * <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>
 * ================================================
 */
@FragmentScope
public class MealFineAllPresenter extends BasePresenter<MealFineAllContract.Model, MealFineAllContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private FineItemTwoAdapter mFineItemTwoAdapter;
    private FineItemOneAdapter mFineItemAllAdapter;

    private List<Modifier> mFineItemOneList = new ArrayList<>();
    private List<Modifier> mFineItemTwoList = new ArrayList<>();

    //所有沽清数据
    private List<SoldoutCtrFood> mCurrentSoldoutFoodList_Full = null;

    //记录第一层细项上次选中的食品种类
    private int mFineItemOneLastPosition = -1;

    //操作頁面：1=沽清頁、2=餐牌頁
    private int operartPage = 1;
    private Activity IActivity;

    @Inject
    public MealFineAllPresenter(MealFineAllContract.Model model, MealFineAllContract.View rootView) {
        super(model, rootView);
        this.IActivity = (Activity) rootView.getCurrentActivity();
    }

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

    public void initAdapter() {
        if (mFineItemAllAdapter == null) {
            mFineItemAllAdapter = new FineItemOneAdapter(mApplication, mFineItemOneList);
            mRootView.setFineItemAllAdapter(mFineItemAllAdapter);
        }
        if (mFineItemTwoAdapter == null) {
            mFineItemTwoAdapter = new FineItemTwoAdapter(mApplication, mFineItemTwoList);
            mRootView.setFineItemKindItemAdapter(mFineItemTwoAdapter);
        }
    }

    public void initItemListener(Context context) {
        mFineItemAllAdapter.setOnItemClickListener(new FineItemOneAdapter.OnItemClickListener() {

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

                VibratorUtils.pressButtonSound(mApplication);

                if (context instanceof MealStandActivity || context instanceof MealStandActivity) {

                    operartPage = 2;

                    if (datasBean.isParent()) {
                        initChildFineItemItemData(datasBean.getMid());
                    } else {
                        addModifierItem(datasBean);
                    }
                } else {
                    operartPage = 1;
                    soldoutCtrlModifierItem(context, datasBean);
                }
            }
        });
        mFineItemTwoAdapter.setOnItemClickListener(new FineItemTwoAdapter.OnItemClickListener() {

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

                VibratorUtils.pressButtonSound(mApplication);

                if (operartPage == 2) {
                    addModifierItem(datasBean);
                } else {
                    soldoutCtrlModifierItem(context, datasBean);
                }
            }

            @Override
            public void onClickReturnFineItemOne() {
                mRootView.getRecycle_fine_item_kind_item().setVisibility(View.INVISIBLE);
                mRootView.getRecycle_fine_adll().setVisibility(View.VISIBLE);
            }
        });
    }

    private void addModifierItem(Modifier datasBean) {
        String OR_Qty = datasBean.getCurrentMaxNumber();
        int Qty = datasBean.getNumber();
        boolean isSoldout = false;

        if (datasBean.isSoldout() || OR_Qty.equalsIgnoreCase("售罄") || OR_Qty.equalsIgnoreCase("暫停")) {
            isSoldout = true;
        } else if (!TextUtils.isEmpty(OR_Qty)) {
            isSoldout = Integer.parseInt(OR_Qty) <= Qty;
        }
        if (isSoldout) {
            String msg = LanguageUtils.get_language_system("meal.Qty.short", "[" + datasBean.getModifierName() + "]數量不足");
            CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
        } else {
            EventBus.getDefault().post(datasBean, MealConstant.ADD_FOOD_MODIFIER);
        }

        mFineItemAllAdapter.notifyDataSetChanged();
    }

    private void soldoutCtrlModifierItem(Context context, Modifier datasBean) {
        //有子细项
//        if (datasBean.isParent()) {
//            initChildFineItemItemData(datasBean.getMid());
//        } else {
//            //操作類型(暂停操作、恢复操作)
//            if (!isStopOpeart(datasBean)) {
//                showInputNumberDialog(datasBean, context);
//            }
        EventBus.getDefault().post(datasBean, MealConstant.SOLDOUT_MODIFIER);
//        }
    }

    public void initModMsgFineItemData(long fid) {

        mFineItemOneLastPosition = -1;

        //获取数据
        List<Modifier> modifierList = mModel.queryDB_ModifierByModMsgAndVisibleQueryBuilder();
        if (modifierList.size() == 0) {
            mFineItemOneList.clear();
            mFineItemAllAdapter.notifyDataSetChanged();
            return;
        }

        setFid(modifierList, fid);

        mFineItemOneList.clear();
        mFineItemOneList.addAll(modifierList);
        mRootView.setFineItemAllRecycleSpanCount(mFineItemOneList.size());
        mFineItemAllAdapter.notifyDataSetChanged();
    }

    public void initModSasteFineItemKindData(long fid) {

        mFineItemOneLastPosition = -1;

        //获取数据
        List<Modifier> modifierList = mModel.queryDB_ModifierByModModTasteVisibleQueryBuilder();

        if (modifierList.size() == 0) {
            mFineItemOneList.clear();
            mFineItemAllAdapter.notifyDataSetChanged();
            return;
        }

        setFid(modifierList, fid);

        mFineItemOneList.clear();
        mFineItemOneList.addAll(modifierList);
        mRootView.setFineItemAllRecycleSpanCount(mFineItemOneList.size());
        mFineItemAllAdapter.notifyDataSetChanged();
    }

    public void initModCommFineItemKindData(long fid) {
        mFineItemOneLastPosition = -1;
        //获取数据
        List<Modifier> modifierList = mModel.queryDB_ModifierByModModCommVisibleQueryBuilder();
        if (modifierList.size() == 0) {
            mFineItemOneList.clear();
            mFineItemAllAdapter.notifyDataSetChanged();
            return;
        }

        setFid(modifierList, fid);

        mFineItemOneList.clear();
        mFineItemOneList.addAll(modifierList);
        mRootView.setFineItemAllRecycleSpanCount(mFineItemOneList.size());
        mFineItemAllAdapter.notifyDataSetChanged();
    }

    public void initChildFineItemItemData(long fid) {
        //获取数据
        List<Modifier> modifierList = mModel.queryDB_ModifierByTopidAndVisibleQueryBuilder(fid);

        if (modifierList.size() == 0) {
            return;
        }

        //添加返回按鈕
        Modifier datasBean = new Modifier();
        datasBean.setModifierName("返回");
        datasBean.setReturn(true);
        datasBean.setBgColor(ArmsUtils.getColor(mApplication, R.color.theme_red_color));
        modifierList.add(0, datasBean);

        setFid(modifierList, fid);

        mFineItemTwoList.clear();
        mFineItemTwoList.addAll(modifierList);
        mRootView.setFineItemKindItemRecycleSpanCount(mFineItemTwoList.size());

        updateChildModifierSlodoutFoodList_Full();

        mFineItemTwoAdapter.notifyDataSetChanged();

        mRootView.getRecycle_fine_item_kind_item().setVisibility(View.VISIBLE);
        mRootView.getRecycle_fine_adll().setVisibility(View.INVISIBLE);
    }

    /**
     * 設置細項沽清數據
     *
     * @param soldoutCtrList
     */
    public void setModifierSoldoutFoodList_Full(List<SoldoutCtrFood> soldoutCtrList) {
        this.mCurrentSoldoutFoodList_Full = soldoutCtrList;
    }

    /**
     * 更新細項組沽清數據
     */
    public void updateParentModifierSoldoutFoodList_Full() {

        clearParentModifierSoldoutCtrData();
        addStopSoldoutCtrItem(mCurrentSoldoutFoodList_Full);
        setSoldoutCtrItem(mCurrentSoldoutFoodList_Full);

        mFineItemAllAdapter.setCurrentSlodoutFoodList_Full(mCurrentSoldoutFoodList_Full);
        mFineItemAllAdapter.notifyDataSetChanged();
    }

    private void addStopSoldoutCtrItem(List<SoldoutCtrFood> soldoutCtrFoods) {
        for (Modifier modifier : mFineItemOneList) {
            if (modifier.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) MODIFIER_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(modifier.getModifierName());
                soldoutCtrFood.setFoodName1(modifier.getModifierName1());
                soldoutCtrFood.setFoodName2(modifier.getModifierName2());
                soldoutCtrFood.setModifierId(modifier.getMid());
                if (!isContainsModifier(soldoutCtrFoods, modifier)) {
                    soldoutCtrFoods.add(soldoutCtrFood);
                }
            }
        }
        for (Modifier modifier : mFineItemTwoList) {
            if (modifier.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) MODIFIER_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(modifier.getModifierName());
                soldoutCtrFood.setFoodName1(modifier.getModifierName1());
                soldoutCtrFood.setFoodName2(modifier.getModifierName2());
                soldoutCtrFood.setModifierId(modifier.getMid());
                if (!isContainsModifier(soldoutCtrFoods, modifier)) {
                    soldoutCtrFoods.add(soldoutCtrFood);
                }
            }
        }
    }

    /**
     * 更新細項組下具體細項數據
     */
    public void updateChildModifierSlodoutFoodList_Full() {
        clearChildModifierSoldoutCtrData();
        setChildModifierSoldoutCtrData(mCurrentSoldoutFoodList_Full);
    }

    private void setChildModifierSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrList) {
        for (SoldoutCtrFood scc : soldoutCtrList) {
            for (Modifier modifier : mFineItemTwoList) {
                if (scc.getType() == MODIFIER_TYPE && scc.getModifierId() != null && modifier.getMid() == scc.getModifierId()) {
                    String qtyName;
                    if (modifier.getInvisible() == 2) {
                        qtyName = "暫停";
                        scc.setStop(true);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        scc.setStop(false);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    }
                    setModifierMaxQty(modifier);
                }
            }
        }
    }

    private void setSoldoutCtrItem(List<SoldoutCtrFood> soldoutCtrList) {
        for (SoldoutCtrFood scc : soldoutCtrList) {
            for (Modifier modifier : mFineItemOneList) {
                if (scc.getType() == MODIFIER_TYPE && scc.getModifierId() != null && modifier.getMid() == scc.getModifierId()) {
                    String qtyName;
                    if (modifier.getInvisible() == 2) {
                        qtyName = "暫停";
                        scc.setStop(true);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        scc.setStop(false);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    }
                    setModifierMaxQty(modifier);
                }
            }
            for (Modifier modifier : mFineItemTwoList) {
                if (scc.getType() == MODIFIER_TYPE && scc.getModifierId() != null && modifier.getMid() == scc.getModifierId()) {
                    String qtyName;
                    if (modifier.getInvisible() == 2) {
                        qtyName = "暫停";
                        scc.setStop(true);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        scc.setStop(false);
                        modifier.setMaxNumber(qtyName);
                        modifier.setCurrentMaxNumber(qtyName);
                    }
                    setModifierMaxQty(modifier);
                }
            }
        }
    }

    private boolean isContainsModifier(List<SoldoutCtrFood> soldoutCtrFoods, Modifier modifier) {
        for (SoldoutCtrFood soldoutCtrFood : soldoutCtrFoods) {
            if (soldoutCtrFood.getType() == MODIFIER_TYPE && soldoutCtrFood.getModifierId() == modifier.getMid()) {
                return true;
            }
        }
        return false;
    }

    private void clearParentModifierSoldoutCtrData() {
        for (Modifier modifier : mFineItemOneList) {
            modifier.setMaxNumber("");
            modifier.setCurrentMaxNumber("");
        }
    }

    private void clearChildModifierSoldoutCtrData() {
        for (Modifier modifier : mFineItemTwoList) {
            modifier.setMaxNumber("");
            modifier.setCurrentMaxNumber("");
        }
    }

    public void setModifierMaxQty(Modifier modfier) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getMid() == modfier.getMid()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = modfier.getMaxNumber();
        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) {
                    modfier.setCurrentMaxNumber("售罄");
                } else {
                    modfier.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
    }

    /**
     * 返回未送單食品列表
     *
     * @return
     */
    protected List<OrderDetail> getNewOrderFoodLists() {
        List<OrderDetail> orderDetails = new ArrayList<>();
        List<OrderDetail> orderCommodityList = MealOrder.getInstance().getShoppingCart().getOrderCommodityList();
        for (int i = 0; i < orderCommodityList.size(); i++) {
            OrderDetail orderDetail = orderCommodityList.get(i);
            if (orderDetail.isNew()) {
                orderDetails.add(orderDetail);
            }
        }
        return orderDetails;
    }

    private void setFid(List<Modifier> fineItemList, long fid) {
        if (fineItemList == null) {
            return;
        }
        for (int i = 0; i < fineItemList.size(); i++) {
            Modifier modifier = fineItemList.get(i);
            modifier.setFid(fid);
        }
    }

    public void changeLanguageNotifyChanged() {
        mFineItemAllAdapter.notifyDataSetChanged();
    }

    private void destroyRecler() {
        if (mFineItemAllAdapter != null) {
            mFineItemAllAdapter = null;
        }
        if (mFineItemOneList != null) {
            mFineItemOneList.clear();
            mFineItemOneList = null;
        }
    }

}
