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

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.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.FineItemOneAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.FineItemTwoAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.table.mvp.contract.FineItemAllContract;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;

import org.simple.eventbus.EventBus;

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

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity.FOOD_GROUP_TYPE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity.FOOD_TYPE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity.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 FineItemAllPresenter extends BasePresenter<FineItemAllContract.Model, FineItemAllContract.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 FineItemAllPresenter(FineItemAllContract.Model model, FineItemAllContract.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) {

                    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(mApplication, "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;

        //获取数据
        ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
        List<Modifier> modifierList = modifierDaoUtils.queryModifierByModMsgAndVisibleQueryBuilder();

        if (modifierList == null || 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;

        //获取数据
        ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
        List<Modifier> modifierList = modifierDaoUtils.queryModifierByModModTasteVisibleQueryBuilder();

        if (modifierList == null || 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;

        //获取数据
        ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
        List<Modifier> modifierList = modifierDaoUtils.queryModifierByModModCommVisibleQueryBuilder();

        if (modifierList == null || 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) {

        //获取数据
        ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
        List<Modifier> modifierList = modifierDaoUtils.queryModifierByTopidAndVisibleQueryBuilder(fid);

        if (modifierList == null || 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<>();
        for (int i = 0; i < MyOrderManage.getInstance().getOrderFoodList().size(); i++) {
            OrderDetail orderDetail = MyOrderManage.getInstance().getOrderFoodList().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;
        }
//        if (mCurrentSoldoutFoodList_Full != null) {
//            mCurrentSoldoutFoodList_Full.clear();
//            mCurrentSoldoutFoodList_Full = null;
//        }
    }

}
