package com.ifavine.pay.ui.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnNetWorkErrorListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.ifavine.pay.R;
import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;
import com.ifavine.pay.utils.TLog;
import com.ifavine.pay.view.ErrorLayout;
import com.ifavine.pay.vo.CommonListResponse;
import com.ifavine.pay.vo.Entity;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by tree on 7/20/2016.
 */
public abstract class BaseListFragment<T extends Entity, D extends CommonListResponse<T>>
        extends Fragment {

    protected int mCurrentPage = 0;
    protected LRecyclerView mRecyclerView;
    protected ErrorLayout mErrorLayout;
    protected ListBaseAdapter<T> mListAdapter;
    protected LRecyclerViewAdapter mLRecyclerViewAdapter;
    protected boolean isRequestInProcess = false;
    protected boolean isPushInProcess = true;
    protected boolean mIsStart = false;


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, getPageSize(),
                    LoadingFooter.State.Loading, null);
            requestData();
        }
    };


    protected int getLayoutId() {
        return R.layout.fragment_pull_refresh_recyclerview;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        mRecyclerView = (LRecyclerView) view.findViewById(R.id.recycler_view);
        mErrorLayout = (ErrorLayout) view.findViewById(R.id.error_layout);
        return view;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public void initView(View view) {
        mListAdapter = getListAdapter();
        if (mListAdapter != null) {
            if (mListAdapter.getDataList().size() > 0) {
                mErrorLayout.setErrorType(ErrorLayout.HIDE_LAYOUT);
            } else {
                mErrorLayout.setErrorType(ErrorLayout.NETWORK_LOADING);
            }
        }
        //加载数据

        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mListAdapter);

        mRecyclerView.setAdapter(mLRecyclerViewAdapter);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.SysProgress);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.SysProgress);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setHasFixedSize(true);
        // mRecyclerView.addItemDecoration(new SpacesItemDecoration(BaseUtil.Dp2Px(getActivity(), -2)));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setPullRefreshEnabled(true);

        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mCurrentPage = 0;
                mErrorLayout.setErrorType(ErrorLayout.NETWORK_LOADING);
                requestData();
            }
        });


        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 0;
                requestData();
            }
        });

        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView,
                        getPageSize(), LoadingFooter.State.Loading, null);
                requestData();
            }
        });

        RecyclerView.Adapter outerAdapter = mRecyclerView.getAdapter();
        LoadingFooter footerView = (LoadingFooter) ((LRecyclerViewAdapter) outerAdapter).getFooterView();
        footerView.setNoMoreHint(getString(R.string.load_no_more_data));
        footerView.setHintTextColor(R.color.font_blue_16);
        requestData();
    }


    protected Call<D> mCall;

    protected void requestData() {
        TLog.log("aa", "requestData:" + mCurrentPage);
        //加载数据
        if (mCurrentPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView,
                    getPageSize(), LoadingFooter.State.Loading, null);
        }

        mCurrentPage++;

        mCall = sendRequestData();
        if (null != mCall) {
            mCall.enqueue(new Callback<D>() {
                @Override
                public void onResponse(Call<D> call, Response<D> response) {
                    mRecyclerView.refreshComplete(getPageSize());
                    if (response != null && response.isSuccessful()) {
                        if (response.body().status != 200) {
                            executeOnLoadDataError(response.body().statusCode, response.body().msg);
                            return;
                        }
                        List<T> list = response.body().data;
                        //没有数据或更多数据
                        if (list == null) {
                            if (mCurrentPage == 1) {
                                setNoDataView();
                            } else {
                                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView,
                                        getPageSize(), LoadingFooter.State.NoMore, null);
                            }
                            return;
                        }
                        //没有更多数据
                        if (list.size() < getPageSize()) {
                            mRecyclerView.setNoMore(true);
                            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView,
                                    getPageSize(), LoadingFooter.State.NoMore, null);
                        } else {
                            RecyclerViewStateUtils.setFooterViewState(mRecyclerView,
                                    LoadingFooter.State.Normal);
                            mRecyclerView.setNoMore(false);
                        }
                        executeOnLoadDataSuccess(list);
                    } else {
                        executeOnLoadDataError("", "");
                    }
                }

                @Override
                public void onFailure(Call<D> call, Throwable t) {
                    mRecyclerView.refreshComplete(getPageSize());
                    String errMsg = "未知错误";
                    if (t != null) {
                        errMsg = AppContext.getExcptionName(t);
                    }
                    executeOnLoadDataError(errMsg, errMsg);
                }
            });
        }
        isRequestInProcess = true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    protected void executeOnLoadDataSuccess(List<T> data) {

        mErrorLayout.setErrorType(ErrorLayout.HIDE_LAYOUT);
        TLog.log("executeOnLoadDataSuccess " + data.size());
        if (data == null || data.size() == 0) {
            if (mCurrentPage > 0) {
                mCurrentPage--;
            }
            return;
        }

        if (mCurrentPage == 1) {
            mListAdapter.setDataList(data);
        } else {
            mListAdapter.addAll(data);
        }
        setLoaded();
    }

    protected void executeOnLoadDataError(String errorCode, String msg) {
        mCurrentPage--;
        isRequestInProcess = false;
        mIsStart = false;
        TLog.log("aaa", "error:" + errorCode);
        mRecyclerView.refreshComplete(getPageSize());
        if (mListAdapter.getDataList().size() <= 0) {
            if ("URE00001".equals(errorCode)) {
                mErrorLayout.setErrorType(ErrorLayout.NO_PERMISSION);
            } else {
                mErrorLayout.setErrorType(ErrorLayout.NETWORK_ERROR);
                AppContext.showToast(msg);
            }
        } else {
            AppContext.showToast(msg);
            mErrorLayout.setErrorType(ErrorLayout.HIDE_LAYOUT);
            RecyclerViewStateUtils.setFooterViewState(mRecyclerView,
                    LoadingFooter.State.NetWorkError);
            //网络错误加载
            mRecyclerView.setOnNetWorkErrorListener(new OnNetWorkErrorListener() {
                @Override
                public void reload() {
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView,
                            getPageSize(), LoadingFooter.State.Loading, null);
                    requestData();
                }
            });
        }
    }


    public abstract void setNoDataView();

    public abstract void setLoaded();

    public abstract void initData();

    protected abstract Call<D> sendRequestData();

    protected abstract ListBaseAdapter<T> getListAdapter();

    public void setPushRefreshEnabled(boolean enabled) {
        isPushInProcess = enabled;
    }

    protected int getPageSize() {
        return Constants.PAGE_SIZE;
    }

    /**
     * 打开一个Activity 默认 不关闭当前activity
     */
    public void gotoActivity(Class<?> clz) {
        gotoActivity(clz, false, null);
    }

    public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity) {
        gotoActivity(clz, isCloseCurrentActivity, null);
    }

    public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity, Bundle ex) {
        Intent intent = new Intent(getActivity(), clz);
        if (ex != null) intent.putExtras(ex);
        startActivity(intent);
        if (isCloseCurrentActivity) {
            getActivity().finish();
        }
    }

    public void gotoActivity(Intent intent, boolean isCloseCurrentActivity) {
        startActivity(intent);
        if (isCloseCurrentActivity) {
            getActivity().finish();
        }
    }

}

