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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.mealManage.OpenTableContract;
import com.gingersoft.gsa.cloud.base.bean.TableBean;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.ViewUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.meal.R2;
import com.gingersoft.gsa.cloud.meal.app.GoldConstants;
import com.gingersoft.gsa.cloud.meal.mvp.ui.adapter.MyViewPagerAdapter;
import com.gingersoft.gsa.cloud.meal.di.component.DaggerMealStandComponent;
import com.gingersoft.gsa.cloud.meal.mvp.model.constant.MealConstant;
import com.gingersoft.gsa.cloud.meal.mvp.ui.adapter.HorizontalGridViewAdpter;
import com.gingersoft.gsa.cloud.meal.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.ui.dialog.LoadingDialog;
import com.gingersoft.gsa.cloud.ui.view.LineGridView;
import com.gingersoft.gsa.cloud.ui.view.PagerSlidingTabStrip;
import com.gingersoft.gsa.cloud.ui.view.RecyclerViewNoBugLinearLayoutManager;
import com.gingersoft.gsa.cloud.ui.view.SearchKeyBoardView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.gingersoft.gsa.cloud.meal.mvp.contract.MealStandContract;
import com.gingersoft.gsa.cloud.meal.mvp.presenter.MealStandPresenter;
import com.gingersoft.gsa.cloud.meal.R;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.simple.eventbus.EventBus;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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 butterknife.OnLongClick;

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


/**
 * ================================================
 * 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>
 * ================================================
 */
public class MealStandActivity extends BaseActivity<MealStandPresenter> implements MealStandContract.View {

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

    @BindView(R2.id.ctime)
    Chronometer chronometer;

    @BindView(R2.id.rv_select_meal)
    RecyclerView rv_select_meal;

    @BindView(R2.id.ll_food_group)
    LinearLayout ll_food_group;
    @BindView(R2.id.vp_food_group)
    ViewPager vp_food_group;
    @BindView(R2.id.ll_food_group_point)
    LinearLayout ll_food_group_point;
    //    @BindView(R2.id.rv_food_group)
//    RecyclerView rv_food_group;
    @BindView(R2.id.rv_food)
    RecyclerView rv_food;
    @BindView(R2.id.rv_combo)
    RecyclerView rv_combo;
    @BindView(R2.id.rv_discount)
    RecyclerView rv_discount;

    @BindView(R2.id.rl_fine_tabs)
    RelativeLayout rl_fine_tabs;
    @BindView(R2.id.iv_fine_back)
    ImageView iv_fine_back;
    @BindView(R2.id.tabs_fine)
    PagerSlidingTabStrip tabs_fine;
    @BindView(R2.id.pager_fine)
    ViewPager pager_fine;
    @BindView(R2.id.meal_stand_search_keyboard_view)
    SearchKeyBoardView keyView;

    @BindView(R2.id.ll_stand_oper)
    LinearLayout ll_stand_oper;
    @BindView(R2.id.tv_no_save_return)
    TextView tv_no_save_return;
//    @BindView(R2.id.tv_send_order)
//    TextView tv_send_order;

    @BindView(R2.id.fl_order_content)
    FrameLayout fl_order_content;
    @BindView(R2.id.tv_order_content)
    TextView tv_order_content;
    @BindView(R2.id.btn_order_count)
    Button btn_order_count;

    //送单
    @BindView(R2.id.fl_send_order)
    FrameLayout fl_send_order;
    @BindView(R2.id.btn_send_order)
    Button btn_send_order;
//    @BindView(R2.id.btn_send_order_machine_name)
//    TextView btn_send_order_machine_name;

    //印单
    @BindView(R2.id.fl_printer_order)
    FrameLayout fl_printer_order;
    @BindView(R2.id.btn_order_printer)
    Button btn_order_printer;
    @BindView(R2.id.btn_printer_machine_name)
    TextView btn_printer_machine_name;

    @BindView(R2.id.ll_meals)
    LinearLayout ll_meals;
    @BindView(R2.id.ll_meals_main)
    LinearLayout ll_meals_main;
    @BindView(R2.id.ll_mm)
    LinearLayout ll_mm;

