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

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

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

import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.order.contract.OrderStatusContract;
import com.gingersoft.gsa.cloud.pay.pos.fragment.PosActionStatusExceptionFragment;
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.action.order.CancelOrder;
import com.gingersoft.gsa.cloud.table.mvp.action.order.RefundOrder;
import com.gingersoft.gsa.cloud.table.mvp.action.order.TipsOrder;
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.base.delegate.IActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.arch.QMUIFragmentPagerAdapter;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
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 butterknife.BindView;
import butterknife.OnClick;

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;
    @BindView(R2.id.ll_content)
    LinearLayout ll_content;
    @BindView(R2.id.ll_bottom)
    LinearLayout ll_bottom;

    @BindView(R2.id.btn_print_order)
    QMUIAlphaButton btn_print_order;
    @BindView(R2.id.btn_cancel_order)
    QMUIAlphaButton btn_cancel_order;
    @BindView(R2.id.btn_refund)
    QMUIAlphaButton btn_refund;
    @BindView(R2.id.btn_tips)
    QMUIAlphaButton btn_tips;
    @BindView(R2.id.btn_modify_order)
    QMUIAlphaButton btn_modify_order;

    private AllOrderFragment mNormalOrderFragment, mCancelOrderFragment, mVoidOrderFragment;
    //當前顯示頁下標
    private int mCurrentFragmentIndex = 0;
    //標題
    private String[] mTabTitles = {"已付款", "已取消"};
    //        private String[] mTabTitles = {"堂食"};
    //是否已經初始化數據,默認初始化第一個頁面
    private boolean[] mPageDataInit = {true, false, false};

    private FrameLayout.LayoutParams lp_content;

    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) {
        lp_content = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        initTabAndPager();
        mPresenter.loadOrderList(OrderManagerResponse.ORDER_TYPE_DOSHOKU + "", getStatusByFragmentIndex(), 0, 10, null, false);
    }

    @Subscriber(tag = PosActionStatusExceptionFragment.REFREAFSH_ORDER_EVENT)
    private void refreafshOrder(boolean refreafsh) {
        refeshOrderList(getStatusByFragmentIndex());
    }

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

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

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

    @OnClick({R2.id.btn_print_order, R2.id.btn_modify_order, R2.id.btn_tips, R2.id.btn_cancel_order, R2.id.btn_refund})
    public void OnClick(View v) {
        OrderManagerResponse orderItem = getCurrentOrderFragment().getCheckedOrderBean();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            LoganManager.w_order(TAG, LoganManager.EVENT_CLICK, "按鈕：" + v.getTransitionName());
        }
        LoganManager.w_order(TAG, LoganManager.EVENT_CLICK, "操作訂單：" + orderItem.getOrderNo());
        if (orderItem != null) {
            int id = v.getId();
            if (id == R.id.btn_print_order) {
                mPresenter.printOrder(this, orderItem);
            } else if (id == R.id.btn_modify_order) {
                if (orderItem.getRestaurantTable() == null) {
                    showMessage("餐檯不存在,無法修改訂單");
                    return;
                }
                mPresenter.modifyOrder(this, orderItem);
            } else if (id == R.id.btn_tips) {
                mPresenter.orderTips(this, orderItem, new TipsOrder.OnRefundListener() {
                    @Override
                    public void refeshOrders() {
                        refreafshOrder(true);
                    }
                });
            } else if (id == R.id.btn_cancel_order) {
                mPresenter.orderCancel(this, orderItem, new CancelOrder.OnCancelListener() {
                    @Override
                    public void cancel(long orderId) {
                        cancelOrder(orderId, getOrderType(), getStatusByFragmentIndex());
                    }

                    @Override
                    public void refeshOrders() {
                        refreafshOrder(true);
                    }
                });
            } else if (id == R.id.btn_refund) {
                mPresenter.orderRefund(this, orderItem, new RefundOrder.OnRefundListener() {
                    @Override
                    public void refeshOrders() {
                        refreafshOrder(true);
                    }
                });
            }
        } else {
            showMessage("請選中需要操作的訂單!");
        }
    }

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

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

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 1:
                        return mTabTitles[1];
                    case 2:
                        return mTabTitles[2];
                    default:
                        return mTabTitles[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) {
                mCurrentFragmentIndex = index;
                //頁面切換
                pagerAdapter.createFragment(index);
                if (!mPageDataInit[index]) {
                    //未初始化數據，獲取數據
                    loadOrderList(getCurrentOrderFragment().getOrderType(), getStatusByFragmentIndex(), null, false);
                }
                mPageDataInit[mCurrentFragmentIndex] = true;

                lp_content.topMargin = QMUIResHelper.getAttrDimen(mContext, com.qmuiteam.qmui.R.attr.qmui_topbar_height);
                if (index == 0) {
                    lp_content.bottomMargin = 40;
                    ll_bottom.setVisibility(View.VISIBLE);
                } else {
                    lp_content.bottomMargin = 0;
                    ll_bottom.setVisibility(View.GONE);
                }
                ll_content.setLayoutParams(lp_content);
            }

            @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 void setOnCheckedChangedListener(OrderManagerResponse checkOrderBean) {
        if (checkOrderBean != null) {
            if (checkOrderBean.isCurrDeviceOrder()) {
                setBtnEnabled(btn_cancel_order, true);
                setBtnEnabled(btn_modify_order, true);
            } else {
                setBtnEnabled(btn_cancel_order, false);
                setBtnEnabled(btn_modify_order, false);
            }
            setBtnEnabled(btn_print_order, true);
        } else {
            setBtnEnabled(btn_print_order, false);
            setBtnEnabled(btn_cancel_order, false);
            setBtnEnabled(btn_modify_order, false);
        }
    }

    private void setBtnEnabled(Button btn, boolean enabled) {
        btn.setEnabled(enabled);
        btn.setClickable(enabled);
    }

    @Override
    public AllOrderFragment getCurrentOrderFragment() {
        switch (mCurrentFragmentIndex) {
            case 1:
                return mCancelOrderFragment;
            case 2:
                return mVoidOrderFragment;
            default:
                return mNormalOrderFragment;
        }
    }

    @Override
    public int getCurrentFragmentIndex() {
        return mCurrentFragmentIndex;
    }

    @Override
    public String getStatusByFragmentIndex() {
        switch (mCurrentFragmentIndex) {
            case 1:
                return OrderStatusContract.STATUS_6 + "";
            default:
                return OrderStatusContract.STATUS_4 + "," + OrderStatusContract.STATUS_5;
        }
    }

    public String getOrderType() {
        //TODO 账单管理现在只显示餐台模式订单
        return String.valueOf(OrderManagerResponse.ORDER_TYPE_DOSHOKU);
    }

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