package com.hongyegroup.cpt_ewallet.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.guadou.lib_baselib.utils.CommUtils
import com.hongyegroup.cpt_ewallet.BR
import com.hongyegroup.cpt_ewallet.R
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import javax.inject.Inject

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

    var mDatas = mutableListOf<String>()
    val mAdapter by lazy { BaseDataBindingAdapter(R.layout.item_withdraw_appointment, BR.item, mDatas) }
    var isNeedPlaceHolder = true

    fun getAppointmentList(): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()

        launchOnUI {
            //开始Loading
            if (isNeedPlaceHolder) loadStartLoading()
            val result = withContext(Dispatchers.IO) {
                delay(1000)

                val list = mutableListOf<String>()
                for (i in 1..2) {
                    list.add(i.toString())
                }
                return@withContext list
            }

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

        }

        return liveData
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun handleData(list: MutableList<String>) {

        if (!list.checkEmpty()) {

            mDatas.clear()
            mDatas.addAll(list)
            mAdapter.notifyDataSetChanged()

        } else {
            //展示无数据
            mDatas.clear()
            mAdapter.notifyDataSetChanged()
            //展示无数据的布局
            val emptyView = CommUtils.inflate(R.layout.item_empty_layout)
            mAdapter.setEmptyView(emptyView)
        }

        isNeedPlaceHolder = false
    }

}