package com.sybotan.android.demo.viewmodel

import android.app.Activity.RESULT_OK
import android.app.Application
import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import cn.sagacloud.android.cadengine.types.*
import com.framework.mvvm.model.db.entity.*
import com.framework.mvvm.model.db.entity.task.Infos
import com.framework.mvvm.model.db.entity.task.Options
import com.framework.mvvm.model.repository.AdmRepository
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.sybotan.android.demo.activities.BaseActivity
import com.sybotan.android.demo.retrofit.BaseViewModelInterface
import com.sybotan.android.demo.tools.CommonUtils
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
import kotlin.collections.HashMap


/**
 * Created by lihao.
 * Date: 2021/6/9
 * 空间详情
 */
class SpaceDetailVM(
    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 {
    private val gson = Gson()

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

    /**
     * SPACE_INFO 静态信息点配置
     * SPACE_INFOS 对象静态信息的值
     */
    fun getInfosConfig(spaceId: String) {
        viewModelScope.launch {
            val infosConfig = repo.getInfosConfigByObjType("space")
            val infoList = gson.fromJson<List<Infos>>(
                infosConfig[0].infos,
                object : TypeToken<List<Infos?>?>() {}.type
            )
            mergeInfo(infoList)
            val spaceObject = repo.getObject(spaceId)
            val infos = gson.fromJson(spaceObject!!.infos, HashMap::class.java)
            mEmitter.SendDirective(SPACE_INFOS, infos)
            mEmitter.SendDirective(SPACE_INFO, infoList)
        }
    }

    private suspend fun mergeInfo(infoList: List<Infos>) {
        for (info in infoList) {
            val infoEntity = repo.getInfoByClassCodeAndCode("GeneralZone", "space", info.code)
            if (infoEntity != null) {
                info.dataType =
                    if (TextUtils.isEmpty(infoEntity?.dataType)) "" else infoEntity?.dataType!!
                info.unit = if (TextUtils.isEmpty(infoEntity?.unit)) "" else infoEntity?.unit!!
                if (infoEntity!!.dataSource != null) {
                    info.options = gson.fromJson(
                        infoEntity.dataSource,
                        object : TypeToken<List<Options?>?>() {}.type
                    )
                }
                if (TextUtils.isEmpty(info.inputType)) {
                    when {
                        info.code.equals("digitalDeliveryID") -> {
                            info.inputType = "digitalDeliveryID"
                        }
                        info.dataType.equals("BOOLEAN") -> {
                            if (CommonUtils.IsNull(info.options)) {
                                info.options = ArrayList()
                                info.options.add(Options("off", "否"))
                                info.options.add(Options("on", "是"))
                            }
                        }
                        info.dataType.equals("ATTACHMENT") -> {
                            info.inputType = "photo"
                        }
                        info.dataType.equals("DATETIME") -> {
                            info.inputType = "date"
                        }
                        info.dataType.equals("DOUBLE") -> {
                            info.inputType = "double"
                        }
                        info.dataType.equals("INTEGER") -> {
                            info.inputType = "text"
                        }
                        else -> {
                            info.inputType = "text"
                        }
                    }
                    if (!CommonUtils.IsNull(info.options)) {
                        info.inputType = "radio"
                    }

                }
            }
        }
    }

    /**
     * 更新空间信息点值
     */
    fun refreshObject(space: TunableSpace, hashMap: HashMap<String, Any>) {
        viewModelScope.launch {
            val spaceObj = repo.getObject(space.id!!)
            spaceObj!!.infos = gson.toJsonTree(hashMap)
            if (hashMap!!["localId"] != null && !TextUtils.isEmpty(hashMap["localId"].toString())) {
                spaceObj.localId = hashMap["localId"].toString()
            }
            if (hashMap!!["localName"] != null && !TextUtils.isEmpty(hashMap["localName"].toString())) {
                spaceObj.localName = hashMap["localName"].toString()
            }
            spaceObj.state()
            repo.insObject(spaceObj)
            mActivity.setResult(RESULT_OK)
            mActivity.finish()
        }
    }

    fun getSpace(spaceId: String) {
        viewModelScope.launch {
            val spaceObj = repo.getObject(spaceId)
            mEmitter.SendDirective(SPACE_OBJECT, spaceObj)
        }
    }


    companion object {
        //静态信息点配置
        const val SPACE_INFO = "SPACE_INFO"

        //对象静态信息点值
        const val SPACE_INFOS = "SPACE_INFOS"

        //空间实例
        const val SPACE_OBJECT = "SPACE_OBJECT"
    }

}