package com.ydl.ydlcommon.adapter

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ydl.ydlcommon.view.BaseViewHolder


/**
 * 支持添加head 和 foot的adapter
 *
 * 子类需复写bindData() 设置显示数据
 *
 * 设置加载更多回调监听
 *
 * Created by harvie on 2017/6/27 0027.
 */
class CommonRecyclerAdapter<T>(recyclerView: RecyclerView?, resLayout: Int) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var datas: ArrayList<T> = ArrayList()

    var layout : Int = resLayout

    var headView: View ?= null

    var footView: View ?=null

    var recyView : RecyclerView? = recyclerView

    private var visibleItemCount : Int = 0
    private var totalItemCount :Int = 0
    private var lastVisibleItem : Int =0
    /**
     * 当前滑动的状态
     */
    private var currentScrollState = 0

    private var layoutManagerType : LayoutManagerType =
        LayoutManagerType.LinearLayout


    //绑定数据的回调接口
    var callback : BindDataCallback<T>?=null

    //加载更多回调接口
    var loadmoreListener : OnLoadMoreLIstener? = null

    private fun setOnScrollListener(){

        recyView?.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager

                if (layoutManager is LinearLayoutManager) {
                    layoutManagerType =
                        LayoutManagerType.LinearLayout
                } else if (layoutManager is GridLayoutManager) {
                    layoutManagerType =
                        LayoutManagerType.GridLayout
                } else if (layoutManager is StaggeredGridLayoutManager) {
                    layoutManagerType =
                        LayoutManagerType.StaggeredGridLayout
                } else {
                    throw RuntimeException(
                            "Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager")
                }

                when (layoutManagerType) {
                    LayoutManagerType.LinearLayout -> lastVisibleItem = (layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                    LayoutManagerType.GridLayout -> lastVisibleItem = (layoutManager as GridLayoutManager).findLastVisibleItemPosition()
                    else -> {
                    }
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                visibleItemCount = recyclerView.childCount
                if (recyclerView.layoutManager is LinearLayoutManager){
                    val laymanager : LinearLayoutManager = recyclerView.layoutManager as LinearLayoutManager

                    totalItemCount = laymanager.itemCount
                    lastVisibleItem = laymanager.findLastVisibleItemPosition()

                    currentScrollState = newState
                    if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem >= totalItemCount - 1)) {
                        //加载更多
                        loadmoreListener?.onLoadMore()
                    }
                }
            }
        })
    }

    //设置加载更多监听
    fun setOnLoadMoreListener(loadmoreListener : OnLoadMoreLIstener) : CommonRecyclerAdapter<T> {
        this.loadmoreListener = loadmoreListener
        //设置滑动监听
        setOnScrollListener()
        return this
    }

    //update data
    fun update(datas1: List<T>?){
        if (datas1!=null){
            this.datas.clear()
            this.datas.addAll(datas1)
            notifyDataSetChanged()
        }
    }

    //追加数据
    fun addDatas(datas1: List<T>){
        this.datas.addAll(datas1)
        notifyDataSetChanged()
    }

    //设置headView
    fun addHeadView(headView: View?) {
        this.headView = headView
    }

    //添加item到列表最后
    fun addItem(t :T){
        if (t==null)return
        datas.add(t)
        notifyDataSetChanged()
    }

    //添加item到制定位置
    fun addItem(index : Int,t:T){
        if (t==null)return
        datas.add(index,t)
        notifyDataSetChanged()
    }

    //设置footView
    fun addFootView(footView: View?) {
        this.footView = footView
    }

    //设置绑定数据回调接口
    fun setBindDataCallback(callback: BindDataCallback<T>) : CommonRecyclerAdapter<T> {
        this.callback = callback
        return this
    }

    val headViewCount: Int
        get() = if (headView == null) 0 else 1

    val footViewCount: Int
        get() = if (footView == null) 0 else 1

    override fun getItemCount(): Int {
        return datas.size + headViewCount + footViewCount
    }

    override fun getItemViewType(position: Int): Int {
        if (position < headViewCount) return HEAD
        if (position >= datas.size + headViewCount) return FOOT
        return NORMAL
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == HEAD) return BaseViewHolder(
            headView
        )
        if (viewType == FOOT) return BaseViewHolder(
            footView
        )
        val view = LayoutInflater.from(viewGroup.context).inflate(layout, null)
        return BaseViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (getItemViewType(position) == HEAD) return
        if (getItemViewType(position) == FOOT) return
        //绑定数据
        callback?.bindDatabindData(holder as BaseViewHolder,datas[position-headViewCount],position-headViewCount)
    }

    companion object {
        val HEAD = 1
        val NORMAL = 2
        val FOOT = 3
    }

    interface BindDataCallback<T>{
        //绑定数据回调  需要子类设置此回调
        fun bindDatabindData(holder : BaseViewHolder, t : T, position: Int)
    }
    //加载更多监听
    interface OnLoadMoreLIstener{
        fun onLoadMore()
    }

    enum class LayoutManagerType {
        LinearLayout,
        StaggeredGridLayout,
        GridLayout
    }
}
