package com.hongyegroup.cpt_parttime.mvvm

import android.annotation.SuppressLint
import android.view.View
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_parttime.BR
import com.hongyegroup.cpt_parttime.R
import com.hongyegroup.cpt_parttime.bean.IndustryBean
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import javax.inject.Inject

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

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


    /**
     * 获取行业列表
     */
    fun getIndustryList(selectedIds: ArrayList<String>?): LiveData<Boolean> {
        val liveData = MutableLiveData<Boolean>()

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

                val list = mutableListOf<IndustryBean>()
                for (i in 1..10) {
                    list.add(IndustryBean().apply {
                        industry_id = i.toString()
                        industry_image = "http://yyjobs.sg/storage/201808/17/eVvOzW6QuxmVPiPtyjo6iSgw0AwRY08YP9fTHVfH.png"
                    })
                }
                return@withContext list
            }

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

        }

        return liveData
    }

    //处理数据-添加或刷新
    @SuppressLint("NotifyDataSetChanged")
    private fun handleData(list: List<IndustryBean>?, selectedIds: ArrayList<String>?) {
        if (!list.checkEmpty()) {

            mDatas.clear()

            //添加已经选中的标记出来
            if (!selectedIds.checkEmpty()) {
                list!!.forEach {
                    it.isSelected = selectedIds!!.contains(it.industry_id)
                    mDatas.add(it)
                }
            } else {
                mDatas.addAll(list!!)
            }

            mAdapter.notifyDataSetChanged()

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

        }

    }

}