package com.lukouguoji.gjc.viewModel

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GjcHaWb
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
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

/**
 * 国际出港运抵-补充信息 ViewModel（5.5寸手机版专属新页）
 *
 * 参照 Pad 端国际进港 [com.lukouguoji.gjj.viewModel.IntArrSupplementInfoViewModel] 的
 * 「单一表单批量复制到选中列表」模式：对该运单的整个 haWbList 批量应用同一份收发货人信息。
 *
 * ⚠️ 后端暂无保存接口，见 [com.lukouguoji.module_base.http.net.Api.supplementArriveHaWb] 注释
 * 与 documents/后端接口对接问题清单.xlsx。
 */
class IntExpArriveSupplementViewModel : BaseViewModel() {

    // 表单编辑用数据对象（取首个分单填充，让用户看到已有数据）
    val dataBean = MutableLiveData(GjcHaWb())

    // 批量应用的目标分单列表
    private var haWbList: List<GjcHaWb> = 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<GjcHaWb>
        // .copy() 补上被 Java 序列化跳过的 @Transient 字段（checked 等），见分单明细页同款注释
        haWbList = (list ?: emptyList()).map { it.copy() }
        dataBean.value = haWbList.firstOrNull()?.copy() ?: GjcHaWb()

        loadCountryCodeList()
        loadComTypeList()
    }

    private fun loadCountryCodeList() {
        launchCollect({ NetApply.api.getCountryCodeList() }) {
            onSuccess = { result ->
                countryCodeList.value = result.data?.mapNotNull { bean ->
                    if (bean.code != null && bean.name != null) KeyValue(bean.name, bean.code) else null
                } ?: emptyList()
            }
        }
    }

    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 (haWbList.isEmpty()) {
            showToast("无可保存的分单数据")
            return
        }

        val updatedList = haWbList.map { haWb ->
            haWb.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
            )
        }

        launchLoadingCollect({ NetApply.api.supplementArriveHaWb(updatedList.toRequestBody()) }) {
            onSuccess = {
                showToast("保存成功")
                getTopActivity().finish()
            }
            onFailed = { code, msg ->
                showToast("保存失败：$msg（后端接口暂未支持，见接口问题清单）")
            }
        }
    }
}
