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

import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Message;
import android.view.View;

import com.gingersoft.gsa.cloud.base.qmui.arch.QMUIFragmentPagerAdapter;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.OrderDetailItem;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderCenterComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderCenterContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderCenterPresenter;
import com.gingersoft.gsa.cloud.table.R;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;

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


/**
 * ================================================
 * Description: 訂單列表頁#顯示每個餐廳下所有已結賬單
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 14:28
 * <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 OrderCenterActivity extends BaseActivity<OrderCenterPresenter> implements OrderCenterContract.View {

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

    private AllOrderFragment allOrderFragment, cancelOrderFragment, voidOrderFragment;
    //當前顯示頁下標
    private int currentPageIndex = 0;
    //標題
    private String[] tabTitles = {"全部", "已取消", "已退款"};
    //是否已經初始化數據,默認初始化第一個頁面
    private boolean[] pageDataInit = {true, false, false};

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

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

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

        initTabAndPager();
        mPresenter.loadOrderList(1, 10, null, false);
    }

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment createFragment(int position) {
                Bundle bundle = new Bundle();
                switch (position) {
                    case 1:
                        if (cancelOrderFragment != null) {
                            return cancelOrderFragment;
                        }
                        cancelOrderFragment = new AllOrderFragment();
                        bundle.putInt("currentPageIndex", 1);
                        cancelOrderFragment.setArguments(bundle);
                        return cancelOrderFragment;
                    case 2:
                        if (voidOrderFragment != null) {
                            return voidOrderFragment;
                        }
                        voidOrderFragment = new AllOrderFragment();
                        bundle.putInt("currentPageIndex", 2);
                        voidOrderFragment.setArguments(bundle);
                        return voidOrderFragment;
                    default:
                        if (allOrderFragment != null) {
                            return allOrderFragment;
                        }
                        allOrderFragment = new AllOrderFragment();
                        bundle.putInt("currentPageIndex", 0);
                        allOrderFragment.setArguments(bundle);
                        return allOrderFragment;
                }
            }

            @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);
        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) {
                //頁面切換
                pagerAdapter.createFragment(index);
                if (!pageDataInit[index]) {
                    //未初始化數據，獲取數據
                    loadOrderList(null, false);
                }
                currentPageIndex = index;
                pageDataInit[currentPageIndex] = true;
            }

            @Override
            public void onTabUnselected(int index) {
            }

            @Override
            public void onTabReselected(int index) {
            }

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

    @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 (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();
    }

    private View.OnClickListener onRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //重新加載
            setPageIndex(1);
            loadOrderList(null, false);
        }
    };

    @Override
    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        if (t != null) {
            if (t instanceof UnknownHostException) {
                //沒有網絡
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof SocketTimeoutException) {
                //請求超時
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                //數據解析錯誤
                mEmptyView.show(false, getResources().getString(R.string.response_error_data_parsing_error), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else {
                //其他error
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            }
            mContentViewPager.setVisibility(View.INVISIBLE);
            return;
        }
        if (!isSuccess) {
            mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            mContentViewPager.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            mEmptyView.show(getResources().getString(R.string.emptyView_mode_desc_double), null);
            mContentViewPager.setVisibility(View.INVISIBLE);
            return;
        }
        mEmptyView.hide();
        mContentViewPager.setVisibility(View.VISIBLE);
    }

    @Override
    public void returnOrderItemList(List<OrderDetailItem> orderItemList) {
        Message message = Message.obtain();
        message.obj = orderItemList;
        if (getPageIndex() == 1) {
            //刷新一頁數據
            message.what = 0;
        } else {
            //加載更多數據
            message.what = 1;
        }
        switch (currentPageIndex) {
            case 0:
                allOrderFragment.setData(message);
                break;
            case 1:
                cancelOrderFragment.setData(message);
                break;
            case 2:
                voidOrderFragment.setData(message);
                break;
        }
        mEmptyView.hide();
        mContentViewPager.setVisibility(View.VISIBLE);
    }

    public void loadOrderList(RefreshLayout refreshLayout, boolean isLoadMore) {
        mPresenter.loadOrderList(getPageIndex(), getPageSize(), refreshLayout, isLoadMore);
    }

    @Override
    public void setPageIndex(int index) {
        switch (currentPageIndex) {
            case 1:
                cancelOrderFragment.setPageIndex(index);
                break;
            case 2:
                voidOrderFragment.setPageIndex(index);
                break;
            default:
                allOrderFragment.setPageIndex(index);
                break;
        }
    }

    @Override
    public int getPageIndex() {
        switch (currentPageIndex) {
            case 1:
                return cancelOrderFragment.getPageIndex();
            case 2:
                return voidOrderFragment.getPageIndex();
            default:
                return allOrderFragment.getPageIndex();
        }
    }

    @Override
    public int getPageSize() {
        switch (currentPageIndex) {
            case 1:
                return cancelOrderFragment.getPageSize();
            case 2:
                return voidOrderFragment.getPageSize();
            default:
                return allOrderFragment.getPageSize();
        }
    }


}
