package com.lukouguoji.gjj.viewModel

import android.view.View
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.FileBean
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.interfaces.IGetData
import com.lukouguoji.module_base.ktx.finish
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.util.DictUtils
import com.lukouguoji.module_base.util.MediaUtil
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils

class GjjManifestDetailsViewModel : BaseViewModel(), IGetData {

    var id = ""
    var fid = ""
    var no = ""
    var prefix = ""
    var pic = ""
    var originalPic = ""

    // 交接图片列表
    val picList = MutableLiveData<List<FileBean>>(emptyList())

    // 是否修改状态
    var modifyAble = MutableLiveData(false)

    // 运单号
    val waybillNo = MutableLiveData("")

    // 运单件数
    val waybillNum = MutableLiveData("")

    // 实到数量
    val actualNum = MutableLiveData("")

    // 实到重量
    val actualWeight = MutableLiveData("")

    // 计费重量
    val billingWeight = MutableLiveData("")

    // 始发港
    val departure = MutableLiveData("")

    // 目的港
    val destination = MutableLiveData("")

    // 品名(中)
    val goodsNameCn = MutableLiveData("")

    // 品名(英)
    val goodsNameEn = MutableLiveData("")

    // 备注
    val remark = MutableLiveData("")

    // 时间
    val date = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())


    // 业务类型 列表
    val businessTypeList = MutableLiveData<List<KeyValue>>()
    private var businessType = ""

    // 包装类型 列表
    val packageTypeList = MutableLiveData<List<KeyValue>>()
    private var packageType = ""

    // 代理列表
    val agentList = MutableLiveData<List<KeyValue>>()
    private var agent = ""

    // 特码列表
    val specialCodeList = MutableLiveData<List<KeyValue>>()
    private var specialCode = ""

    // 货物类型
    val goodsTypeList = MutableLiveData<List<KeyValue>>()
    private var goodsType = ""

    // 运单类型
    val waybillTypeList = MutableLiveData<List<KeyValue>>()
    private var waybillType = ""


    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    override fun getData() {
        parsePicList()
        showLoading()
        launchCollect({
            NetApply.api.getGjjManifestDetail(id)
        }) {
            onSuccess = { result ->
                result.data?.let { data ->
                    fid = data.fid.toString()
                    no = data.no
                    prefix = data.prefix
                    waybillNo.value = data.getWaybillCode().noNull()
                    waybillNum.value = data.awbpc.toString()
                    actualNum.value = data.pc.toString()
                    actualWeight.value = data.weight.noNull()
                    billingWeight.value = data.planweight.noNull()
                    departure.value = data.origin.noNull(data.dep.noNull())
                    destination.value = data.dest.noNull()
                    goodsNameCn.value = data.goodsCn.noNull()
                    goodsNameEn.value = data.goods.noNull()
                    remark.value = data.remark.noNull()
                    date.value = data.storageTime.noNull()

                    // 初始化下拉控件的选中值（避免 onSelected 回调时机不确定导致值丢失）
                    agent = data.agent.noNull()
                    specialCode = data.spCode.noNull()
                    businessType = data.businessType.noNull()
                    packageType = data.packagecode.noNull()
                    goodsType = data.cargoType.noNull()
                    waybillType = data.awbType.noNull()

                    DictUtils.getAgentList(addAll = false, checkedValue = data.agent) {
                        agentList.postValue(it)
                    }
                    DictUtils.getSpecialCodeList(addAll = false, flag = 1, ieFlag = "", checkedValue = data.spCode) {
                        specialCodeList.postValue(it)
                    }
                    DictUtils.getBusinessTypeList(
                        addAll = false,
                        checkedValue = data.businessType
                    ) {
                        businessTypeList.postValue(it)
                    }
                    DictUtils.getGjjPackageTypeList(addAll = false, checkedValue = data.packagecode) {
                        packageTypeList.postValue(it)
                    }
                    DictUtils.getGjjGoodsTypeList(addAll = false, checkedValue = data.cargoType) {
                        goodsTypeList.postValue(it)
                    }
                    DictUtils.getWaybillTypeList(
                        type = "II",
                        addAll = false,
                        checkedValue = data.awbType
                    ) {
                        waybillTypeList.postValue(it)
                    }
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 修改状态点击
     */
    fun onModifyClick(view: View) {
        modifyAble.value = !modifyAble.value!!
    }

    /**
     * 代理点击
     */
    fun onAgentSelected(position: Int) {
        agent = agentList.value?.get(position)?.value.noNull()
    }

    /**
     * 特码点击
     */
    fun onSpecialCodeSelected(position: Int) {
        specialCode = specialCodeList.value?.get(position)?.value.noNull()
    }

    /**
     * 包装类型点击
     */
    fun onPackageTypeSelected(position: Int) {
        packageType = packageTypeList.value?.get(position)?.value.noNull()
    }

    /**
     * 业务类型点击
     */
    fun onBusinessTypeSelected(position: Int) {
        businessType = businessTypeList.value?.get(position)?.value.noNull()
    }

    /**
     * 货物类型点击
     */
    fun onGoodsTypeSelected(position: Int) {
        goodsType = goodsTypeList.value?.get(position)?.value.noNull()
    }

    /**
     * 运单类型点击
     */
    fun onWaybillTypeSelected(position: Int) {
        waybillType = waybillTypeList.value?.get(position)?.value.noNull()
    }

    /**
     * 保存点击
     */
    fun onSaveClick(view: View) {
        if ((waybillNo.value.verifyNullOrEmpty("请输入运单号")
                    || waybillNum.value.verifyNullOrEmpty("请输入运单件数")
                    || actualNum.value.verifyNullOrEmpty("请输入实到数量")
                    || actualWeight.value.verifyNullOrEmpty("请输入实到重量"))
        ) {
            return
        }
        showLoading()
        launchCollect({
            NetApply.api.gjjManifestUpdate(
                mapOf(
                    "mfId" to id,
                    "fid" to fid,
                    "no" to no,
                    "prefix" to prefix,
                    "wbNo" to waybillNo.value,
                    "agent" to agent,
                    "spCode" to specialCode,
                    "businessType" to businessType,
                    "awbpc" to waybillNum.value,
                    "pc" to actualNum.value,
                    "weight" to actualWeight.value,
                    "planweight" to billingWeight.value,
                    "packagecode" to packageType,
                    "dep" to departure.value,
                    "origin" to departure.value,
                    "dest" to destination.value,
                    "goods" to goodsNameEn.value,
                    "goodsCn" to goodsNameCn.value,
                    "awbType" to waybillType,
                    "cargoType" to goodsType,
                    "remark" to remark.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess()) {
                    showToast("保存成功")
                    view.context.finish()
                } else {
                    showToast(it.msg.noNull("保存失败"))
                }
            }

            onComplete = {
                dismissLoading()
            }
        }
    }

    /**
     * 取消点击
     */
    fun onCancelClick(view: View) {
        modifyAble.value = false
    }

    /**
     * 解析 pic / originalPic 字符串为 FileBean 列表
     */
    fun parsePicList() {
        val thumbUrls = pic.split(",").filter { it.isNotEmpty() }
        val originalUrls = originalPic.split(",").filter { it.isNotEmpty() }
        val list = thumbUrls.mapIndexed { index, thumbFile ->
            val originalFile = originalUrls.getOrElse(index) { thumbFile }
            FileBean(
                path = MediaUtil.fillUrl(thumbFile),
                url = thumbFile,
                originalPic = MediaUtil.fillUrl(originalFile)
            )
        }
        picList.value = list
    }
}