package com.gingersoft.gsa.cloud.table.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.qmui.arch.QMUIFragmentPagerAdapter;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.constans.GoldConstants;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.utils.ComboItemDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerSoldoutCtrlComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.SoldoutCtrlContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.presenter.SoldoutCtrlPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.FineItemAllFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridLayoutManager;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridSnapHelper;
import com.gingersoft.gsa.cloud.ui.view.RecyclerViewNoBugLinearLayoutManager;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/22/2020 10:39
 * <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>
 * ================================================
 */
public class SoldoutCtrlActivity extends BaseActivity<SoldoutCtrlPresenter> implements SoldoutCtrlContract.View, PagerGridLayoutManager.PageListener {

    private SparseArray<View> map = new SparseArray<>();

    @BindView(R2.id.tv_sold_hmmc)
    TextView tv_sold_hmmc;
    @BindView(R2.id.tv_sold_hmsl)
    TextView tv_sold_hmsl;
    @BindView(R2.id.ll_stand_oper)
    LinearLayout ll_stand_oper;

    @BindView(R2.id.ll_food_group)
    LinearLayout ll_food_group;
    @BindView(R2.id.ll_food_group_point)
    LinearLayout ll_food_group_point;

    @BindView(R2.id.recycle_current_soldout_food)
    RecyclerView recycle_current_soldout_food;
    @BindView(R2.id.recycle_food_group)
    RecyclerView recycle_food_group;
    @BindView(R2.id.recycle_food)
    RecyclerView recycle_food;
    @BindView(R2.id.recycle_combo)
    RecyclerView recycle_combo;

    @BindView(R2.id.ll_fine_item)
    LinearLayout ll_fine_item;//细项操作
    @BindView(R2.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R2.id.contentViewPager)
    ViewPager mContentViewPager;

    @BindView(R2.id.tv_soldout)
    TextView tv_soldout;
    @BindView(R2.id.tv_return)
    TextView tv_return;
//    @BindView(R2.id.btn_adddelete)
//    Button btn_adddelete;
//    @BindView(R2.id.btn_msg)
//    Button btn_msg;
//    @BindView(R2.id.btn_delete)
//    Button btn_delete;
//    @BindView(R2.id.btn_end)
//    Button btn_end;


    private int mCurrentViewMode;
    private String[] mTypeItem = {"沽清控制-食品組", "沽清控制-食品", "沽清控制-細項"};
    /**
     * 1-食品組
     * 2-食品
     * 3-細項
     * 默認為食品
     */
    private int mSoldoutType = 2;
    public static final int FOOD_GROUP_TYPE = 1;
    public static final int FOOD_TYPE = 2;
    public static final int MODIFIER_TYPE = 3;

    private FineItemAllFragment modMsgFineItemFragment, modSasteFineItemFragment;
    private String[] mFineTabTitles = {"口味", "特別信息"};
    private int mCurrentFinePageIndex;

    private boolean mInitModData = false;

    private ImageView[] ivPoints;
    private int mPageIndex;
    private int totalPage;
    private FoodGroupAdapter mFoodGroupAdapter;
    private PagerGridLayoutManager mLayoutManager;

