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

import android.app.Dialog;
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.RadioButton;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
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.di.component.DaggerTableComponent;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.TableBean;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BaseFragmentAdapter;
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.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.layout.QMUIButton;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

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.PagerTabStrip;
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.pts_table_type)
    PagerSlidingTabStrip tabs;
    @BindView(R2.id.vp_table_type)
    ViewPager pager_content;

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


    public static boolean isRefreshData = false;

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

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

    private String[] tabTitles;
    private final int[] icon0 = {0, 0, 0};
    private final int[] icon1 = {0, 0, 0};

    //默认显示页下标
    private int mDefaultPosition = 1;
    //记录当前页面下标
    private int mPosition = 1;

    //餐檯操作類型
    private int mTableOperatingType = 0;

    @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) {

        initTabBarViewPage();
        mPresenter.initBottomFunction();
        mPresenter.getTables(true, GoldConstants.restaurantId);
    }


    @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();
            }
        });
        mTopBar.setTitle("餐檯模式");
    }

    @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 void returnTableList(List<TableBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            nofilyFragmentUpdateAllTableData(dataBeanList, 1);
        }
    }

    @Override
    public void openTableItem(int id) {
        mPresenter.openTable(id);
    }

//    @OnClick({R2.id.btn_init_table, R2.id.btn_cancel_operat})
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R2.id.btn_init_table:
//                mTableOperatingType = 1;
//
//                break;
//            case R2.id.btn_sure_operat:
//                sureOperat();
//                break;
//            case R2.id.btn_cancel_operat:
//                mTableOperatingType = 0;
//
//                break;
//        }
//    }

    private void sureOperat() {


    }


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

    @Override
    public void onPauseRefreshTableData() {
        isRefreshData = false;
        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());
    }


    private void nofilyFragmentUpdateAllTableData(List<TableBean.DataBean> dataBeanList, int status) {
        //更新所有餐台页数据
        if (allTableFragment != null) {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = dataBeanList;
            message.arg1 = status;
            allTableFragment.setData(message);
        }
        //更新所有餐台状态页数据
        if (stateTableFragment != null) {
            Message message = Message.obtain();
            message.what = 1;
            message.obj = dataBeanList;
            message.arg1 = status;
            stateTableFragment.setData(message);
        }
    }
    private void initTabBarViewPage() {

        fm = getSupportFragmentManager();
        List<Fragment> fragmentList = new ArrayList<>();
        // Fragment标签
        inputTableFragment = InputTableFragment.newInstance();
        allTableFragment = AllTableFragment.newInstance();
        stateTableFragment = StateTableFragment.newInstance();
        fragmentList.add(inputTableFragment);
        fragmentList.add(allTableFragment);
        fragmentList.add(stateTableFragment);
        // tab title
        tabTitles = new String[3];
        tabTitles[0] = "編號";
        tabTitles[1] = "全部";
        tabTitles[2] = "狀態";

        BaseFragmentAdapter adapter = new BaseFragmentAdapter(this, fm, fragmentList, Arrays.asList(tabTitles));
        pager_content.setAdapter(adapter);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        // 设置Tab底部选中的指示器Indicator的高度
        tabs.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.5f, dm));
        // 设置Tab底部选中的指示器 Indicator的颜色
        tabs.setIndicatorColor(ArmsUtils.getColor(this, R.color.theme_color));
        //设置Tab标题文字的颜色
        tabs.setTextColor(ArmsUtils.getColor(this, R.color.theme_text_color));
        //设置选中的Tab文字的颜色
        tabs.setSelectedTextColor(ArmsUtils.getColor(this, R.color.theme_color));
        //设置Tab底部分割线的颜色
        tabs.setUnderlineColor(Color.TRANSPARENT);
        // 设置点击某个Tab时的背景色,设置为0时取消背景色
        tabs.setTabBackground(0);
        // 设置Tab是自动填充满屏幕的
        tabs.setShouldExpand(true);
        //设置布局样式
        tabs.setIconAndText(PagerSlidingTabStrip.TABICONTEXT);
        //设置未选择的图标
        tabs.setNormalIconRes(icon0);
        //设置已选择的图标
        tabs.setLightIconRes(icon1);
        // 设置Tab标题文字的大小
