package com.qy.agv.ui.swipeView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.qy.agv.R;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * 自定义View继承SwipeRefreshLayout，添加上拉加载更多的布局属性
 * Created by Pinger on 2016/9/26.
 */

public class SwipeRefreshGridView extends SwipeRefreshLayout {

    private final int mScaledTouchSlop;
    private final View mFooterView;
    private GridViewWithHeaderAndFooter mListView;
    private OnLoadListener mOnLoadListener;
    private BaseAdapter adapter;
    private Context context;

    /**
     * 正在加载状态
     */
    private boolean isLoading;

    public SwipeRefreshGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 填充底部加载布局
        mFooterView = View.inflate(context, R.layout.swipe_view_footer, null);
        this.context = context;
        // 表示控件移动的最小距离，手移动的距离大于这个距离才能拖动控件
        mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        System.out.println("====" + mScaledTouchSlop);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        // 获取ListView,设置ListView的布局位置
        if (mListView == null) {
            // 判断容器有多少个孩子
            for (int i=0;i<getChildCount();i++) {
                // 判断第一个孩子是不是ListView
                if (getChildAt(i) instanceof GridViewWithHeaderAndFooter) {
                    // 创建ListView对象
                    mListView = (GridViewWithHeaderAndFooter) getChildAt(i);

                    // 设置ListView的滑动监听
                    setListViewOnScroll();
                }
            }
            if(mListView!=null){
                mListView.addFooterView(mFooterView);
                mListView.setAdapter(adapter);
                mListView.removeFooterView(mFooterView);
            }
        }
    }

    /**
     * 在分发事件的时候处理子控件的触摸事件
     *
     * @param ev
     * @return
     */
    private float mDownY,mMoveY, mUpY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if(isRefreshing()){
            System.out.println("正在刷新");
            return false;
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 移动的起点
                mDownY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                // 移动过程中判断时候能下拉加载更多
                mMoveY = ev.getY();
                if (canLoadMore()) {
                    // 加载数据
                    loadData();
                }

                break;
            case MotionEvent.ACTION_UP:
                // 移动的终点
                mUpY = ev.getY();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
        return !isRefreshing() && super.onStartNestedScroll(child, target, nestedScrollAxes);
    }

    /**
     * 判断是否满足加载更多条件
     *
     * @return
     */
    private boolean canLoadMore() {
        // 1. 是上拉状态
        boolean condition1 = (mDownY - mUpY) >= mScaledTouchSlop;
        if (condition1) {
            System.out.println("是上拉状态");
        }

        boolean condition4 = (mDownY - mMoveY) >= mScaledTouchSlop;
        if (condition4) {
            System.out.println("往上移动");
        }

        // 2. 当前页面可见的item是最后一个条目
        boolean condition2 = false;
        if (mListView != null && mListView.getAdapter() != null) {
            condition2 = mListView.getLastVisiblePosition() == (mListView.getAdapter().getCount() - 1);
        }

        if (condition2) {
            System.out.println("是最后一个条目");
        }
        // 3. 正在加载状态
        boolean condition3 = !isLoading;
        if (condition3) {
            System.out.println("不是正在加载状态");
        }
        return condition1 && condition2 && condition3 && condition4;
    }

    /**
     * 处理加载数据的逻辑
     */
    private void loadData() {
        System.out.println("加载数据...");
        if (mOnLoadListener != null) {
            // 设置加载状态，让布局显示出来
            setLoading(true);
            mOnLoadListener.onLoad();
        }

    }

    /**
     * 设置加载状态，是否加载传入boolean值进行判断
     *
     * @param loading
     */
    public void setLoading(boolean loading) {
        // 修改当前的状态
        isLoading = loading;
        if (isLoading) {
            // 显示布局
//            View mFooterView = View.inflate(context, R.layout.rrgy_view_footer, null);
            ViewGroup p = (ViewGroup) mFooterView.getParent();
            if (p != null) {
                p.removeAllViewsInLayout();
            }
            mListView.addFooterView(mFooterView);
            mListView.setSelection(mListView.getBottom());
        } else {
            // 隐藏布局
            mListView.removeFooterView(mFooterView);

            // 重置滑动的坐标
            mDownY = 0;
            mUpY = 0;
        }
    }


    /**
     * 设置ListView的滑动监听
     */
    private void setListViewOnScroll() {

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 移动过程中判断时候能下拉加载更多
                if (canLoadMore()) {
                    // 加载数据
                    loadData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    public void autoRefresh() {
        try {
            Field mCircleView = SwipeRefreshLayout.class.getDeclaredField("mCircleView");
            mCircleView.setAccessible(true);
            View progress = (View) mCircleView.get(this);
            progress.setVisibility(VISIBLE);

            Method setRefreshing = SwipeRefreshLayout.class.getDeclaredMethod("setRefreshing", boolean.class, boolean.class);
            setRefreshing.setAccessible(true);
            setRefreshing.invoke(this, true, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上拉加载的接口回调
     */

    public interface OnLoadListener {
        void onLoad();
    }

    public void setOnLoadListener(OnLoadListener listener) {
        this.mOnLoadListener = listener;
    }

    public void setAdapter(BaseAdapter adapter) {
        this.adapter = adapter;
    }
}
