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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.qmui.arch.QMUIFragmentPagerAdapter;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.app.GoldConstants;
import com.gingersoft.gsa.cloud.table.app.TableOperatTypeConstant;
import com.gingersoft.gsa.cloud.table.di.component.DaggerTableComponent;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BaseFragmentAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.InputTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.StateTableFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gingersoft.gsa.cloud.ui.view.PagerSlidingTabStrip;
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.table.mvp.contract.TableContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.TablePresenter;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
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 12/27/2019 19:19
 * <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 TableActivity extends BaseActivity<TablePresenter> implements TableContract.View {

    @BindView(R2.id.topbar)
    QMUITopBar mTopBar;
    @BindView(R2.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R2.id.contentViewPager)
    ViewPager mContentViewPager;

    @BindView(R2.id.rv_bottom_function)
    RecyclerView rv_bottom_function;
    @BindView(R2.id.btn_cancel_operat)
    QMUIButton btn_cancel_operat;

    @BindView(R2.id.ll_table_operat_content)
    LinearLayout ll_table_operat_content;
    @BindView(R2.id.tv_operat_hint)
    TextView tv_operat_hint;
    @BindView(R2.id.tv_operat_content)
    TextView tv_operat_content;

    public static boolean isRefreshData = true;
    private boolean firstFlag = true;

    public static final int FUNCTION_ALL_TABLE = 1;
    public static final int FUNCTION_STATE_TABLE = 2;

    private InputTableFragment inputTableFragment;
    private AllTableFragment allTableFragment;
    private StateTableFragment stateTableFragment;

    private String[] tabTitles = {"編號", "全部", "狀態"};

    //當前顯示頁下標
    private int mCurrentPageIndex = 1;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTabAndPager();
        mPresenter.initBottomFunction();
        mPresenter.getTables(true);
    }

    @Subscriber(tag = "initTable_status_event")
    private void notifyUpdateTableStatus(int tableId) {
        mPresenter.initTable(tableId, false);
    }

    @Override
    public void initIntent() {
    }

    @Override
    public void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                killMyself();
            }
        });
        QMUIAlphaImageButton rightButton = mTopBar.addRightImageButton(R.drawable.icon_refresh, R.id.btn_right);
        QMUIAlphaImageButton rightButton2 = mTopBar.addRightImageButton(R.mipmap.meal_down, R.id.btn_fid);
        rightButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mPresenter.getTables(true);
            }
        });
        rightButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CC.obtainBuilder("Component.Download")
                        .setActionName("showDownloadActivity")
                        .build()
                        .call();
            }
        });
        mTopBar.setTitle("餐檯模式");
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @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(TableActivity.this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        if (intent != null)
            ArmsUtils.startActivity(intent);
    }

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

    @Override
    public void returnTableList(List<TableBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            mPresenter.filterTableByOperatType(1);
        }
    }

    @Override
    public void clickTableItem(TableBean.DataBean dataBean) {
        if (dataBean == null)
            return;
        switch (mPresenter.getCurrentChooseOperatType()) {
            case TableOperatTypeConstant.splite_table_1:

                break;
            case TableOperatTypeConstant.print_parper_2:

                break;
            case TableOperatTypeConstant.init_table_3:
                setOperatContentText(dataBean.getTableName());
                mPresenter.showOperatTipDialog(dataBean);
                break;
            case TableOperatTypeConstant.move_table_4:
                //獲取餐檯狀態
                mPresenter.getTable(dataBean.getId());
                break;
            case TableOperatTypeConstant.skyorder_mode_5:

                break;
            default:
                mPresenter.openTable(dataBean.getId());
                break;
        }
    }

    @OnClick({R2.id.btn_cancel_operat})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_cancel_operat) {
            canceOperat();
        }
    }

    @Override
    public void setCurrentOperatType(int type) {
        switch (type) {
            case TableOperatTypeConstant.splite_table_1:

                break;
            case TableOperatTypeConstant.print_parper_2:

                break;
            case TableOperatTypeConstant.init_table_3:
                tv_operat_hint.setText("請選擇需要重置的檯號");
                mTopBar.setTitle("重置檯號");
                break;
            case TableOperatTypeConstant.move_table_4:
                tv_operat_hint.setText("請選擇檯號");
                mTopBar.setTitle("轉檯");
                break;
            case TableOperatTypeConstant.skyorder_mode_5:

                break;
        }
        mPresenter.setCurrentChooseOperatType(type);
        btn_cancel_operat.setVisibility(View.VISIBLE);
        ll_table_operat_content.setVisibility(View.VISIBLE);
        rv_bottom_function.setVisibility(View.INVISIBLE);

        //转台不需要过滤
        if (mPresenter.getCurrentChooseOperatType() != TableOperatTypeConstant.move_table_4) {
            //根据操作类型过滤一遍餐台
            mPresenter.filterTableByOperatType(2);
        }
    }

    @Override
    public void canceOperat() {
        mPresenter.setCurrentChooseOperatType(-1);
        btn_cancel_operat.setVisibility(View.INVISIBLE);
        ll_table_operat_content.setVisibility(View.INVISIBLE);
        rv_bottom_function.setVisibility(View.VISIBLE);

        tv_operat_hint.setText("");
        tv_operat_content.setText("");
        mTopBar.setTitle("餐檯模式");

        mPresenter.initTableParameter();
        mPresenter.filterTableByOperatType(1);
    }

    @Override
    public void startMealStandActivity() {
        startActivity(new Intent(this, MealStandActivity.class));
    }

    @Override
    public void setOperatContentText(String contentText) {
        tv_operat_content.setText(contentText);
    }

    @Override
    public String getOperatContentText() {
        return tv_operat_content.getText().toString();
    }

    @Override
    public void onStartRefreshTableData() {
        isRefreshData = true;
        mPresenter.startTableTimer();
        mPresenter.getTables(false);
    }

    @Override
    public void onPauseRefreshTableData() {
        isRefreshData = false;
        mPresenter.cancelTableTimer();
        //立刻停止獲取餐檯接口
        if (mPresenter.getGetTablesDataDisposable() != null && !mPresenter.getGetTablesDataDisposable().isDisposed()) {
            mPresenter.getGetTablesDataDisposable().dispose();
        }
    }

    @Override
    public void setBottomFunctionAdapter(DefaultAdapter adapter) {
        setBottomFunctionRecycleLayoutManager(LinearLayoutManager.VERTICAL);
        rv_bottom_function.setAdapter(adapter);
    }

    private GridLayoutManager bottomFunctionRecycleLayoutManager;

    @Override
    public void setBottomFunctionRecycleLayoutManager(int orientation) {
        bottomFunctionRecycleLayoutManager = new GridLayoutManager(this, GoldConstants.bottomFunctionColCount, orientation, false);
        rv_bottom_function.setLayoutManager(bottomFunctionRecycleLayoutManager);
        rv_bottom_function.setItemAnimator(new DefaultItemAnimator());
    }

    public void nofilyFragmentUpdateTableData(List<TableBean.DataBean> dataBeanList, int status) {
        Message message = Message.obtain();
        message.what = 1;
        message.obj = dataBeanList;
        message.arg1 = status;
        if (inputTableFragment != null) {
            inputTableFragment.setData(message);
        }
        if (allTableFragment != null) {
            allTableFragment.setData(message);
        }
        if (stateTableFragment != null) {
            stateTableFragment.setData(message);
        }
    }

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 1:
                        if (allTableFragment != null) {
                            return allTableFragment;
                        }
                        allTableFragment = new AllTableFragment();
                        return allTableFragment;
                    case 2:
                        if (stateTableFragment != null) {
                            return stateTableFragment;
                        }
                        stateTableFragment = new StateTableFragment();
                        return stateTableFragment;
                    default:
                        if (inputTableFragment != null) {
                            return inputTableFragment;
                        }
                        inputTableFragment = new InputTableFragment();
                        return inputTableFragment;
                }
            }

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

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 1:
                        return tabTitles[1];
                    case 2:
                        return tabTitles[2];
                    default:
                        return tabTitles[0];
                }
            }
        };
        mContentViewPager.setAdapter(pagerAdapter);
        mContentViewPager.setCurrentItem(mCurrentPageIndex);
        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);
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

            @Override
            public void onTabSelected(int index) {
                if (index == 0) {
                    setBottomFunctionVisibility(false);
                    //标号输入页面 暂停刷新餐台数据
                    onPauseRefreshTableData();
                } else {
                    setBottomFunctionVisibility(true);
                    //页面切换完成区域，状态页面恢复获取餐台数据
                    onStartRefreshTableData();
                }
                mCurrentPageIndex = index;
            }

            @Override
            public void onTabUnselected(int index) {
                //滑動過程中先 暫停刷新數據
                onPauseRefreshTableData();
            }

            @Override
            public void onTabReselected(int index) {
            }

            @Override
            public void onDoubleTap(int index) {
            }
        });
    }

    private void setBottomFunctionVisibility(boolean show) {
        rv_bottom_function.setVisibility(show == true ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //開始刷新餐檯數據
        onStartRefreshTableData();
        //清空賬單數據
        MyOrderManage.getInstance().clear();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止刷新餐檯數據
        onPauseRefreshTableData();
    }
}
