package com.hongyegroup.cpt_parttime.mvvm

import android.annotation.SuppressLint
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.guadou.cs_cptservices.binding.BaseDataBindingAdapter
import com.guadou.lib_baselib.base.vm.BaseViewModel
import com.guadou.lib_baselib.ext.checkEmpty
import com.hongyegroup.cpt_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.bean.PartJobResult
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class PartJobDetailSlotsViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle
) : BaseViewModel() {

    var mDatas = mutableListOf<PartJobResult>()
    val mAdapter by lazy { BaseDataBindingAdapter(R.layout.item_part_job_slots, BR.item, mDatas) }

    /**
     * 获取其他的工作
     */
    fun requestJobSlots(): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()

        launchOnUI {
            loadStartLoading()
            val result = withContext(Dispatchers.IO) {
                delay(1000)

                val list = mutableListOf<PartJobResult>()
                for (i in 1..10) {
                    list.add(PartJobResult().apply {
                        type = 1
                    })
                }
                return@withContext list
            }

            loadSuccess()
            handleData(result)
            liveData.postValue(true)

        }

        return liveData
    }


    //处理数据-添加或刷新
    @SuppressLint("NotifyDataSetChanged")
    private fun handleData(list: List<PartJobResult>?) {
        if (!list.checkEmpty()) {
            mDatas.clear()
            mDatas.addAll(list!!)
            mAdapter.notifyDataSetChanged()
        } else {
            //展示无数据
            mDatas.clear()
            mAdapter.notifyDataSetChanged()
        }
    }

}