package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
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.jcodecraeer.xrecyclerview.XRecyclerView;
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.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 com.sheep.jiuyan.samllsheep.base.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

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

/**
 * Created by realicing on 2018/9/3.
 * realicing@sina.com
 */
public abstract class BaseListFragment<T> extends BaseFragment {
    @Override
    public int getLayoutId() {
        return R.layout.net_empty_xrecycler;
    }

    protected Activity activity;
    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initListener();
        switch (refreshDataType()) {
            case 0:
                view_list.refresh();
            case 1:
                break;
            default:
                notifyDataSetChanged();
                break;
        }
    }
    @BindView(R.id.title)
    protected View title;
    @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 XRecyclerView view_list;

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

    @Subscribe
    public void initView() {
        title.setVisibility(View.GONE);
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected View bottomLine;
    public void initListener() {
        view_list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }

            @Override
            public void onLoadMore() {
                loadMoreData();

            }
        });
        bottomLine = ViewUtil.setBottomLine(view_list, getNoMoreCallBack());
        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(getAdapter());
    }

    protected void loadMoreData() {
        if(!loadMore){
            loadMore = true;
            if(ListUtil.size(list) >= per_page*page){
                page += 1;
                initData();
            }else {
                view_list.setNoMore(true);
                setNoMore(true);
            }
        }else {
            view_list.loadMoreComplete();
        }
    }

    public void setNoMore(boolean noMore) {
        this.noMore = noMore;
    }

    protected List<T> list = ListUtil.emptyList();
    protected List<T> lastCacheList = ListUtil.emptyList();
    //默认先获取缓存
    protected boolean isFirstGetACache(){
        return true;
    }
    public void setPerpage(int per_page){
        this.per_page = per_page;
    }
    public synchronized void initData() {
        final String urlKey = getKey(page, per_page);
        if(isFirstGetACache()) {
            //先尝试获取缓存数据
            lastCacheList = DataUtil.getInstance().getCacheList(urlKey, getTClass());
            loadList(lastCacheList);
        }
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(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 = baseMessage.getDatas(getTClass());
                            loadList(newList);
                        }else {
                            notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }
    public Action1<String> getNoMoreCallBack(){
        return null;
    }


    @Override
    public void onResume() {
        super.onResume();
        if(refreshDataType() == 1){
            view_list.refresh();
        }
    }

    /**
     * 在哪里初始化数据：0 onViewCreated后， 1 onResume后， -1 不初始化
     * @return
     */
    public int refreshDataType() {
        return 0;
    }
    public void clear(){
        lastMessage = null;
        setNoMore(false);
        empty_view.setVisibility(View.INVISIBLE);
        list.clear();
        page = 1;
    }
    public void refreshData(){
        clear();
        view_list.getAdapter().notifyDataSetChanged();
        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)
            view_list = findViewById(R.id.view_list);
        if(empty_view == null)
            empty_view = findViewById(R.id.empty_view);
        loadMore = false;
        updateEmptyView();
        if(page == 1){
            view_list.refreshComplete();
        } else {
            view_list.loadMoreComplete();
        }
        view_list.getAdapter().notifyDataSetChanged();
        notifyData();
        view_list.getFootView().setVisibility(view_list.getAdapter().getItemCount() == 0?View.GONE : View.VISIBLE);
    }

    protected void updateEmptyView(){
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // any time,when you finish your activity or fragment,call this below
        if(view_list != null){
            view_list.destroy(); // this will totally release XR's memory
            view_list = null;
        }
        EventBus.getDefault().unregister(this);
    }
    public int getDataCount() {
        return list.size();
    }

    /**
     *
     * @return
     */
    public void setNoFresh(){
        if(view_list != null)
            view_list.setPullRefreshEnabled(false);
    }

    private boolean noMore = false;
    public boolean isNoMore() {
        return noMore;
    }
    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();

    public abstract void notifyData();
}
