package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.sheep.gamegroup.absBase.BaseActivity;
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 java.util.List;

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

/**
 * Created by ljy on 2018/9/3.
 */

public abstract class BaseListActivity<T> extends BaseActivity {

    @BindView(R.id.title)
    View title;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.view_list)
    XRecyclerView view_list;
    protected Activity activity;

    @Override
    protected int getLayoutId() {
        return R.layout.net_empty_xrecycler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        activity = this;
        getType();
        initView();
        initListener();
        if(!refreshDataAfterOnResume())
            view_list.refresh();
    }

    protected int page = 1;//页数
    protected int per_page = DataUtil.PER_PAGE;
    protected BaseMessage lastMessage;//最后一个网络获取的结果
    private boolean noMore = false;
    public void initView() {
//        title.setVisibility(View.GONE);
    }
    private View bottomLine;
    public void initListener() {
        view_list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }

            @Override
            public void onLoadMore() {
                if(ListUtil.size(list) >= per_page*page){
                    page += 1;
                    initData();
                }else {
                    view_list.setNoMore(true);
                    setNoMore(true);
                }
            }
        });
        bottomLine = ViewUtil.setBottomLine(view_list);
        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(getAdapter());
        view_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isSlidingToLast;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();

                if(layoutManager instanceof LinearLayoutManager){
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;

                    //获取最后一个完全显示的item的position
                    int lastVisibleItem = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                    int totalCount = linearLayoutManager.getItemCount();
                    Log.e("lastvisi_item_-----", lastVisibleItem+","+totalCount);

                    if(newState == RecyclerView.SCROLL_STATE_IDLE && isSlidingToLast){//滑动到了底部
                        if(ListUtil.size(list) >= per_page*page){


                        }

                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e("dx-----", dx+","+dy);
                if (dy > 0) {
                    //大于0表示正在向下滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0表示停止或向上滚动
                    isSlidingToLast = false;
                }

            }
        });

    }


    protected List<T> list = ListUtil.emptyList();
    protected List<T> lastCacheList = ListUtil.emptyList();
    //默认先获取缓存
    protected boolean isFirstGetACache(){
        return true;
    }
    public 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 void refreshData(){
        lastMessage = null;
        setNoMore(false);
        empty_view.setVisibility(View.INVISIBLE);
        list.clear();
        view_list.getAdapter().notifyDataSetChanged();
        page = 1;
        initData();
    }
    private void loadList(List<T> newList){
        ListUtil.addAllItem(list, newList);
        notifyDataSetChanged();
    }
    protected void notifyDataSetChanged(){

        if(view_list == null)
            view_list = findViewById(R.id.view_list);
        if(empty_view == null)
            empty_view = findViewById(R.id.empty_view);
        if(empty_view == null)
            empty_view = findViewById(R.id.empty_view);
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        bottomLine.setVisibility(list.isEmpty() ? View.INVISIBLE : View.VISIBLE);
        if(page == 1){
            view_list.refreshComplete();
        } else {
            view_list.loadMoreComplete();
        }
        view_list.getAdapter().notifyDataSetChanged();
    }

    /**
     * 每次都在onResume方法中进行更新数据
     * @return
     */
    public boolean refreshDataAfterOnResume() {
        return false;
    }
    @Override
    public void onResume() {
        super.onResume();
        if(refreshDataAfterOnResume()){
            view_list.refresh();
        }
    }

    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();

    protected abstract int getType();
    public void setNoMore(boolean noMore) {
        this.noMore = noMore;
    }
}
