package com.sheep.gamegroup.view.fragment;

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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
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.RefreshUtil;
import com.sheep.gamegroup.util.SysAppUtil;
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 ljy on 2018/9/13.
 */

public abstract class BaseListFragment2<T> extends BaseFragment {
    @Override
    public int getLayoutId() {
        return R.layout.fgt_playgame_son_refresh_layout;
    }

    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.refreshLayout)
    protected SmartRefreshLayout refreshLayout;
    @BindView(R.id.view_list)
    protected RecyclerView 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();
        }

        RefreshUtil.newInstance().publicParameterRefresh(refreshLayout, activity);
//        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//内容不满屏幕的时候也开启加载更多
//        refreshLayout.setFooterTriggerRate(1);
    }
    protected View bottomLine;
    public void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                refreshData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshlayout) {
                if(ListUtil.size(list) >= per_page*page){
                    page += 1;
                    initData();
                }else {
                    refreshlayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
                    setNoMore(true);
                }

            }
        });
        view_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isSlidingToLast;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                RecyclerView.LayoutManager layoutManager = view_list.getLayoutManager();

                if(layoutManager instanceof LinearLayoutManager){
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个view 位置
                    int lastItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                    View childView = recyclerView.getChildAt(list.size() - 1);
                    //底部bottom
//                    int bottom = childView.getBottom();
                    //正常来说RecycleView的顶部坐标应该是0,但是严格来考虑,当RecycleView设置了paddingTop时,所有子view的绘制将以paddingTop的位置为起始位置,所以实际的顶部应该是paddingTop的高度的数值.
                    int topEdge=recyclerView.getPaddingBottom();

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

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

                            refreshLayout.autoLoadMore();
                        }

                    }
                }
            }

            @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;
                }

            }
        });

//        bottomLine = ViewUtil.setBottomLine(refreshLayout, getNoMoreCallBack());

        LinearLayoutManager hotManager = new LinearLayoutManager(SheepApp.getInstance(), LinearLayoutManager.VERTICAL, false);
        view_list.setHasFixedSize(true);
        view_list.setNestedScrollingEnabled(false);
        view_list.setLayoutManager(hotManager);
        view_list.setAdapter(getAdapter());

    }

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

    protected List<T> list = ListUtil.emptyList();
    protected List<T> listCacheOneList = 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);
                }
            }
        });
        getData(urlKey);
    }

    /**
     * 获取数据
     * @return
     */
    public void getData(final String urlKey){

        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()) {
                            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){
            refreshData();
        }
    }

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

    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){
        if(!isFirstGetACache() && page == 1)
            list.clear();
        ListUtil.addAll(list, newList);
        notifyDataSetChanged();
    }
    public void notifyDataSetChanged(){
        if(refreshLayout == null)
            refreshLayout = findViewById(R.id.refreshLayout);
        if(empty_view == null)
            empty_view = findViewById(R.id.empty_view);
        if(view_list == null)
            view_list = findViewById(R.id.empty_view);
        loadMore = false;
        if(list.isEmpty()){
            refreshLayout.setVisibility(View.GONE);
        }else {

            refreshLayout.setVisibility(View.VISIBLE);
        }
        CommonUtil.getInstance().updateEmptyView(empty_view, list.isEmpty());
        if(page == 1){
            refreshLayout.finishRefresh(100/*,false*/);//传入false表示加载失败
        } else {
            refreshLayout.finishLoadMore(100/*,false*/);//传入false表示加载失败
        }
        view_list.getAdapter().notifyDataSetChanged();
        notifyData();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

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