package com.hongyegroup.cpt_ewallet.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.activity.YYBaseVDBLoadingActivity
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.engine.toast
import com.guadou.lib_baselib.ext.commContext
import com.guadou.lib_baselib.ext.dp2px
import com.guadou.lib_baselib.ext.gotoActivity
import com.guadou.lib_baselib.ext.vertical
import com.guadou.lib_baselib.utils.KeyboardUtils
import com.guadou.lib_baselib.view.gloading.GLoadingTitleStatus
import com.guadou.lib_baselib.view.gloading.Gloading
import com.guadou.lib_baselib.view.gloading.GloadingPlaceHolderlAdapter
import com.hongyegroup.cpt_ewallet.BR
import com.hongyegroup.cpt_ewallet.R
import com.hongyegroup.cpt_ewallet.databinding.ActivityEwalletHistoryBinding
import com.hongyegroup.cpt_ewallet.mvvm.EWalletHistoryViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * 电子钱包的历史记录列表
 */
class EWalletHistoryActivity : YYBaseVDBLoadingActivity<EWalletHistoryViewModel, ActivityEwalletHistoryBinding>(), OnLoadMoreListener,
    OnRefreshListener {

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

    companion object {
        fun startInstance() {
            commContext().gotoActivity<EWalletHistoryActivity>()
        }
    }

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

    //重新生成GLoading对象
    override fun generateGLoading(): Gloading.Holder {
        return Gloading.from(GloadingPlaceHolderlAdapter(R.layout.layout_placeholder_normal))
            .wrap(this, GLoadingTitleStatus(true, true, false))
            .withRetry {
                initData()
            }
    }

    override fun startObserve() {

    }

    override fun init(savedInstanceState: Bundle?) {
        initRV()
        initData()
        initListener()
    }

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

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

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

        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.setOnItemClickListener { _, _, position ->
            val item = mViewModel.mHistoryDatas[position]
            clickProxy.gotoHistoryDetailPage()
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mTopDecoration?.clearCache()

        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()
    }

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

        fun backPage() {
            finish()
        }

        //执行搜索
        fun doSearch() {
            KeyboardUtils.hideSoftInput(mActivity)
            mBinding.refreshLayout.autoRefresh()
        }

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

        //根据时间搜索
        fun searchByData() {
            toast("去新页面筛选时间")
        }

        //去历史详情页面
        fun gotoHistoryDetailPage() {
            EWalletHistoryDetailJobActivity.startInstance()
        }

    }
}