package com.lukouguoji.gjj.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GjjImportManifest
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国际进港补充信息 ViewModel
 */
class IntArrSupplementInfoViewModel : BaseViewModel() {

    // 表单编辑用数据对象
    val dataBean = MutableLiveData<GjjImportManifest>()

    // 所有选中的 manifest 列表（用于批量保存）
    private var manifestList: List<GjjImportManifest> = emptyList()

    // 国家代码下拉列表
    val countryCodeList = MutableLiveData<List<KeyValue>>(emptyList())

    // 通讯方式下拉列表
    val comTypeList = MutableLiveData<List<KeyValue>>(emptyList())

    /**
     * 初始化数据
     */
    @Suppress("UNCHECKED_CAST")
    fun initOnCreated(intent: Intent) {
        val list = intent.getSerializableExtra(Constant.Key.DATA) as? ArrayList<GjjImportManifest>
        if (!list.isNullOrEmpty()) {
            manifestList = list
            // 取首个填充表单，让用户看到已有数据
            dataBean.value = list.first().copy()
        } else {
            dataBean.value = GjjImportManifest()
        }

        // 加载下拉列表
        loadCountryCodeList()
        loadComTypeList()
    }

    /**
     * 加载国家代码下拉列表
     */
    private fun loadCountryCodeList() {
        launchCollect({ NetApply.api.getCountryCodeList() }) {
            onSuccess = { result ->
                val keyValueList = result.data?.mapNotNull { bean ->
                    if (bean.code != null && bean.name != null) {
                        KeyValue(bean.name, bean.code)
                    } else null
                } ?: emptyList()
                countryCodeList.value = keyValueList

                // 全量加载完成后，按始发站过滤查询，若唯一则自动选中
                autoMatchCountryCodeByFdep()
            }
        }
    }

    /**
     * 根据始发站/目的站自动匹配国家代码
     * - 始发站(fdep) → 匹配发货人国家代码
     * - 目的站(fdest) → 匹配收货人国家代码
     */
    private fun autoMatchCountryCodeByFdep() {
        val manifest = manifestList.firstOrNull() ?: return
        val bean = dataBean.value ?: return

        // 始发站 → 发货人国家代码
        if (manifest.fdep.isNotEmpty() && bean.consignorCountryCode.isEmpty()) {
            launchCollect({ NetApply.api.getCountryCodeListByFdep(manifest.fdep) }) {
                onSuccess = { result ->
                    val filtered = result.data?.mapNotNull { dictBean ->
                        if (dictBean.code != null && dictBean.name != null) KeyValue(dictBean.name, dictBean.code) else null
                    } ?: emptyList()
                    if (filtered.size == 1) {
                        dataBean.value?.let { current ->
                            dataBean.value = current.copy(consignorCountryCode = filtered.first().value)
                        }
                    }
                }
            }
        }

        // 目的站 → 收货人国家代码
        if (manifest.fdest.isNotEmpty() && bean.consigneeCountryCode.isEmpty()) {
            launchCollect({ NetApply.api.getCountryCodeListByFdep(manifest.fdest) }) {
                onSuccess = { result ->
                    val filtered = result.data?.mapNotNull { dictBean ->
                        if (dictBean.code != null && dictBean.name != null) KeyValue(dictBean.name, dictBean.code) else null
                    } ?: emptyList()
                    if (filtered.size == 1) {
                        dataBean.value?.let { current ->
                            dataBean.value = current.copy(consigneeCountryCode = filtered.first().value)
                        }
                    }
                }
            }
        }
    }

    /**
     * 加载通讯方式下拉列表
     */
    private fun loadComTypeList() {
        launchCollect({ NetApply.api.getCommunicateTypeList() }) {
            onSuccess = { result ->
                comTypeList.value = result.data?.mapNotNull { bean ->
                    if (bean.code != null && bean.name != null) {
                        KeyValue(bean.name, bean.code)
                    } else null
                } ?: emptyList()
            }
        }
    }

    /**
     * 取消按钮点击
     */
    fun cancel() {
        getTopActivity().finish()
    }

    /**
     * 保存按钮点击 - 将表单信息复制到所有选中项，批量提交
     */
    fun save() {
        val formBean = dataBean.value ?: return

        // 收货人必填校验
        if (formBean.consigneeName.verifyNullOrEmpty("收货人名称不能为空")) return
        if (formBean.consigneeCountryCode.verifyNullOrEmpty("收货人国家代码不能为空")) return
        if (formBean.consigneeComType.verifyNullOrEmpty("收货人通讯方式不能为空")) return
        if (formBean.consigneePNum.verifyNullOrEmpty("收货人联系号码不能为空")) return
        // 发货人必填校验
        if (formBean.consignorName.verifyNullOrEmpty("发货人名称不能为空")) return
        if (formBean.consignorCountryCode.verifyNullOrEmpty("发货人国家代码不能为空")) return
        if (formBean.consignorComType.verifyNullOrEmpty("发货人通讯方式不能为空")) return
        if (formBean.consignorPNum.verifyNullOrEmpty("发货人联系号码不能为空")) return

        if (manifestList.isEmpty()) {
            showToast("无可保存的数据")
            return
        }

        // 将表单中的收发货人+危险品字段复制到每个 manifest
        val updatedList = manifestList.map { manifest ->
            manifest.copy(
                // 收货人信息
                consigneeName = formBean.consigneeName,
                consigneeCountryCode = formBean.consigneeCountryCode,
                consigneeComType = formBean.consigneeComType,
                consigneePNum = formBean.consigneePNum,
                consigneeAddress = formBean.consigneeAddress,
                // 发货人信息
                consignorName = formBean.consignorName,
                consignorCountryCode = formBean.consignorCountryCode,
                consignorComType = formBean.consignorComType,
                consignorPNum = formBean.consignorPNum,
                consignorAddress = formBean.consignorAddress,
                // 危险品信息
                dgrContactName = formBean.dgrContactName,
                dgrContactNumber = formBean.dgrContactNumber,
                unNumber = formBean.unNumber
            )
        }

        // 拼装成数组提交
        launchLoadingCollect({
            NetApply.api.completeIntArrManifest(updatedList.toRequestBody())
        }) {
            onSuccess = {
                showToast("保存成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                getTopActivity().finish()
            }
        }
    }
}
