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

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
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.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.table.mvp.presenter.orderManager.OrderCenterPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.arch.QMUIFragmentPagerAdapter;
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 com.scwang.smartrefresh.layout.api.RefreshLayout;
import org.simple.eventbus.Subscriber;
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 BaseFragmentActivity<OrderCenterPresenter> implements OrderCenterContract.View {

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

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

    public static final int MODIFY_ORDER_RETURN_CODE = 100;

    @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(OrderManagerResponse.ORDER_TYPE_DOSHOKU+"", 0, 10, null, false);
    }

    @Subscriber(tag = "updateOrderListEvent")
    private void updateOrderList(boolean update) {
        refeshOrderList();
    }

    private void refeshOrderList(){
        setPageIndex(0);
        mPresenter.loadOrderList(OrderManagerResponse.ORDER_TYPE_DOSHOKU+"", 0, 10, null, false);
    }

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

    public void cancelOrder(long orderId, String orderType) {
        mPresenter.cancelOrder(orderId, orderType);
    }

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

    @Override
    public void returnOrderItemList(List<OrderManagerResponse> orderItemList) {
        Message message = Message.obtain();
        message.obj = orderItemList;
        if (getPageIndex() == 0) {
            //刷新一頁數據
            message.what = 0;
        } else {
            //加載更多數據
            message.what = 1;
        }
        getCurrentOrderFragment().setData(message);
    }

    @Override
    public void setPageIndex(int index) {
        getCurrentOrderFragment().setPageIndex(index);
    }

    @Override
    public int getPageIndex() {
        return getCurrentOrderFragment().getPageIndex();
    }

    @Override
    public int getPageSize() {
        return getCurrentOrderFragment().getPageSize();
    }

    @Override
    public AllOrderFragment getCurrentOrderFragment() {
        switch (currentPageIndex) {
            case 1:
                return cancelOrderFragment;
            case 2:
                return voidOrderFragment;
            default:
                return allOrderFragment;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MODIFY_ORDER_RETURN_CODE) {
            //修改訂單返回,刷新訂單數據
            refeshOrderList();
        }
    }
}
