package com.hongyegroup.cpt_parttime.ui.main

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
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.YYBaseVDBLoadingFragment
import com.guadou.cs_cptservices.interfaces.IFragmentRefresh
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.ext.checkEmpty
import com.guadou.lib_baselib.ext.dp2px
import com.guadou.lib_baselib.ext.horizontal
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_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.databinding.FragmentParttimeMainBinding
import com.hongyegroup.cpt_parttime.mvvm.PartTimeHomeViewModel
import com.hongyegroup.cpt_parttime.ui.activity.PartTimeIndustryActivity
import com.hongyegroup.cpt_parttime.ui.activity.PartTimeJobDetailActivity
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.flow.MutableStateFlow
import java.util.*

/**
 * 兼职模块的首页Frgment
 */
class PartTimeHomeFragment : YYBaseVDBLoadingFragment<PartTimeHomeViewModel, FragmentParttimeMainBinding>(), IFragmentRefresh, OnRefreshListener,
    OnLoadMoreListener {

    private val startForResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val industryIds = result.data?.getStringArrayListExtra("industryIds")
            setIndustryFilter(industryIds)
        }
    }

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

    //重新生成GLoading对象-跳动动画
    override fun generateGLoading(view: View): Gloading.Holder {
        return Gloading.from(GloadingPlaceHolderlAdapter(R.layout.layout_placeholder_parttime_job))
            .wrap(view, GLoadingTitleStatus(true, true, true))
            .withRetry { onGoadingRetry() }
    }

    override fun startObserve() {
    }

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

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

    override fun onGoadingRetry() {
        mViewModel.isNeedPlaceHolder = true
        mViewModel.mCurPage = 1
        initData()
    }

    private fun initRV() {
        //顶部的横向RV使用
        mBinding.rvNewJob.horizontal().adapter = mViewModel.mNewJobAdapter

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

            override fun getGroupView(position: Int): View {
                //获取自定定义的组View
                return if (mViewModel.mAllJobDataes.size > position) {
                    layoutInflater.inflate(R.layout.item_header_job_date, null, false).apply {
                        findViewById<TextView>(R.id.tv_head_job_date).text = mViewModel.mAllJobDataes[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.rvAllJob.vertical()
            .apply {
                addItemDecoration(mTopDecoration!!)
                adapter = mViewModel.mAllJobAdapter
            }
    }

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

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

        //Item点击-进入详情
        mViewModel.mAllJobAdapter.setOnItemClickListener { _, view, position ->
            val item = mViewModel.mAllJobDataes[position]
            mClickProxy.gotoJobDetailPage()
        }

        //新工作的点击-进入详情
        mViewModel.mNewJobAdapter.setOnItemClickListener { _, view, position ->
            mClickProxy.gotoJobDetailPage()
        }
    }

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

        mViewModel.isNeedCleanAllData = true
        mViewModel.mAllJobAdapter.loadMoreModule.loadMoreComplete()
        mViewModel.mAllJobAdapter.loadMoreModule.isEnableLoadMore = false
        //直接调用，参数从成员变量中获取
        mViewModel.mCurPage = 1
        initData()
    }

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

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

    }

    //设置行业的筛选选中
    private fun setIndustryFilter(industryIds: ArrayList<String>?) {
        mViewModel.mFilterIndustryIds = industryIds
        //设置是否选中
        mClickProxy.filterIndustryFlow.value = !industryIds.checkEmpty()
    }

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

        var filterIndustryFlow = MutableStateFlow(false)
        var filterDateFlow = MutableStateFlow(false)
        var filterOptionFlow = MutableStateFlow(false)

        //关闭Activity
        fun backPage() {
            mActivity.finish()
        }

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

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

        //重置筛选的条件
        fun searchReset() {
            filterIndustryFlow.value = false
            filterDateFlow.value = false
            filterOptionFlow.value = false
            mViewModel.mKeywordLiveData.value = ""
            doSearch()
        }

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

        fun filterIndustry() {
            //带返回值的启动
            startForResultLauncher.launch(
                Intent(mActivity, PartTimeIndustryActivity::class.java).putExtra("industryIds", mViewModel.mFilterIndustryIds)
            )
        }

        fun filterDate() {
            filterDateFlow.value = true
        }

        fun filterOption() {
            filterOptionFlow.value = true
        }

    }

}