    @BindView(R2.id.btn_table)
    Button btn_table;
    @BindView(R2.id.btn_numberman)
    Button btn_numberman;
    @BindView(R2.id.btn_fid)
    TextView btn_fid;
    //    @BindView(R2.id.btn_temporary)
//    TextView btn_temporary;
//    @BindView(R2.id.btn_meal_discount)
//    TextView btn_meal_discount;
    @BindView(R2.id.btn_meal_delete)
    TextView btn_meal_delete;
//    @BindView(R2.id.btn_meal_modify_restore)
//    ImageButton btn_meal_modify_restore;
//    @BindView(R2.id.btn_change_Language)
//    ImageButton btn_change_Language;
//    @BindView(R2.id.btn_food_merge)
//    ImageButton btn_food_merge;
//    @BindView(R2.id.btn_food_mode)
//    TextView btn_food_mode;


    @BindView(R2.id.ll_Keys)
    LinearLayout ll_Keys;
    @BindView(R2.id.btn_key0)
    Button btn_key0;
    @BindView(R2.id.btn_key1)
    Button btn_key1;
    @BindView(R2.id.btn_key2)
    Button btn_key2;
    @BindView(R2.id.btn_key3)
    Button btn_key3;
    @BindView(R2.id.btn_key4)
    Button btn_key4;
    @BindView(R2.id.btn_keys)
    Button btn_keys;

    @BindView(R2.id.ll_modify)
    LinearLayout ll_modify;
    @BindView(R2.id.btn_add_delete)
    Button btn_add_delete;
    @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 ChooseNumberDialog chooseNumberDialog;


    private int mCurrentViewMode;
    private boolean isPluMode = false;

    private HorizontalGridViewAdpter mFoodGroupGridViewAdapter;
    //小圆点图片的集合
    private ImageView[] ivPoints;
    //总的页数
    private int totalPage;
    //每页显示的最大的数量
    private int mPageSize = 12;
    //GridView作为一个View对象添加到ViewPager集合中
    private List<View> viewPagerList;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMealStandComponent //如找不到该类,请编译一下项目
                .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_meal_stand; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

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

