package com.yidianling.home.listener

import android.support.design.widget.TabLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.yidianling.home.adapter.YdlHomeAdapter
import com.yidianling.home.constract.YdlHomeViewHolderConstract
import com.yidianling.common.tools.RxImageTool

/**
 * @author yuanwai
 * @描述:悬浮按钮监听事件
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/9/25
 */
class HomeConfideRecyleSuspendListener : RecyclerView.OnScrollListener() {

    private var mCurrentPosition = 0

    private var mSuspensionHeight: Int = RxImageTool.dip2px(51f)

    private var filterView: LinearLayout? = null

    private var adapter: YdlHomeAdapter? = null

    fun setFilterView(filterView: LinearLayout) {
        this.filterView = filterView
    }

    fun setSectionAdapter(adapter: YdlHomeAdapter) {
        this.adapter = adapter
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        if (null != filterView) {
            mSuspensionHeight = filterView!!.height
        }
    }

    override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        if (null == adapter) {
            return
        }
        val manager = recyclerView!!.layoutManager as LinearLayoutManager
        if (mCurrentPosition != manager.findFirstVisibleItemPosition()) {
            mCurrentPosition = manager.findFirstVisibleItemPosition()
        }
//        LogUtil.e("http----------------type=" + adapter!!.getItemViewType(mCurrentPosition))
        if (adapter!!.getItemViewType(mCurrentPosition) == YdlHomeViewHolderConstract.CONFIDE_VIEW) {
            var view = manager.findViewByPosition(mCurrentPosition)
            if (view != null) {
                if (view is ViewGroup) {
                    if (view.getChildAt(1) is TabLayout) {
                        var tablayout = view.getChildAt(1)
                        var location = IntArray(2)
                        tablayout.getLocationOnScreen(location)
                        if (location[1] - RxImageTool.dip2px(40f) <= mSuspensionHeight) {
                            filterView!!.visibility = View.VISIBLE
                        } else {
                            filterView!!.visibility = View.INVISIBLE
                        }
                    }
                }
            }

            var nextView = manager.findViewByPosition(mCurrentPosition + 1)
            if (nextView != null) {
                if (nextView.top <= (mSuspensionHeight + RxImageTool.dip2px(41f))) {
                    filterView!!.visibility = View.INVISIBLE
                }
            }
        } else {
            filterView!!.visibility = View.INVISIBLE
        }
    }
}