package com.sybotan.android.demo.viewmodel

import android.app.Application
import androidx.lifecycle.viewModelScope
import com.framework.mvvm.model.db.entity.task.ObjectEntity
import com.framework.mvvm.model.repository.AdmRepository
import com.sybotan.android.demo.activities.BaseActivity
import com.sybotan.android.demo.bean.ContainerParentBean
import com.sybotan.android.demo.retrofit.BaseViewModelInterface
import kotlinx.coroutines.launch
import org.kodein.di.DI
import org.kodein.di.DIAware
import org.kodein.di.android.x.closestDI
import org.kodein.di.instance


/**
 * Created by lihao.
 * Date: 2021/6/9
 */
class ContainerVM(
    app: Application,
    b: BaseViewModelInterface?, activity: BaseActivity?, //建筑id
    private val buildingId: String, //楼层id
    private val floorId: String,
    private val projectId: String
) : BaseViewModel(app, b, activity), DIAware {

    override val di: DI by closestDI()
    private val repo: AdmRepository by instance()

    fun getConfig(deviceId: String) {
        viewModelScope.launch {
            val equip = repo.getObject(deviceId)
            val configs = repo.getContainerConfig(equip!!.classCode!!)
            val parent = ArrayList<ContainerParentBean>()
            val children = ArrayList<ArrayList<ObjectEntity>>()
            val conObjs = repo.getContainerObjs(deviceId)
            for (config in configs) {
                val child = ArrayList<ObjectEntity>()
                val p = ContainerParentBean()
                p.widgetCode = config.widgetCode
                val equipment = repo.getEquipByCode(config.widgetCode)
                p.widgetName = equipment?.name
                parent.add(p)
                for (obj in conObjs) {
                    if (obj.classCode.equals(config.widgetCode)) {
                        child.add(obj)
                    }
                }
                children.add(child)
            }
            val hashMap = HashMap<String, Any>()
            hashMap.put("title", equip.localId!!)
            hashMap.put("parent", parent)
            hashMap.put("child", children)
            mEmitter.SendDirective(CONTAINER, hashMap)
        }
    }

    fun deleteObject(item: ObjectEntity, deviceId: String) {
        viewModelScope.launch {
            item.valid = 0
            if (item.state == 2) item.state = 1
            repo.insObject(item)
            getConfig(deviceId)
        }
    }

    companion object {

        //
        const val CONTAINER = "CONTAINER"

    }
}