package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.Conversion;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/11/26.
 * realicing@sina.com
 * 使用普通的RecyclerView来显示列表，配合BaseQuickAdapter来刷新数据与加载更多
 */
public abstract class BaseListFragment4<T> extends BaseFragment {

    protected Activity activity;
    protected RecyclerView view_list;
    protected BaseQuickAdapter<T, BaseViewHolder> adapter;

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initListener();
        initLoadMoreListener();
    }


    protected BaseMessage lastMessage;//最后一个网络获取的结果
    protected int page = 1;//页数
    protected int per_page = DataUtil.PER_PAGE;

    public void initView() {

    }

    public void initListener() {

    }

    //加载更多数据
    public void loadMoreData() {
        if (hasMore()) {
            page += 1;
            initData();
        } else {
            setNoMore(true);
        }
    }
    //还有数据没有获取
    protected boolean hasMore() {
        if(lastMessage != null && lastMessage.getTotal() > 0){
            return lastMessage.getTotal() > ListUtil.size(list);
        }
        return ListUtil.size(list) >= per_page * page;
    }

    protected void setNoMore(boolean noMore) {
        if (noMore)
            if (adapter != null)
                adapter.loadMoreEnd(true);

    }

    protected List<T> list = ListUtil.emptyList();
    protected List<T> lastCacheList = ListUtil.emptyList();

    //默认先获取缓存
    protected boolean isFirstGetACache() {
        return true;
    }

    //将baseMessage转化为list<T>
    private Conversion<BaseMessage, List<T>> conversion = new Conversion<BaseMessage, List<T>>() {
        @Override
        public List<T> convert(BaseMessage baseMessage, int position) {
            return resolveData(baseMessage, position);
        }
    };

    //加载数据
    public void initData() {
        final String urlKey = getKey(page, per_page);
        if (isFirstGetACache()) {
            //先尝试获取缓存数据
            lastCacheList = DataUtil.getInstance().getCacheList(urlKey, getTClass(), conversion, page);
            loadList(lastCacheList);
        }
        getApi(SheepApp.getInstance().getNetComponent().getApiService())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        lastMessage = baseMessage;
                        boolean isNewData = DataUtil.getInstance().isNewData(urlKey);
                        if (isNewData || !isFirstGetACache()) {
                            if (isFirstGetACache())
                                ListUtil.removeAll(list, lastCacheList);
                            List<T> newList = conversion.convert(baseMessage, page);
                            loadList(newList);
                        } else {
                            notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }


    //解析数据
    protected List<T> resolveData(BaseMessage baseMessage, int page) {
        return baseMessage.getDatas(getTClass());
    }


    public void clear() {
        lastMessage = null;
        setNoMore(false);

        list.clear();
        page = 1;
        initLoadMoreListener();
    }

    protected void initLoadMoreListener() {
        if (adapter != null && view_list != null) {
//            adapter.setUpFetchListener(new BaseQuickAdapter.UpFetchListener() {
//                @Override
//                public void onUpFetch() {
//                    LogUtil.println("BaseListFragment4", "onUpFetch");
//                    refreshData();
//                }
//            });
            adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    loadMoreData();
                }
            }, view_list);
        }
    }

    //通过刷新来重新加载数据
    public void refreshData() {
        clear();
        ViewUtil.notifyDataSetChanged(view_list);
        initData();
    }

    protected List<T> newList;

    protected void loadList(List<T> addList) {
        ListUtil.addAllItem(list, addList);
        newList = addList;
        notifyDataSetChanged();
    }

    //刷新数据
    public void notifyDataSetChanged() {
        updateEmptyView();
        ViewUtil.notifyDataSetChanged(view_list);
        if (adapter != null)
            adapter.loadMoreComplete();
    }

    //是否显示无数据占位图
    protected void updateEmptyView() {

    }

    protected abstract String getKey(int page, int per_page);

    protected abstract Observable<BaseMessage> getApi(ApiService apiService);

    protected abstract Class<T> getTClass();

}
