package com.hongyegroup.cpt_parttime.ui

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.guadou.cs_cptservices.base.fragment.YYBaseVDBFragment
import com.guadou.cs_cptservices.interfaces.IFragmentRefresh
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.engine.toast
import com.guadou.lib_baselib.ext.dp2px
import com.guadou.lib_baselib.ext.vertical
import com.guadou.lib_baselib.utils.KeyboardUtils
import com.hongyegroup.cpt_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.databinding.FragmentParttimeMainBinding
import com.hongyegroup.cpt_parttime.mvvm.PartTimeMainViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * 兼职模块的首页Frgment
 */
class PartTimeMainFragment : YYBaseVDBFragment<PartTimeMainViewModel, FragmentParttimeMainBinding>(), IFragmentRefresh, OnRefreshListener,
    OnLoadMoreListener {

    private var mTopDecoration: PowerfulStickyDecoration? = null
    private val mClickProxy by lazy { ClickProxy() }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_parttime_main, BR.viewModel, mViewModel)
            .addBindingParams(BR.click, mClickProxy)
    }

    override fun startObserve() {
    }

    override fun init(savedInstanceState: Bundle?) {

        initRV()
        initData()
        initListener()
    }

    private fun initData() {
        mViewModel.requestJobList().observe(this) {
            mBinding.refreshLayout.finishRefresh()
            mViewModel.mAdapter.loadMoreModule.isEnableLoadMore = true

            //清楚悬停头缓存
            if (mViewModel.isNeedCleanAllData) {
                mTopDecoration?.clearCache()
            }
        }
    }

    private fun initRV() {

        //悬停头的定义
        val listener: PowerGroupListener = object : PowerGroupListener {
            override fun getGroupName(position: Int): String? {
                //获取组名，用于判断是否是同一组
                return if (mViewModel.mDatas.size > position) {
                    mViewModel.mDatas[position].groupDate
                } else null
            }

            override fun getGroupView(position: Int): View {
                //获取自定定义的组View
                return if (mViewModel.mDatas.size > position) {
                    layoutInflater.inflate(R.layout.item_header_job_date, null, false).apply {
                        findViewById<TextView>(R.id.tv_head_job_date).text = mViewModel.mDatas[position].groupDate
                    }
                } else {
                    View(mActivity).apply { setBackgroundColor(Color.WHITE) }
                }
            }
        }
        mTopDecoration = PowerfulStickyDecoration.Builder
            .init(listener)
            .setGroupHeight(dp2px(40f))
            .setCacheEnable(true)
            .setHeaderCount(0) //是否有头布局->头布局的数量
            .setOnClickListener { _, _ -> //Head点击事件
            }
            .build()

        //设置悬停头和Adapter
        mBinding.recyclerView.vertical()
            .apply {
                addItemDecoration(mTopDecoration!!)
                adapter = mViewModel.mAdapter
            }
    }

    private fun initListener() {
        //Adapter的滑动监听，监听加载更多
        mViewModel.mAdapter.loadMoreModule.isEnableLoadMore = false
        mViewModel.mAdapter.loadMoreModule.preLoadNumber = 4
        mViewModel.mAdapter.loadMoreModule.setOnLoadMoreListener(this)

        //刷新控件初始化
        mBinding.refreshLayout.setEnableNestedScroll(true)
        mBinding.refreshLayout.setEnableLoadMore(false)
        mBinding.refreshLayout.setEnableRefresh(true)
        mBinding.refreshLayout.setOnRefreshListener(this)

        //Item点击
        mViewModel.mAdapter.addChildClickViewIds(R.id.ll_job_root, R.id.cl_banner_root)
        mViewModel.mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mViewModel.mDatas[position]
            when (view.id) {
                R.id.ll_job_root -> {
                    mClickProxy.gotoJobDetailPage()
                }
                R.id.cl_banner_root -> {
                    toast("点击banner")
                }
            }

        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mViewModel.isNeedCleanAllData = true
        mViewModel.mAdapter.loadMoreModule.loadMoreComplete()
        mViewModel.mAdapter.loadMoreModule.isEnableLoadMore = false
        //直接调用，参数从成员变量中获取
        mViewModel.mCurPage = 1
        initData()
    }

    override fun onLoadMore() {
        mViewModel.isNeedCleanAllData = false
        mViewModel.mCurPage++
        initData()
    }

    //自动刷新
    override fun scrollTopRefresh() {
        if (mViewModel.mDatas.size > 1) {
            mBinding.recyclerView.scrollToPosition(0)
        }
        mBinding.refreshLayout.autoRefresh()
    }

    /**
     * DataBinding事件处理
     */
    inner class ClickProxy {

        //执行搜索
        fun doSearch() {
            KeyboardUtils.hideSoftInput(mActivity)
            scrollTopRefresh()
        }

        //搜索的删除
        fun searchDel() {
            mViewModel.mKeywordLiveData.value = ""
            doSearch()
        }

        //跳转页面-选择城市
        fun gotoChooseCityPage() {

        }

        //跳转页面-兼职工作详情
        fun gotoJobDetailPage() {
            PartTimeJobDetailActivity.startInstance()
        }

        //推荐的排序
        fun switchReCommend() {
            mViewModel.mSortTypeLD.value = 1
        }

        //最新的排序
        fun switchlatested() {
            mViewModel.mSortTypeLD.value = 2
        }

        //附近的排序
        fun switchNearby() {
            mViewModel.mSortTypeLD.value = 3
        }

    }

}