        initViewMap();
        //初始化Plu模式
        setPluMode();
        initOrderDetail();
        mPresenter.initAdapter();
        mPresenter.initItemClickListener();
        //初始化默认食品组
        mPresenter.initMealData();
        //获取订单数据
        mPresenter.loadOrderBefore();
        //搜索
        keyView.setOnConfirmCallBack(inputText -> {
            if (TextUtils.isEmpty(inputText))
                return;
            mPresenter.toFindMeal(inputText);
        });

    }

    private void initOrderDetail() {
        TableBean.DataBean dataBean = OpenTableContract.getDefault().getTableBean();
        if (dataBean != null) {
            btn_table.setText(dataBean.getTableName());
            btn_numberman.setText(dataBean.getPeopleNumber()+"");
        }
    }

    public void initFoodGroupView(List<Food> foodGroupList) {

        ll_food_group_point.setVisibility(View.VISIBLE);

        //默認選中第一組
        foodGroupList.get(0).setIsSelected(true);

        //总的页数向上取整
        totalPage = (int) Math.ceil(foodGroupList.size() * 1.0 / mPageSize);
        viewPagerList = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            //每个页面都是inflate出一个新实例
            LineGridView gridView = (LineGridView) View.inflate(this, R.layout.meal_food_group_grid, null);
            gridView.setNumColumns(6);
            HorizontalGridViewAdpter horizontalGridViewAdpter = new HorizontalGridViewAdpter(this, foodGroupList, i, mPageSize);
            gridView.setAdapter(horizontalGridViewAdpter);
            if (i == 0) {
                mFoodGroupGridViewAdapter = horizontalGridViewAdpter;
            }
            //添加item点击监听
            horizontalGridViewAdpter.setOnItemClickListener(new HorizontalGridViewAdpter.OnItemClickListener() {

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

                    recordOperat(true);

                    if (!ViewUtils.isFastClick2()) {
                        return;
                    }

                    if (!foodGroupConditionFilter(food, false)) {
                        return;
                    }

                    mFoodGroupGridViewAdapter = horizontalGridViewAdpter;

                    mPresenter.setRvMealClicked(false);

                    mPresenter.changedMealByParentId(food.getId());
                }
            });
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        vp_food_group.setAdapter(new MyViewPagerAdapter(viewPagerList));

        //添加小圆点
        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);
        }
        //设置ViewPager的滑动监听，主要是设置点点的背景颜色的改变
        vp_food_group.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

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

    /**
     * 添加食品条件过滤
     * 1：售罄、最大选择数
     */
    public boolean foodGroupConditionFilter(Food foodBean, boolean init) {

        if (init) {
            return true;
        }

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

        return true;
    }

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

    @Override
    public void initFineItemTabBarViewPage() {

    }

    @Override
    public void showFinePage() {

    }

    @Override
    public void setPluMode() {
        isPluMode = (boolean) SPUtils.get(this, MealConstant.EXIT_IS_PLU_MODE, false);
        if (isPluMode) {
            btn_fid.setBackgroundColor(ArmsUtils.getColor(this, R.color.theme_grey_color));
            showViewModeVisibility(MealConstant.ViewMode_keys);
        }
    }

    @Override
    public void resetPluMode() {
        isPluMode = false;
        SPUtils.put(this, MealConstant.EXIT_IS_PLU_MODE, false);
        btn_fid.setBackground(ArmsUtils.getDrawablebyResource(this, R.drawable.ui_selector_item_background));
    }

    @OnLongClick({R2.id.btn_meal_delete, R2.id.btn_order_printer})
    public boolean onLongClick1(View view) {

        //记录操作 并且震动
        recordOperat(true);

        int id = view.getId();
        if (id == R.id.btn_meal_delete) {
            mPresenter.deleteFoodItem(2);
        } else if (id == R.id.btn_order_printer) {

        }
        return false;
    }

    @OnClick({R2.id.btn_numberman, R2.id.btn_fid, R2.id.btn_meal_delete, R2.id.btn_send_order, R2.id.tv_no_save_return, R2.id.fl_order_content})
    public void onClick(View v) {

        recordOperat(true);

        if (!ViewUtils.isFastClick2()) {
            return;
        }

        int id = v.getId();
        if (id == R.id.btn_numberman) {
            showChoosePeopleNumDialog(true);
        } else if (id == R.id.btn_fid) {
            //搜索
            if (mCurrentViewMode == MealConstant.ViewMode_keys) {
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            } else {
                showViewModeVisibility(MealConstant.ViewMode_keys);
            }
        } else if (id == R.id.btn_meal_delete) {
            mPresenter.deleteFoodItem(1);
        } else if (id == R.id.btn_send_order) {
            mPresenter.sendOrder();
        } else if (id == R.id.fl_order_content) {
            Intent intent = new Intent(this, OrderContentActivity.class);
            startActivity(intent);
        } else if (id == R.id.tv_no_save_return) {
            returnTableActivity(true);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        returnTableActivity(true);
    }

    public void returnTableActivity(boolean initTable) {
        SPUtils.put(this, MealConstant.EXIT_IS_PLU_MODE, isPluMode);
        if (initTable && OpenTableContract.getDefault() != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableContract.getDefault().getTableBean().getId(), "initTable_status_event");
        }
        //返回餐台页面
        killMyself();
    }

    @Override
    public void recordOperat(boolean isPressButtonSound) {
        if (isPressButtonSound)
            VibratorUtils.pressButtonSound(this);
        //关闭倒计时
        if (chronometer != null) {
            chronometer.stop();
        }
        //重新开启倒计时
        if (chronometer != null) {
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();
        }
    }

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        if (chooseNumberDialog == null) {
            chooseNumberDialog = new ChooseNumberDialog(this);
            chooseNumberDialog.builder();
            chooseNumberDialog.setValueHint("請輸入人數");
//            mInputNumberDialog2.setTitle(LanguageUtils.get_language_system(this, "Meal.Mannumber", "Number"));
//            mInputNumberDialog2.setHeadLayoutVisibility(View.VISIBLE);
            if (!isNeedCancel)
                chooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

                    @Override
                    public void OnBackClick() {
                        recordOperat(true);
//                        returnTableOrOrderManagementActivity();
                    }
                });
            int backPageBtnVisibility;
            if (isNeedCancel) {
                backPageBtnVisibility = View.GONE;
            } else {
                backPageBtnVisibility = View.VISIBLE;
            }
