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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.FailureCallback;
import com.gingersoft.gsa.cloud.common.loadsir.LoadsirUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerAllTableComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.RegionTableContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.RegionTablePresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_SETTLING;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/28/2019 17:33
 * <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 RegionTableFragment extends BaseFragment<RegionTablePresenter> implements RegionTableContract.View {


    @BindView(R2.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.recycle_all_table)
    RecyclerView recycle_all_table;

    private LoadService loadService;

    private TableActivity mTableActivity;
    private OrderContentActivity mOrderContentActivity;
    /**
     * 當前頁碼
     * 0#全部
     * 1#狀態
     */
    private int currentPageIndex;

    public static RegionTableFragment newInstance() {
        RegionTableFragment fragment = new RegionTableFragment();
        return fragment;
    }

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.table_fragment_all_table, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        currentPageIndex = getArguments().getInt("currentPageIndex", TableActivity.FUNCTION_ALL_TABLE);
        if (mContext instanceof TableActivity) {
            mTableActivity = (TableActivity) mContext;
        } else if (mContext instanceof OrderContentActivity) {
            mOrderContentActivity = (OrderContentActivity) mContext;
        }
        loadService = LoadSir.getDefault().register(refreshLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (mContext instanceof TableActivity) {
                    mTableActivity.getTables(true, refreshLayout);
                } else if (mContext instanceof OrderContentActivity) {
                    mOrderContentActivity.getTables(true, refreshLayout);
                }
            }
        });
        initRefreshLayout();
        initRecycleScrollListener();
    }

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                //刷新餐檯數據
                if (mTableActivity != null) {
                    mTableActivity.getTables(false, refreshLayout);
                } else if (mOrderContentActivity != null) {
                    mOrderContentActivity.getTables(false, refreshLayout);
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
            }
        });
        refreshLayout.setEnableLoadMore(false);
    }

    private void initRecycleScrollListener() {
        recycle_all_table.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case SCROLL_STATE_IDLE://停止滚动
                        if (mTableActivity != null) {
                            mTableActivity.onStartRefreshTableData();
                        } else if (mOrderContentActivity != null) {
                            mOrderContentActivity.onStartRefreshTableData();
                        }
                        break;
                    case SCROLL_STATE_DRAGGING://正在被外部拖拽,一般为用户正在用手指滚动
                    case SCROLL_STATE_SETTLING://自动滚动开始
                        if (mTableActivity != null) {
                            mTableActivity.onPauseRefreshTableData();
                        } else if (mOrderContentActivity != null) {
                            mOrderContentActivity.onPauseRefreshTableData();
                        }
                        break;
                }
            }
        });
        recycle_all_table.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE: //用户滑动 先停止刷新餐台数据
                        if (mTableActivity != null) {
                            mTableActivity.onPauseRefreshTableData();
                        } else if (mOrderContentActivity != null) {
                            mOrderContentActivity.onPauseRefreshTableData();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (mTableActivity != null) {
                            mTableActivity.onStartRefreshTableData();
                        } else if (mOrderContentActivity != null) {
                            mOrderContentActivity.onStartRefreshTableData();
                        }
                        //用户手抬起是 继续刷新餐台数据
                        break;
                }
                return false;
            }
        });
    }

    @Override
    public void setData(@Nullable Object data) {
        List<TableBean.DataBean> datasBeans;
        if (data != null && data instanceof Message) {
            switch (((Message) data).what) {
                case 0:
                    break;
                case 1://刷新全部数据
                    datasBeans = (List<TableBean.DataBean>) ((Message) data).obj;
                    if (mPresenter != null) {
                        //recycleView正在滑动
                        if (recycle_all_table != null && recycle_all_table.getScrollState() != 0) {
                        } else {
                            if (currentPageIndex == TableActivity.FUNCTION_ALL_TABLE) {
                                mPresenter.updateAllTableData(mContext, datasBeans);
                            } else {
                                int status = ((Message) data).arg1;
                                mPresenter.updateStateTableData(mContext, datasBeans, status);
                            }
                        }
                    }
                    if (loadService != null) {
                        loadService.showSuccess();
                    }
                    if (recycle_all_table != null) {
                        recycle_all_table.setVisibility(View.VISIBLE);
                    }
                    break;
                case 2://刷新状态已变数据
                    datasBeans = (List<TableBean.DataBean>) ((Message) data).obj;
                    if (mPresenter != null) {
                        //recycleView正在滑动
                        if (recycle_all_table != null && recycle_all_table.getScrollState() != 0) {
                        } else {
                            mPresenter.updataTableItem(datasBeans);
                        }
                    }
                    if (loadService != null) {
                        loadService.showSuccess();
                    }
                    if (recycle_all_table != null) {
                        recycle_all_table.setVisibility(View.VISIBLE);
                    }
                    break;
                default:
                    //do something
                    break;
            }
        }
    }


    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastUtils.show(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    public Activity getCurrentActivity() {
        return (Activity) mContext;
    }

    @Override
    public void showLoadSirCall(boolean isSuccess, int size, Throwable t) {
        if (t != null) {
            LoadsirUtil.showCallbackByError(t, loadService);
            recycle_all_table.setVisibility(View.INVISIBLE);
            return;
        }
        if (!isSuccess) {
            loadService.showCallback(FailureCallback.class);
            recycle_all_table.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            loadService.showCallback(EmptyCallback.class);
            recycle_all_table.setVisibility(View.INVISIBLE);
            return;
        }
        loadService.showSuccess();
        recycle_all_table.setVisibility(View.VISIBLE);
    }

    @Override
    public void setAllTableAdapter(DefaultAdapter adapter) {
        recycle_all_table.setAdapter(adapter);
        initAllTableRecycleViewLayout();
    }

    private GridLayoutManager mAllTableRecycleLayoutManager;

    private void initAllTableRecycleViewLayout() {
//        if (GSAApplication.androidSetting.getTableDirection() == 2) { //横向展示
//            mAllTableRecycleLayoutManager = new GridLayoutManager(getActivity(), 5, LinearLayoutManager.HORIZONTAL, false);
//            recycle_all_table.setLayoutManager(mAllTableRecycleLayoutManager);
//            recycle_all_table.setItemAnimator(new DefaultItemAnimator());
//            recycle_all_table.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
//            recycle_all_table.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.HORIZONTAL));
//        } else {
        mAllTableRecycleLayoutManager = new GridLayoutManager(mContext, 4, LinearLayoutManager.VERTICAL, false);
        recycle_all_table.setLayoutManager(mAllTableRecycleLayoutManager);
//            recycle_all_table.addItemDecoration(new GridDividerItemDecoration(ArmsUtils.dip2px(getActivity(),1), ArmsUtils.getColor(getActivity(), R.color.theme_grey_color)));
//        recycle_all_table.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.HORIZONTAL));
//        recycle_all_table.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
//        }
    }
}
