package com.lukouguoji.aerologic.page.car.add

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.CarBean
import com.lukouguoji.module_base.bean.FlatcarBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.DetailsPageType
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.util.DictUtils
import dev.DevUtils
import dev.utils.app.info.KeyValue

class CarDetailsViewModel : BaseViewModel() {

    var id = ""

    val pageType = MutableLiveData(DetailsPageType.Add)

    val carBean = MutableLiveData(FlatcarBean())

    // 位置列表
    val locationList = MutableLiveData(listOf(KeyValue("占位", ""))).apply {
        DictUtils.getCarLocationList {
            value = listOf(KeyValue("", "")) + it
        }
    }

    // 状态列表
    val statusList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("正常", "0"),
            KeyValue("故障", "1"),
        )
    )

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    fun initOnCreate(intent: Intent) {
        id = intent.getStringExtra(Constant.Key.ID) ?: ""
        val modify = intent.getBooleanExtra(Constant.Key.DATA, false)
        pageType.value = if (id.isEmpty()) DetailsPageType.Add
        else if (modify) DetailsPageType.Modify else DetailsPageType.Details

        getData()

    }

    private fun getData() {
        if (id.isEmpty()) {
            return
        }
        launchLoadingCollect({
            NetApply.api.getCarDetails(id)
        }) {
            onSuccess = {
                carBean.value = it.data ?: FlatcarBean()
                carBean.value?.positionName =
                    locationList.value?.find { b -> b.value == carBean.value?.position }?.key ?: ""
            }
        }
    }

    fun onSaveClick() {
        launchLoadingCollect({
            NetApply.api.anyPost(
                url = if (pageType.value == DetailsPageType.Add) "eqm/flatcar/insertFlatcar" else "eqm/flatcar/updateFlatcar",
                body = carBean.value!!.toRequestBody()
            )
        }) {
            onSuccess = {
                showToast(it.msg.noNull("${pageType.value!!.title}成功"))
                if (id.isNotEmpty()) {
                    getData()
                } else {
                    carBean.value = FlatcarBean()
                }
            }
        }
    }

    fun onCancelClick() {
        DevUtils.getTopActivity().finish()
    }

}