package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseRefreshLoadMoreFragment;
import com.sheep.gamegroup.absBase.ILoadMore;
import com.sheep.gamegroup.absBase.IRefresh;
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.CommonUtil;
import com.sheep.gamegroup.util.Conversion;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/10/9.
 * realicing@sina.com
 * 使用普通的RecyclerView来显示列表，可配合SmartRefreshLayout和ViewPager使用（setSmartRefreshLayout和setViewPager）
 */
public abstract class BaseListFragment3<T> extends BaseRefreshLoadMoreFragment{
    @Override
    public int getLayoutId() {
        return R.layout.net_empty_rv;
    }

    protected Activity activity;

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initListener();
        switch (refreshDataType()) {
            case REFRESH_ON_CREATE:
                refreshData();
                break;
            case REFRESH_ON_RESUME:
                break;
            case REFRESH_ON_YOURSELF:
            default:
                notifyDataSetChanged();
                break;
        }
        if (!useSelfEmpty() && empty_view != null)
            empty_view.setVisibility(View.GONE);
    }

    @BindView(R.id.empty_view)
    protected View empty_view;
    @BindView(R.id.check_net_ll)
    protected View check_net_ll;
    @BindView(R.id.view_list)
    protected RecyclerView view_list;

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

    public void initView() {
    }

    public void initListener() {
        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setHasFixedSize(true);
        view_list.setNestedScrollingEnabled(false);
        view_list.setAdapter(getAdapter());
    }

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

    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);
        }
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(Integer result) {
                if (result != 0) {//无网络
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
            }
        });
        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());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (refreshDataType() == REFRESH_ON_RESUME) {
            refreshData();
        }
    }

    //使用布局中自带的无数据空view
    public boolean useSelfEmpty() {
        return true;
    }

    public static final int REFRESH_ON_CREATE = 0;
    public static final int REFRESH_ON_RESUME = 1;
    public static final int REFRESH_ON_YOURSELF = -1;

    /**
     * 在哪里初始化数据：0 onViewCreated后， 1 onResume后， -1 不初始化
     *
     * @return
     */
    public int refreshDataType() {
        return REFRESH_ON_CREATE;
    }

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

        if (useSelfEmpty() && empty_view != null)
            empty_view.setVisibility(View.INVISIBLE);
        list.clear();
        page = 1;
    }

    //通过刷新来重新加载数据
    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() {
        if (view_list == null || empty_view == null) {
            return;
        }
        updateEmptyView();
        ViewUtil.notifyDataSetChanged(view_list);
        refreshOrLoadMoreComplete();
    }

    //是否显示无数据占位图
    protected void updateEmptyView() {
        if (useSelfEmpty())
            CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
    }

    protected abstract RecyclerView.Adapter getAdapter();

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

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

    protected abstract Class<T> getTClass();

}
