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

import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
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.base.table.bean.TableBean;
import com.gingersoft.gsa.cloud.base.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.AllTableContract;
import com.gingersoft.gsa.cloud.table.mvp.presenter.AllTablePresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
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.qmuiteam.qmui.widget.QMUIEmptyView;
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 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.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 AllTableFragment extends BaseFragment<AllTablePresenter> implements AllTableContract.View {


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

    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;

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

    private List<TableBean.DataBean> datasBeans;

    public static AllTableFragment newInstance() {
        AllTableFragment fragment = new AllTableFragment();
        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;
        }
        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) {
        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 (mEmptyView != null)
                        mEmptyView.hide();
                    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.getScrollState() != 0) {
                        } else {
                            mPresenter.updataTableItem(datasBeans);
                        }
                    }
                    if (mEmptyView != null)
                        mEmptyView.hide();
                    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);
//        ArmsUtils.snackbarText(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;
    }

    private View.OnClickListener onRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mTableActivity != null) {
                mTableActivity.getTables(true, refreshLayout);
            } else if (mOrderContentActivity != null) {
                mOrderContentActivity.getTables(true, refreshLayout);
            }
        }
    };

    @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);
            }
            recycle_all_table.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);
            recycle_all_table.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            mEmptyView.show(getResources().getString(R.string.emptyView_mode_desc_double), null);
            recycle_all_table.setVisibility(View.INVISIBLE);
            return;
        }
        mEmptyView.hide();
        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));
//        }
    }
}
