package com.framework.mvvm.mv

import androidx.lifecycle.*
import cn.sagacloud.cadengine.OkhttpUtil
import com.framework.app.pathDownloadMap
import com.framework.app.testIP
import com.framework.mvvm.model.data.AbsentLiveData
import com.framework.mvvm.model.data.Data
import com.framework.mvvm.model.db.entity.ProjectEntity
import com.framework.mvvm.model.repository.AdmRepository
import com.framework.mvvm.model.vo.AdmRequest
import com.framework.mvvm.model.vo.FloorInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json


class AdmViewModel(private val repository: AdmRepository) : ViewModel() {
    private val _frameRequest = MutableLiveData<AdmRequest>()

    private var _projects = MutableLiveData<Data<List<ProjectEntity>>>()

    val projects: LiveData<Data<List<ProjectEntity>>> =
        Transformations.switchMap(_frameRequest) { request ->
            if (request == null) {
                AbsentLiveData.create()
            } else {
                repository.getProjects(request)
            }
        }

    /**
     * 请求架构数据
     */
    fun requestFrame(request: AdmRequest) {
        viewModelScope.launch {
            repository.requestFrame(request)
        }
    }


    /**
     * 请求字典
     */
    fun requestDict(request: AdmRequest) {
        viewModelScope.launch {
            repository.requestDict(request)
        }
    }

    /**
     * 请求建筑
     */
    fun requestBuilding(request: AdmRequest) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.requestBuilding(request)
            val floors = repository.getFloors()
            floors.forEach {
                val strInfo = it.strInfos
                if (!strInfo.isNullOrEmpty()) {
                    try {
                        val info = Json.decodeFromString<FloorInfo>(strInfo)
                        val map = info.floorMap
                        val floorMap =
                            OkhttpUtil.getGzipMap("$testIP$pathDownloadMap${map!!}")
                        it.floorMap = floorMap
                        repository.upObject(it)
                    } catch (e: Exception) {
                        println("floor map Exception: $e")
                    }
                }
            }
        }
    }
}