package com.lukouguoji.gjj.dialog

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.DialogIntImpInStorageBinding
import com.lukouguoji.module_base.base.BaseDialogModel
import com.lukouguoji.module_base.util.DeviceUtil
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import dev.utils.app.info.KeyValue

/**
 * 国际进港仓库 - 入库操作对话框
 */
class IntImpInStorageDialogModel(
    private val callback: (IntImpInStorageDialogModel) -> Unit
) : BaseDialogModel<DialogIntImpInStorageBinding>(
    if (DeviceUtil.isPhone()) DIALOG_TYPE_BOTTOM else DIALOG_TYPE_CENTER
) {

    // 库位列表
    val locationList = MutableLiveData<List<KeyValue>>()

    // 选中的库位（存储的是code）
    val selectedLocationCode = MutableLiveData("")

    // 库位ID (后端需要的code)
    var locationId: String = ""

    // 库位名称 (后端需要的name)
    var locationName: String = ""

    override fun layoutId(): Int {
        return R.layout.dialog_int_imp_in_storage
    }

    override fun onDialogCreated(context: Context) {
        binding.model = this
        loadLocationList()

        // 监听选择变化，更新locationId和locationName
        selectedLocationCode.observeForever { code ->
            val selectedItem = locationList.value?.find { it.value == code }
            locationId = selectedItem?.value ?: ""
            locationName = selectedItem?.key ?: ""
        }
    }

    /**
     * 加载库位列表
     */
    private fun loadLocationList() {
        launchCollect({ NetApply.api.getLocationList(flag = 3) }) {
            onSuccess = { result ->
                val list = result.data?.map { it.toKeyValue() } ?: emptyList()
                locationList.value = list
            }
            onFailed = { _, msg ->
                showToast(msg ?: "加载库位列表失败")
            }
        }
    }

    /**
     * 保存按钮点击
     */
    fun onSaveClick() {
        if (selectedLocationCode.value.verifyNullOrEmpty("请选择库位")) {
            return
        }
        dismiss()
        callback(this)
    }
}