//            mInputNumberDialog2.setBackPageBtnVisibility(backPageBtnVisibility);
            chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    //选择的人数大于0
                    if (Integer.parseInt(number) > 0) {
                        OpenTableContract.getDefault().getTableBean().setPeopleNumber(Integer.parseInt(number));
                    }
                    btn_numberman.setText(number);
                }

                @Override
                public void onBackPage() {
                    returnTableActivity(true);
                }
            });
            chooseNumberDialog.setCancelable(isNeedCancel);
        }
    }

    @Override
    public void setPrinterLocalmachine(boolean isPrint) {

    }

    @Override
    public void setTableInfoDialogAdapter(BaseAdapter adapter) {

    }

    @Override
    public void setSelectFoodAdapter(RecyclerView.Adapter adapter) {
        setSelectFoodRecycleLayoutManager();
        rv_select_meal.setAdapter(adapter);
    }

    @Override
    public void setFoodGroupAdapter(DefaultAdapter adapter) {
    }

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

    @Override
    public void setComboAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void setDiscountAdapter(DefaultAdapter adapter) {

    }

    private GridLayoutManager foodRecycleLayoutManager;

    @Override
    public void setSelectFoodRecycleLayoutManager() {
        RecyclerViewNoBugLinearLayoutManager selectFoodRecycleLayoutManager = new RecyclerViewNoBugLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rv_select_meal.setLayoutManager(selectFoodRecycleLayoutManager);
//        rv_select_meal.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodGroupRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setFoodRecycleLayoutManager(int orientation) {
        foodRecycleLayoutManager = new GridLayoutManager(this, 1, orientation, false);
        rv_food.setLayoutManager(foodRecycleLayoutManager);
        rv_food.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setComboRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setDiscountRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {

    }

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

    @Override
    public void setComboRecycleSpanCount(int size) {

    }

    @Override
    public void setDiscountRecycleSpanCount(int size) {

    }

    @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);
        }
        //設置當前模式為輸入Plu模式
        if (viewMode != null && viewMode[0] == MealConstant.ViewMode_keys) {
            isPluMode = true;
        } else {
            isPluMode = false;
        }
        switch (mCurrentViewMode) {
            case MealConstant.food_group_ViewMode:
            case MealConstant.food_ViewMode:
                showModifyLayoutVisibility(false);
                break;
            case MealConstant.combo_ViewMode:
            case MealConstant.discount_ViewMode:
                showModifyLayoutVisibility(true);
                break;
        }
    }

    @Override
    public void showModifyLayoutVisibility(boolean show) {
//        if (show) {
//            ll_modify.setVisibility(View.VISIBLE);
//            ll_stand_oper.setVisibility(View.INVISIBLE);
//        } else {
//            ll_modify.setVisibility(View.INVISIBLE);
//            ll_stand_oper.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void setOrderFoodCount(String number) {
        if (!number.equals(0)) {
            btn_order_count.setText(number);
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void setMealRvScrollToPosition(int position) {
        rv_select_meal.scrollToPosition(position);
    }

    @Override
    public void initIntent() {
    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (!TextUtils.isEmpty(message))
            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.snackbarText(message);
    }

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

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

    @Override
    public Activity getActivity() {
        return this;
    }

    public void clearInput() {
        keyView.clearInput();
    }

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, ll_food_group);
        map.put(MealConstant.food_ViewMode, rv_food);
        map.put(MealConstant.combo_ViewMode, rv_combo);
        map.put(MealConstant.discount_ViewMode, rv_discount);
        map.put(MealConstant.fine_ViewMode, pager_fine);
        map.put(MealConstant.fine_tabs_ViewMode, rl_fine_tabs);
        map.put(MealConstant.ViewMode_keys, keyView);
    }

    public HorizontalGridViewAdpter getFoodGroupGridViewAdapter() {
        return mFoodGroupGridViewAdapter;
    }
}
