package com.lukouguoji.gjc.viewModel

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GjcUldUseBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.DiBangWeightModel
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.getActivity
import com.lukouguoji.module_base.ktx.launchLoadingCollect
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.model.ScanModel
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date

/**
 * 国际出港板箱过磅添加 ViewModel
 */
class GjcBoxWeighingAddViewModel : BaseViewModel() {

    // 数据Bean
    val dataBean = MutableLiveData(GjcUldUseBean())

    // 地磅集成 - 暂时注释
    // val diBangModel = DiBangWeightModel()
    val channel = MutableLiveData("")  // 通道号（用于控制地磅key）

    // 计算字段显示
    val totalWeight = MutableLiveData("0")      // 总重（红色）
    val netWeight = MutableLiveData("0")        // 装机重（蓝色）
    val cargoWeight = MutableLiveData("0")      // 货重（绿色）

    // 下拉选择数据源
    val passagewayList = MutableLiveData<List<KeyValue>>()  // 通道号列表
    val piCloseList = MutableLiveData<List<KeyValue>>()     // 探板收口列表

    // 打印挂签
    val printTag = MutableLiveData(false)

    /**
     * 初始化
     */
    fun initOnCreated(activity: Activity) {
        // 监听地磅重量变化 - 暂时注释
        // diBangModel.weight.observe(activity as LifecycleOwner) { weight ->
        //     val w = weight?.toDoubleOrNull() ?: 0.0
        //     totalWeight.value = w.toString()
        //     dataBean.value?.totalWeight = w
        //     // 实时计算装机重和货重
        //     calculateWeights()
        // }

        // 监听通道号变化，设置地磅的key - 暂时注释
        // channel.observe(activity as LifecycleOwner) {
        //     diBangModel.key = it ?: ""
        // }

        // 加载下拉列表数据
        loadPassagewayList()
        loadPiCloseList()

        // 初始化航班日期为今天
        dataBean.value?.fdate = Date().formatDate()
    }

    /**
     * 加载通道号列表
     */
    private fun loadPassagewayList() {
        DictUtils.getChannelList {
            passagewayList.value = it
        }
    }

    /**
     * 加载探板收口列表
     */
    private fun loadPiCloseList() {
        // 探板收口选项（是/否）
        piCloseList.value = listOf(
            KeyValue("1", "是"),
            KeyValue("0", "否")
        )
    }

    /**
     * 计算重量字段
     * 装机重 = 总重 - 架子车自重
     * 货重 = 装机重 - ULD自重
     */
    private fun calculateWeights() {
        val total = totalWeight.value?.toDoubleOrNull() ?: 0.0
        val carW = dataBean.value?.carWeight ?: 0.0
        val uldW = dataBean.value?.uldWeight ?: 0.0

        val net = total - carW
        val cargo = net - uldW

        netWeight.value = if (net > 0) net.toString() else "0"
        cargoWeight.value = if (cargo > 0) cargo.toString() else "0"

        dataBean.value?.netWeight = if (net > 0) net else 0.0
        dataBean.value?.cargoWeight = if (cargo > 0) cargo else 0.0
    }

    /**
     * 航班日期点击
     */
    fun flightDateClick(view: View) {
        Common.onYearMonthDay(view.context.getActivity(), dataBean.value?.fdate) { year, month, day ->
            val calendar = Calendar.getInstance()
            calendar.set(year, month - 1, day)
            val date = calendar.time.formatDate()
            dataBean.value = dataBean.value?.apply { fdate = date }
        }
    }

    /**
     * ULD编号扫码
     */
    fun uldScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.ULD)
    }

    /**
     * 架子车号扫码
     */
    fun carIdScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.CAR)
    }

    /**
     * 重置按钮点击
     */
    fun resetClick() {
        dataBean.value = GjcUldUseBean().apply {
            fdate = Date().formatDate()
        }
        totalWeight.value = "0"
        netWeight.value = "0"
        cargoWeight.value = "0"
        channel.value = ""
        printTag.value = false
    }

    /**
     * 确定按钮点击
     */
    fun confirmClick() {
        val bean = dataBean.value ?: return

        // 验证必填字段
        if (bean.carId.verifyNullOrEmpty("请输入架子车号")) return
        if (bean.uld.verifyNullOrEmpty("请输入ULD编号")) return

        // 提交数据
        val params = mapOf(
            "carId" to bean.carId,
            "passageway" to bean.passageway,
            "uld" to bean.uld,
            "dgrCode" to bean.dgrCode,
            "boardType" to bean.boardType,
            "height" to bean.height,
            "piClose" to bean.piClose,
            "piCloseSize" to bean.piCloseSize,
            "carWeight" to bean.carWeight,
            "uldWeight" to bean.uldWeight,
            "fdate" to bean.fdate,
            "fno" to bean.fno,
            "fdest" to bean.fdest,
            "remark" to bean.remark,
            "totalWeight" to bean.totalWeight,
            "netWeight" to bean.netWeight,
            "cargoWeight" to bean.cargoWeight,
            "printTag" to printTag.value
        ).toRequestBody(removeEmptyOrNull = true)

        launchLoadingCollect({
            NetApply.api.submitGjcBoxWeighing(params)
        }) {
            onSuccess = { result ->
                if (result.verifySuccess()) {
                    showToast("添加成功")
                    // 发送刷新事件
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }
                    getTopActivity().finish()
                } else {
                    showToast(result.msg.noNull("添加失败"))
                }
            }
        }
    }

    /**
     * 处理扫码结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            val content = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
            when (requestCode) {
                Constant.RequestCode.ULD -> {
                    dataBean.value = dataBean.value?.apply { uld = content }
                }
                Constant.RequestCode.CAR -> {
                    dataBean.value = dataBean.value?.apply { carId = content }
                }
            }
        }
    }

    /**
     * 清理资源
     */
    override fun onCleared() {
        super.onCleared()
        // diBangModel.cancelLooperGet()  // 暂时注释
    }
}
