package com.hongyegroup.cpt_main.mvvm

import android.annotation.SuppressLint
import android.view.View
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
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_main.R
import com.hongyegroup.cpt_main.adapter.NotificationAdapter
import com.hongyegroup.cpt_main.bean.NotificationBean
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import javax.inject.Inject

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

    var mCurPage = 1
    var isNeedPlaceHolder = true
    var isNeedCleanAllData = true

    var mDatas = mutableListOf<NotificationBean>()
    val mAdapter by lazy { NotificationAdapter(mDatas) }

    /**
     * 获取通知列表
     */
    fun getNotificationList(): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()

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

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

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

        }

        return liveData
    }

    //处理数据-添加或刷新
    @SuppressLint("NotifyDataSetChanged")
    private fun handleData(list: List<NotificationBean>?) {
        if (!list.checkEmpty()) {
            //有数据，判断是刷新还是加载更多的数据
            if (isNeedCleanAllData) {
                //刷新的方式
                mDatas.clear()
                mDatas.addAll(list!!)
                mAdapter.notifyDataSetChanged()
            } else {
                //加载更多
                mDatas.addAll(list!!)
                mAdapter.notifyItemRangeInserted(mDatas.size - list.size, list.size)
                mAdapter.loadMoreModule.loadMoreComplete()
            }
        } else {
            //展示无数据
            if (isNeedCleanAllData && mCurPage == 1) {
                mDatas.clear()
                mAdapter.notifyDataSetChanged()
                //展示无数据的布局
                val emptyView: View = CommUtils.inflate(R.layout.item_empty_layout)
                emptyView.findViewById<TextView>(R.id.tv_empty_msg).text = "你没有任何通知"
                mAdapter.setEmptyView(emptyView)
            } else {
                //如果是加载更多,展示加载完成，没有更多数据了
                mAdapter.loadMoreModule.loadMoreEnd()
            }
        }
        isNeedPlaceHolder = false
        isNeedCleanAllData = false
    }

}