//        tabs.setTextSize(GSAApplication.androidSetting.getTableFunctionTopFontSize());
        tabs.setTextSize(16);
        //设置文本
        tabs.setTabTexts(tabTitles);
        //tab间的分割线
        tabs.setDividerColor(Color.TRANSPARENT);
        //底部横线与字体宽度一致
        tabs.setIndicatorinFollower(false);
        //与ViewPager关联，这样指示器就可以和ViewPager联动
        tabs.setViewPager(pager_content);

        //设置当前现在的页面  默认输入页
        pager_content.setCurrentItem(mDefaultPosition);
        //设置当前默认显示Fragment页面
//        mPresenter.setCurrentShowFragment(fragmentList.get(mDefaultPosition));
        pager_content.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                if (!firstFlag) {
//                    //防止滑动页面 滑动的过程中不让刷新数据
//                    GSAApplication.isRefreshData = false;
//                    LogUtil.d(TAG, "position: " + position + "  positionOffset: " + positionOffset + "  positionOffsetPixels: " + positionOffsetPixels);
//                }
//                firstFlag = false;
            }

            @Override
            public void onPageSelected(int position) {
//                if (position == 0) {
//                    //标号输入页面 暂停获取餐台数据
//                    onPauseRefreshTableData();
//                } else {
//                    //页面切换完成区域，状态页面恢复获取餐台数据
//                    if (mPosition == 0) {
//                        //是从输入编号页面回到全部，使用状态页面 直接刷新餐台数据
//                        onStartRefreshTableData();
//                    } else {
//                        GSAApplication.isRefreshData = true;
//                    }
//                }
//                mPosition = position;
//                //设置当前显示Fragment页面
//                mPresenter.setCurrentShowFragment(fragmentList.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabs.setOnItemTagClickListener(new PagerSlidingTabStrip.OnItemTagClickListener() {
            @Override
            public void onItemTagClick(int position, View tab) {
//                initTableStatusPopup();
//                switch (position) {
//                    case 0:
//                        break;
//                    case 1:
//                        if (mPosition == position) {
//                            initViewPageListener();
//                        }
//                        break;
//                    case 2:
//                        if (mPosition == position) {
//                            //显示下拉框停止刷新餐台数据
//                            GSAApplication.isRefreshData = false;
//                            //处于当前tab页面 再次点击tab
//                            mTableStatusPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
//                            mTableStatusPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
//                            mTableStatusPopup.show(tab);
//                        }
//                        break;
//                }
//                mPosition = position;
//                //设置当前显示Fragment页面
//                mPresenter.setCurrentShowFragment(fragmentList.get(position));
            }
        });
    }

    public static class SortTableByName implements Comparator {

        @Override
        public int compare(Object lhs, Object rhs) {
            TableBean.DataBean s1 = (TableBean.DataBean) lhs;
            TableBean.DataBean s2 = (TableBean.DataBean) rhs;
            try {
                String s1_tn = s1.getTableName();
                String s2_tn = s2.getTableName();
                //String s1_tn_s=String.valueOf(s1_tn).com

                //各位补零
                int i = (10 - s1_tn.trim().length());
                String v = "";
                for (int j = 0; j < i; j++) {
                    v = v + "0";
                }
                s1_tn = "A" + v + s1_tn.trim();
                v = "";
                i = (10 - s2_tn.trim().length());
                for (int j = 0; j < i; j++) {
                    v = v + "0";
                }
                s2_tn = "A" + v + s2_tn.trim();
                return s1_tn.compareTo(s2_tn);
            } catch (Exception E) {
                return s1.getTableName().compareTo(s2.getTableName());
            }
        }
    }
}
