package com.gh.gamecenter.energy.view

import android.os.Bundle
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.core.utils.ClickUtils
import com.gh.gamecenter.common.utils.safelyGetInRelease
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.energy.eventbus.EBTask
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class TaskFragment : ListFragment<TaskItemData, TaskViewModel>() {

    private var mAdapter: TaskAdapter? = null

    override fun provideListAdapter() = mAdapter
        ?: TaskAdapter(requireContext()).apply { mAdapter = this }

    override fun provideListViewModel(): TaskViewModel = viewModelProvider()

    override fun getItemDecoration() = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mListRefresh?.isNestedScrollingEnabled = false
    }

    override fun onLoadDone() {
        super.onLoadDone()
        mListRefresh?.isEnabled = false
    }

    override fun onLoadRefresh() {
        // 防止"短时间内触发多次刷新，任务列表会变成可以无限加载"
        if (!ClickUtils.isFastDoubleClick()) {
            mListViewModel.load(LoadType.REFRESH)
        }
    }

    fun setNestedScrollingEnabled(enable: Boolean) {
        mListRv.isNestedScrollingEnabled = enable
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTaskChange(task: EBTask) {
        mAdapter?.run {
            if (entityList.isEmpty()) return
            if (task.isHorizontalTask) {
                if (entityList[0].noviceTasks.isNullOrEmpty()) return
                entityList[0].noviceTasks!!.safelyGetInRelease(task.position)?.status = "finished"
                horizontalTaskAdapter?.run {
                    list.safelyGetInRelease(task.position)?.status = "finished"
                    notifyItemChanged(task.position)
                }
            } else {
                entityList.safelyGetInRelease(task.position)?.dailyTask?.status = "finished"
                notifyItemChanged(task.position)
            }
        }
    }
}