    private int mParentRowCount;
    private int mParentColCount;
    private int mDetailColCount = 1;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSoldoutCtrlComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.meal_activity_soldout_ctrl; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initViewMap();
        initTabAndPager();
        //初始化Recyclerview高度
        initRecyclerHeight();
        //初始化适配器
        mPresenter.initAdapter();
        //初始化食品數據
        mPresenter.initFoodData();
        mPresenter.initFoodListener();
        //初始化细项控制按钮点击事件
//        mPresenter.initFineItemButtonListener(this, btn_adddelete, btn_msg, btn_delete, btn_end);
    }

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, ll_food_group);
        map.put(MealConstant.food_ViewMode, recycle_food);
        map.put(MealConstant.combo_ViewMode, recycle_combo);
        map.put(MealConstant.fine_ViewMode, ll_fine_item);
    }

    @Override
    public void initIntent() {
    }

    @Override
    public void initTopBar() {
    }

    @Override
    public void initLanguage() {
        tv_sold_hmmc.setText(LanguageUtils.get_language_system(this, "soldout_head_name", "項目名稱"));
        tv_sold_hmsl.setText(LanguageUtils.get_language_system(this, "soldout_head_number", "數量"));
    }

    @Override
    public void initLayoutParams() {
    }

    @Override
    public void initLayoutVisible() {
    }

    private void initRecyclerHeight() {
        int screenHeidth = ArmsUtils.getScreenHeidth(this);
        LinearLayout.LayoutParams para1 = (LinearLayout.LayoutParams) recycle_current_soldout_food.getLayoutParams();
        para1.height = screenHeidth * 33 / 100;
        recycle_current_soldout_food.setLayoutParams(para1);

        mParentRowCount = GsaCloudApplication.androidSetting.getFoodTypeRow();
        mParentColCount = GsaCloudApplication.androidSetting.getFoodTypeCol();
        mDetailColCount = GsaCloudApplication.androidSetting.getFoodCol();
    }

    public void initFoodGroupView(List<Food> foodGroupList) {

        //总的页数向上取整
        totalPage = (int) Math.ceil(foodGroupList.size() * 1.0 / GoldConstants.foodGriupPageSize);

        int Rows = GoldConstants.foodGriupRows;
        if (foodGroupList.size() <= GoldConstants.foodGriupColumns) {
            Rows = 1;
        }
        mLayoutManager = new PagerGridLayoutManager(Rows, GoldConstants.foodGriupColumns, PagerGridLayoutManager.HORIZONTAL);

        // 水平分页布局管理器
        mLayoutManager.setPageListener(this);
        //设置页面变化监听器
        recycle_food_group.setLayoutManager(mLayoutManager);

        // 设置滚动辅助工具
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(recycle_food_group);

        // 使用原生的 Adapter 即可
        mFoodGroupAdapter = new FoodGroupAdapter(this, foodGroupList, 2);
        mFoodGroupAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                int count = mFoodGroupAdapter.getItemCount();

            }
        });
        recycle_food_group.setAdapter(mFoodGroupAdapter);

        mFoodGroupAdapter.setOnItemClickListener(new FoodGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Food datasBean, int position) {

                VibratorUtils.pressButtonSound(SoldoutCtrlActivity.this);

                if (mSoldoutType == FOOD_GROUP_TYPE) {
                    //操作類型(暂停操作、恢复操作)
                    boolean isStopOpeart = false;
                    for (SoldoutCtrFood csf : mPresenter.getCurrentSlodoutFoodList_Full()) {
                        if (csf.getType() == FOOD_GROUP_TYPE &&
                                csf.getFoodId() != null && datasBean.getId() != null &&
                                csf.getFoodId().equals(datasBean.getId())) {
                            if (!TextUtils.isEmpty(csf.getQtyName())) {
                                isStopOpeart = true;
                                //暂停或者售罄直接提示恢复
                                String msg = LanguageUtils.get_language_system(SoldoutCtrlActivity.this, "whether.recover", "是否恢復\"") + datasBean.getFoodName() + "\"?";
                                Class[] parameterTypes = {long.class};
                                Object[] parameters = {csf.getId()};
                                CommonTipDialog.showDoubtDialog(SoldoutCtrlActivity.this, msg, SoldoutCtrlPresenter.class, mPresenter, "restoreSoldoutCtrl", parameterTypes, parameters);
                                break;
                            }
                        }
                    }
                    if (!isStopOpeart) {
                        String msg = LanguageUtils.get_language_system(SoldoutCtrlActivity.this, "whether.suspend.group", "是否暫停組別?") + datasBean.getFoodName() + "\"?";
                        Class[] parameterTypes = {Long.class, Long.class, int.class, int.class};
                        Object[] parameters = {datasBean.getId(), null, 0, 0};
                        CommonTipDialog.showDoubtDialog(SoldoutCtrlActivity.this, msg, SoldoutCtrlPresenter.class, mPresenter, "insertSoldoutCtrl", parameterTypes, parameters);
                    }
                } else {
                    mPresenter.changedMealByParentId(datasBean.getId());
                    mPresenter.setFoodSoldoutCtrData();
                }
            }
        });

        int mParentColHeight = GsaCloudApplication.androidSetting.getLayoutFoodTypeHeight() / GsaCloudApplication.androidSetting.getFoodTypeRow() * Rows;

        //设置ViewPager适配器
        recycle_food_group.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                mParentColHeight));

        //添加小圆点
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(this);
            if (i == 0) {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_unfocused);
            }
            ivPoints[i].setPadding(0, 0, 0, 0);
            ll_food_group_point.addView(ivPoints[i]);

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ivPoints[i].getLayoutParams();
            layoutParams.height = ll_food_group_point.getLayoutParams().height;
            layoutParams.width = ArmsUtils.getScreenWidth(this) / totalPage;
            ivPoints[i].setLayoutParams(layoutParams);
        }
        if (foodGroupList.size() > 10) {
            ll_food_group_point.setVisibility(View.VISIBLE);
        } else {
            ll_food_group_point.setVisibility(View.GONE);
        }
    }

    @OnClick({R2.id.tv_return, R2.id.iv_fine_item_back, R2.id.tv_soldout})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_return) {
            if (mCurrentViewMode == MealConstant.fine_ViewMode) {
                mSoldoutType = FOOD_TYPE;
                tv_soldout.setText(mTypeItem[1]);
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            } else {
                killMyself();
            }
        } else if (id == R.id.tv_soldout) {
            showClearControlDialog();
        } else if (id == R.id.iv_fine_item_back) {
            ll_fine_item.setVisibility(View.INVISIBLE);

            recycle_food_group.setVisibility(View.VISIBLE);
            recycle_food.setVisibility(View.VISIBLE);
        }
    }

    private void showClearControlDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("沽清控制");
        builder.setSingleChoiceItems(mTypeItem, (mSoldoutType - 1), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_soldout.setText(mTypeItem[which]);
                mSoldoutType = which + 1;
                //选择食品组需要收起食品、细项显示数据
                switch (mSoldoutType) {
                    case FOOD_GROUP_TYPE:
                        showViewModeVisibility(MealConstant.food_group_ViewMode);
                        break;
                    case FOOD_TYPE:
                        showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                        break;
                    case MODIFIER_TYPE:
                        if (!mInitModData) {
                            modSasteFineItemFragment.onModSasteEvent(0);
                            modMsgFineItemFragment.onModMsgMidEvent(0);
                            mInitModData = true;
                        }
                        setFineItemSlodoutListFull(mPresenter.getCurrentSlodoutFoodList_Full());
                        showViewModeVisibility(MealConstant.fine_ViewMode);
                        break;
                }

                mPresenter.filterSlodoutData(true);

                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void setCurrentSoldoutFoodAdapter(DefaultAdapter adapter) {
        recycle_current_soldout_food.setAdapter(adapter);
    }

    @Override
    public void setFoodGroupAdapter(DefaultAdapter adapter) {
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {
        initFoodLayoutManager(LinearLayoutManager.VERTICAL);
        recycle_food.setAdapter(adapter);
    }

    @Override
    public void setComboAdapter(DefaultAdapter adapter) {
        recycle_combo.setAdapter(adapter);
    }

    private GridLayoutManager foodRecycleLayoutManager;

    public void initFoodLayoutManager(int orientation) {
        foodRecycleLayoutManager = new GridLayoutManager(this, 1, orientation, false);
        recycle_food.setLayoutManager(foodRecycleLayoutManager);
        recycle_food.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public RecyclerView getRecycleCurrentSoldoutFood() {
        return recycle_current_soldout_food;
    }

    @Override
    public RecyclerView getRecycleFoodGroup() {
        return recycle_food_group;
    }

    @Override
    public RecyclerView getRecycleFood() {
        return recycle_food;
    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {

    }

    @Override
    public void setFoodRecycleSpanCount(int size) {
        if (size > 0) {
            if (size > mDetailColCount) {
                initFoodLayoutManager(LinearLayoutManager.VERTICAL);
                foodRecycleLayoutManager.setSpanCount(mDetailColCount);
            } else if (size <= mDetailColCount) {
                //只有一行就使用水平显示以免不能占满
                initFoodLayoutManager(LinearLayoutManager.HORIZONTAL);
            }
        }
    }

    @Override
    public int getSoldoutType() {
        return mSoldoutType;
    }

    @Override
    public boolean isInitFineItemLayout() {
        return false;
    }

    @Override
    public void initFineItemTabBarViewPage() {

    }

    @Override
    public void showFoodLayoutVisibility() {

    }

    @Override
    public void showFineItemLayoutVisibility() {

    }

    @Override
    public void showViewModeVisibility(int... viewMode) {
        //將所有的view隱藏
        for (int i = 0; i < map.size(); i++) {
            map.valueAt(i).setVisibility(View.INVISIBLE);
        }
        //設置當前mode為第一個傳入的mode
        for (int mode : viewMode) {
            this.mCurrentViewMode = mode;
            break;
        }
        //顯示所有傳入的需要顯示的view
        for (int mode : viewMode) {
            map.get(mode).setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageSizeChanged(int pageSize) {
    }

    @Override
    public void onPageSelect(int pageIndex) {
        mPageIndex = pageIndex;
        for (int i = 0; i < totalPage; i++) {
            if (i == pageIndex) {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_unfocused);
            }
        }
    }

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 1:
                        if (modMsgFineItemFragment != null) {
                            return modMsgFineItemFragment;
                        }
                        modMsgFineItemFragment = FineItemAllFragment.newInstance();
                        return modMsgFineItemFragment;
                    default:
                        if (modSasteFineItemFragment != null) {
                            return modSasteFineItemFragment;
                        }
                        modSasteFineItemFragment = FineItemAllFragment.newInstance();
                        return modSasteFineItemFragment;
                }
            }

            @Override
            public int getCount() {
                return mFineTabTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "";
            }
        };

        QMUITabBuilder builder = mTabSegment.tabBuilder();
        QMUITab tab1 = builder
                .setText(mFineTabTitles[0])
                .build(mContext);
        QMUITab tab2 = builder
                .setText(mFineTabTitles[1])
                .build(mContext);
        mTabSegment
                .addTab(tab1)
                .addTab(tab2);

        mContentViewPager.setAdapter(pagerAdapter);
        mContentViewPager.setCurrentItem(mCurrentFinePageIndex);
        int space = QMUIDisplayHelper.dp2px(this, 16);
        mTabSegment.setIndicator(new QMUITabIndicator(QMUIDisplayHelper.dp2px(this, 2), false, true));
        mTabSegment.setDefaultTextSize(QMUIDisplayHelper.dp2px(this, 16), QMUIDisplayHelper.dp2px(this, 16));
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.setupWithViewPager(mContentViewPager, false);
        mTabSegment.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public void onTabClick(int index) {
                mCurrentFinePageIndex = index;
            }
        });
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

            @Override
            public void onTabSelected(int index) {
                mCurrentFinePageIndex = index;
            }

            @Override
            public void onTabUnselected(int index) {
            }

            @Override
            public void onTabReselected(int index) {
                LogUtil.d(TAG, "onTabReselected " + index);
            }

            @Override
            public void onDoubleTap(int index) {
                LogUtil.d(TAG, "onDoubleTap " + index);
            }
        });
    }

    public void setFineItemSlodoutListFull(List<SoldoutCtrFood> currentSlodoutFoodListc_Full) {
        if (modMsgFineItemFragment != null) {
            modMsgFineItemFragment.updateCurrentSlodoutFoodList_Full(currentSlodoutFoodListc_Full);
        }
        if (modSasteFineItemFragment != null) {
            modSasteFineItemFragment.updateCurrentSlodoutFoodList_Full(currentSlodoutFoodListc_Full);
        }
    }

    public FoodGroupAdapter getFoodGroupAdapter() {
        return mFoodGroupAdapter;
    }
}
