package com.lukouguoji.gjj.dialog

import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.DialogIntImpModifyStorageBinding
import com.lukouguoji.module_base.base.BaseDialogModel
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.bean.GjcStorageUse
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.util.DeviceUtil
import dev.utils.app.info.KeyValue

/**
 * 国际进港 - 修改库位对话框
 * 手机为底部弹层（layout/ 变体），平板为居中弹框（layout-sw600dp/ 变体）。
 *
 * 平板：列表勾选唯一库位后打开，弹框内只选新库位（sourceStorageList 传 null，原库位项不存在于平板布局）。
 * 手机：卡片级操作，运单可能有多个库位——传入该运单未出库的库位列表，弹层内先单选「原库位」再选新库位。
 */
class IntImpModifyStorageDialogModel(
    private val currentLocationId: String = "",
    private val currentLocationName: String = "",
    private val sourceStorageList: List<GjcStorageUse>? = null,
    private val callback: (IntImpModifyStorageDialogModel) -> Unit
) : BaseDialogModel<DialogIntImpModifyStorageBinding>(
    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 = ""

    // ========== 手机卡片级操作专属：原库位单选 ==========
    val sourceList = MutableLiveData<List<KeyValue>>(emptyList())
    val selectedSourceId = MutableLiveData("")

    // 选中的原库位对象（保存后由调用方取用）
    var selectedSourceStorage: GjcStorageUse? = null

    override fun layoutId(): Int {
        return R.layout.dialog_int_imp_modify_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 ?: ""
        }

        // 手机版：初始化原库位列表，单库位时默认选中
        if (sourceStorageList != null) {
            sourceList.value = sourceStorageList.map {
                KeyValue(it.location ?: "", it.id?.toString() ?: "")
            }
            selectedSourceId.observeForever { id ->
                selectedSourceStorage = sourceStorageList.find { it.id?.toString() == id }
            }
            if (sourceStorageList.size == 1) {
                selectedSourceId.value = sourceStorageList[0].id?.toString() ?: ""
            }
        }
    }

    /**
     * 加载库位列表
     */
    private fun loadLocationList() {
        launchCollect({ NetApply.api.getLocationList(flag = 3) }) {
            onSuccess = { result ->
                val list = result.data?.map { it.toKeyValue() } ?: emptyList()
                locationList.value = list
                // 列表加载完成后，预选当前库位（优先按ID匹配，其次按名称匹配）
                if (currentLocationId.isNotEmpty()) {
                    selectedLocationCode.value = currentLocationId
                } else if (currentLocationName.isNotEmpty()) {
                    val matched = list.find { it.key == currentLocationName }
                    if (matched != null) {
                        selectedLocationCode.value = matched.value
                    }
                }
            }
            onFailed = { _, msg ->
                showToast(msg ?: "加载库位列表失败")
            }
        }
    }

    /**
     * 保存按钮点击
     */
    fun onSaveClick() {
        if (sourceStorageList != null && selectedSourceStorage == null) {
            showToast("请选择原库位")
            return
        }
        if (selectedLocationCode.value.verifyNullOrEmpty("请选择库位")) {
            return
        }
        dismiss()
        callback(this)
    }
}
