package com.lukouguoji.aerologic.page.uld.edit

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.ULDBean
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 dev.DevUtils
import dev.utils.app.info.KeyValue

class UldEditViewModel : BaseViewModel() {

    var id = ""

    val pageType = MutableLiveData(DetailsPageType.Add)

    val uldBean = MutableLiveData(ULDBean())

    val statusList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("正常", "0"),
            KeyValue("故障", "1"),
        )
    )

    // 所属航司下拉列表（mock，后续替换为接口）
    val carrierList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("MU - 东方航空", "MU"),
            KeyValue("CA - 国航", "CA"),
            KeyValue("CZ - 南方航空", "CZ"),
            KeyValue("HO - 吉祥航空", "HO"),
            KeyValue("FM - 上海航空", "FM"),
        )
    )

    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.queryUldByCode(id)
        }) {
            onSuccess = {
                uldBean.value = it.data ?: ULDBean()
            }
        }
    }

    fun onSaveClick() {
        val bean = uldBean.value ?: return
        if (bean.uld.isBlank()) {
            showToast("ULD编号不能为空")
            return
        }
        val isAdd = pageType.value == DetailsPageType.Add
        launchLoadingCollect({
            if (isAdd) NetApply.api.saveUld(bean.toRequestBody())
            else NetApply.api.updateUld(bean.toRequestBody())
        }) {
            onSuccess = {
                showToast(it.msg.noNull(if (isAdd) "新增成功" else "修改成功"))
                if (isAdd) uldBean.value = ULDBean() else getData()
            }
        }
    }

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