package com.sheep.jiuyan.samllsheep.utils;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;


/**
 * @ Created by Dlg
 * @ <p>TiTle:  RecyleViewLoadMoreUtils</p>
 * @ <p>Description:RecyleView实现加载更多的工具类</p>
 * @ date:  2017/12/27 14:41
 * @ QQ:    315096953
 */

public class RecyleViewLoadMoreUtils {

    /**
     * 是否正在载入中
     */
    private boolean mIsLoading = false;
    private final static int LAYOUT_TYPE_LINEAR = 0;
    private final static int LAYOUT_TYPE_GRID = 1;
    private final static int LAYOUT_TYPE_STAGGERED_GRID = 2;
    /**
     * 加载更多时的操作
     */
    private BackDo mBackDo;
    /**
     * Layout的类型
     */
    private int mIntLayoutManagerType;
    private RecyclerView.LayoutManager mLayoutManager;

    /**
     * 设置初始化。
     *
     * @param recyclerView
     * @param backDo
     */
    public void setLoadMore(RecyclerView recyclerView, BackDo backDo) {
        initType(recyclerView);
        recyclerView.addOnScrollListener(onScrollListener);
        mBackDo = backDo;
    }

    /**
     * 设置载入状态，在正在载入状态下，不会去加载更多
     *
     * @param mIsLoading 特殊情况下，如已经不能加载更多时，可强制设置为真即可
     */
    public void setmIsLoading(boolean mIsLoading) {
        this.mIsLoading = mIsLoading;
    }

    /**
     * 加载更多的实现
     */
    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && !mIsLoading) {
                isArrivedBottom();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 0 && !mIsLoading) { //向下滚动
                isArrivedBottom();
            }
        }
    };


    /**
     * 判断各种类型的view是否到达最底端
     */
    private void isArrivedBottom() {
        int lastVisibleItemPosition = -1;
        switch (mIntLayoutManagerType) {
            case LAYOUT_TYPE_LINEAR:
                lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager)
                        .findLastVisibleItemPosition();
                break;
            case LAYOUT_TYPE_GRID:
                lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager)
                        .findLastVisibleItemPosition();
                break;
            case LAYOUT_TYPE_STAGGERED_GRID:
                StaggeredGridLayoutManager staggeredGridLayoutManager
                        = (StaggeredGridLayoutManager) mLayoutManager;
                int[] lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItemPosition = findMax(lastPositions);
                break;
        }

        int visibleItemCount = mLayoutManager.getChildCount();
        int totalItemCount = mLayoutManager.getItemCount();
        if (!mIsLoading && visibleItemCount > 0 &&
                lastVisibleItemPosition >= totalItemCount - 1) {
            mIsLoading = true;
            mBackDo.Run();
        }
    }

    /**
     * 返回数组中的最大值
     *
     * @param lastPositions
     * @return
     */
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }


    /**
     * 初始化类型
     */
    private void initType(RecyclerView recyclerView) {
        mLayoutManager = recyclerView.getLayoutManager();
        if (mLayoutManager instanceof LinearLayoutManager) {
            mIntLayoutManagerType = LAYOUT_TYPE_LINEAR;
        } else if (mLayoutManager instanceof GridLayoutManager) {
            mIntLayoutManagerType = LAYOUT_TYPE_GRID;
        } else if (mLayoutManager instanceof StaggeredGridLayoutManager) {
            mIntLayoutManagerType = LAYOUT_TYPE_STAGGERED_GRID;
        } else {
            throw new RuntimeException("不支持的Layout_Type"+mLayoutManager);
        }
    }


    /**
     * 返回是否滑动到底部了
     *
     * @param recyclerView
     * @return
     */
    private boolean isArrivedBottom2(RecyclerView recyclerView) {
        //得到当前显示的最后一个item的view
        View lastChildView = recyclerView.getLayoutManager()
                .getChildAt(recyclerView.getLayoutManager().getChildCount() - 1);
        //得到lastChildView的bottom坐标值
        int lastChildBottom = lastChildView.getBottom();
        //得到Recyclerview的底部坐标减去底部padding值，也就是显示内容最底部的坐标
        int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
        //通过这个lastChildView得到这个view当前的position值
        int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);

        //判断lastChildView的bottom值跟recyclerBottom
        //判断lastPosition是不是最后一个position
        //如果两个条件都满足则说明是真正的滑动到了底部
        if (lastChildBottom == recyclerBottom
                && lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
            return true;
        }
        return false;
    }

}
