package com.lukouguoji.gjc.viewModel

import android.app.AlertDialog
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.GjcHandoverSheetBean
import com.lukouguoji.module_base.bean.GjcMaWb
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.*
import java.util.Date

/**
 * 国际出港货物交接单 ViewModel
 */
class GjcHandoverViewModel : BaseViewModel() {

    // 运单主键ID
    var maWbId: Long = 0L

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

    // ========== 主单数据持有者 ==========
    val maWbData = MutableLiveData<GjcMaWb>(GjcMaWb())

    // ========== 计算/格式化字段 ==========
    val displayAgentName = MutableLiveData<String>()       // 托运人/交货单位/盖章单位
    val displayDeliveryDate = MutableLiveData<String>()    // 交货日期（2025年12月03日）
    val displayFlightPlan = MutableLiveData<String>()      // 计划班期（MU5555/2025-12-03/LAX）
    val displayWaybillNo = MutableLiveData<String>()       // 货单号（834-91508524）
    val displayGoods = MutableLiveData<String>()           // 品名（优先中文）
    val displayPc = MutableLiveData<String>()              // 件数
    val displayWeight = MutableLiveData<String>()          // 重量
    val displayVolume = MutableLiveData<String>()          // 体积
    val displayChargeWeight = MutableLiveData<String>()    // 计费重量
    val displayRemark = MutableLiveData<String>()          // 备注

    // ========== 跨境电商单选框 ==========
    val cbEcFlag = MutableLiveData("1")  // 默认选中"是"

    /**
     * 跨境电商RadioButton点击（已禁用，仅根据expressName自动判断）
     */
    fun onCbEcFlagClick(value: String) {
        // 不允许手动点击修改，仅根据expressName自动判断
    }

    // ========== 防止隐含危险品检查单 ==========
    val goodsNameYes = MutableLiveData(false)     // 品名为确指品名-是
    val goodsNameNo = MutableLiveData(false)      // 品名为确指品名-否
    val dangerYes = MutableLiveData(false)        // 不含危险品-是
    val dangerNo = MutableLiveData(false)         // 不含危险品-否
    val fishYes = MutableLiveData(false)          // 非观赏鱼类-是
    val fishNo = MutableLiveData(false)           // 非观赏鱼类-否
    val packagingYes = MutableLiveData(false)     // 无油渍渗漏-是
    val packagingNo = MutableLiveData(false)      // 无油渍渗漏-否
    val labelsYes = MutableLiveData(false)        // 清除标记-是
    val labelsNo = MutableLiveData(false)         // 清除标记-否

    // ========== 高风险货物检查单 ==========
    val appearanceYes = MutableLiveData(false)    // 外观异常-是
    val appearanceNo = MutableLiveData(false)     // 外观异常-否
    val threatYes = MutableLiveData(false)        // 情报威胁-是
    val threatNo = MutableLiveData(false)         // 情报威胁-否
    val highRiskYes = MutableLiveData(false)      // 高风险-是
    val highRiskNo = MutableLiveData(false)       // 高风险-否

    // ========== 跨境电商检查单 ==========
    val submitStatementYes = MutableLiveData(false)     // 提交声明-是
    val submitStatementNA = MutableLiveData(false)      // 提交声明-不适用
    val submitStatementNo = MutableLiveData(false)      // 提交声明-否

    // ========== 安检信息 ==========
    val securityChannel = MutableLiveData("")      // 安检机通道号
    val securityStartTime = MutableLiveData("")    // 开始过机时间
    val securityEndTime = MutableLiveData("")      // 结束过机时间

    /**
     * 初始化(从Intent获取参数并加载数据)
     */
    fun initOnCreated(intent: Intent) {
        maWbId = intent.getLongExtra(Constant.Key.MAWB_ID, 0L)
        if (maWbId > 0) {
            loadData()
        }
    }

    /**
     * 加载交接单数据
     */
    private fun loadData() {
        launchLoadingCollect({ NetApply.api.queryHandoverSheet(maWbId) }) {
            onSuccess = { result ->
                val response = result.data
                val maWb = response?.maWb
                val handoverSheet = response?.handoverSheet

                // 创建或更新dataBean
                val bean = (handoverSheet ?: GjcHandoverSheetBean()).apply {
                    // 如果handoverSheet为null，从maWb填充基础信息
                    if (handoverSheet == null && maWb != null) {
                        this.maWbId = maWb.maWbId
                        this.prefix = maWb.prefix
                        this.no = maWb.no
                        this.chargeWeight = maWb.weight // 使用主单重量作为计费重量
                        this.saleAgentCode = maWb.agentCode
                    }
                }

                dataBean.value = bean

                // 填充主单数据
                maWbData.value = maWb ?: GjcMaWb()

                // 计算格式化字段
                updateDisplayFields(maWb)

                // 填充CheckBox状态
                updateCheckBoxState(bean)

                // 填充安检信息
                securityChannel.value = bean.securityChannel ?: ""
                securityStartTime.value = bean.securityStartTime ?: ""
                securityEndTime.value = bean.securityEndTime ?: ""
            }
        }
    }

    /**
     * 根据Bean数据更新CheckBox状态
     */
    private fun updateCheckBoxState(bean: GjcHandoverSheetBean) {
        // 跨境电商 - 根据expressName自动判断
        // 当expressName不为null且不为空时，为"是"(1)，否则为"否"(0)
        cbEcFlag.value = if (!bean.expressName.isNullOrEmpty()) "1" else "0"

        // 防止隐含危险品检查单
        goodsNameYes.value = (bean.goodsName == "1")
        goodsNameNo.value = (bean.goodsName == "0")
        dangerYes.value = (bean.danger == "1")
        dangerNo.value = (bean.danger == "0")
        fishYes.value = (bean.fish == "1")
        fishNo.value = (bean.fish == "0")
        packagingYes.value = (bean.packaging == "1")
        packagingNo.value = (bean.packaging == "0")
        labelsYes.value = (bean.labels == "1")
        labelsNo.value = (bean.labels == "0")

        // 高风险货物检查单
        appearanceYes.value = (bean.appearance == "1")
        appearanceNo.value = (bean.appearance == "0")
        threatYes.value = (bean.threat == "1")
        threatNo.value = (bean.threat == "0")
        highRiskYes.value = (bean.highRisk == "1")
        highRiskNo.value = (bean.highRisk == "0")

        // 跨境电商检查单
        submitStatementYes.value = (bean.submitStatement == "1")
        submitStatementNA.value = (bean.submitStatement == "2")
        submitStatementNo.value = (bean.submitStatement == "0")
    }

    /**
     * CheckBox点击事件处理(防止隐含危险品)
     */
    fun onGoodsNameClick(isYes: Boolean) {
        if (isYes) {
            goodsNameYes.value = true
            goodsNameNo.value = false
        } else {
            goodsNameYes.value = false
            goodsNameNo.value = true
        }
    }

    fun onDangerClick(isYes: Boolean) {
        if (isYes) {
            dangerYes.value = true
            dangerNo.value = false
        } else {
            dangerYes.value = false
            dangerNo.value = true
        }
    }

    fun onFishClick(isYes: Boolean) {
        if (isYes) {
            fishYes.value = true
            fishNo.value = false
        } else {
            fishYes.value = false
            fishNo.value = true
        }
    }

    fun onPackagingClick(isYes: Boolean) {
        if (isYes) {
            packagingYes.value = true
            packagingNo.value = false
        } else {
            packagingYes.value = false
            packagingNo.value = true
        }
    }

    fun onLabelsClick(isYes: Boolean) {
        if (isYes) {
            labelsYes.value = true
            labelsNo.value = false
        } else {
            labelsYes.value = false
            labelsNo.value = true
        }
    }

    /**
     * CheckBox点击事件处理(高风险货物)
     */
    fun onAppearanceClick(isYes: Boolean) {
        if (isYes) {
            appearanceYes.value = true
            appearanceNo.value = false
        } else {
            appearanceYes.value = false
            appearanceNo.value = true
        }
    }

    fun onThreatClick(isYes: Boolean) {
        if (isYes) {
            threatYes.value = true
            threatNo.value = false
        } else {
            threatYes.value = false
            threatNo.value = true
        }
    }

    fun onHighRiskClick(isYes: Boolean) {
        if (isYes) {
            highRiskYes.value = true
            highRiskNo.value = false
        } else {
            highRiskYes.value = false
            highRiskNo.value = true
        }
    }

    /**
     * CheckBox点击事件处理(跨境电商)
     */
    fun onSubmitStatementClick(type: Int) {
        when (type) {
            1 -> {  // 是
                submitStatementYes.value = true
                submitStatementNA.value = false
                submitStatementNo.value = false
            }
            2 -> {  // 不适用
                submitStatementYes.value = false
                submitStatementNA.value = true
                submitStatementNo.value = false
            }
            0 -> {  // 否
                submitStatementYes.value = false
                submitStatementNA.value = false
                submitStatementNo.value = true
            }
        }
    }

    /**
     * 取消按钮点击
     */
    fun cancelClick() {
        AlertDialog.Builder(getTopActivity())
            .setTitle("提示")
            .setMessage("确定要取消吗？未保存的数据将丢失")
            .setPositiveButton("确定") { _, _ -> getTopActivity().finish() }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 保存按钮点击
     */
    fun saveClick() {
        val bean = dataBean.value ?: GjcHandoverSheetBean()

        // 更新Bean中的CheckBox字段
        bean.maWbId = maWbId
        bean.cbEcFlag = cbEcFlag.value

        // 防止隐含危险品检查单
        bean.goodsName = if (goodsNameYes.value == true) "1" else if (goodsNameNo.value == true) "0" else null
        bean.danger = if (dangerYes.value == true) "1" else if (dangerNo.value == true) "0" else null
        bean.fish = if (fishYes.value == true) "1" else if (fishNo.value == true) "0" else null
        bean.packaging = if (packagingYes.value == true) "1" else if (packagingNo.value == true) "0" else null
        bean.labels = if (labelsYes.value == true) "1" else if (labelsNo.value == true) "0" else null

        // 高风险货物检查单
        bean.appearance = if (appearanceYes.value == true) "1" else if (appearanceNo.value == true) "0" else null
        bean.threat = if (threatYes.value == true) "1" else if (threatNo.value == true) "0" else null
        bean.highRisk = if (highRiskYes.value == true) "1" else if (highRiskNo.value == true) "0" else null

        // 跨境电商检查单
        bean.submitStatement = when {
            submitStatementYes.value == true -> "1"
            submitStatementNA.value == true -> "2"
            submitStatementNo.value == true -> "0"
            else -> null
        }

        // 发送保存请求（已删除不需要的安检信息字段赋值）
        launchLoadingCollect({ NetApply.api.saveHandoverSheet(bean.toRequestBody()) }) {
            onSuccess = {
                showToast("保存成功")
                getTopActivity().finish()
            }
        }
    }

    /**
     * 更新格式化/计算字段
     */
    private fun updateDisplayFields(maWb: GjcMaWb?) {
        if (maWb == null) {
            displayAgentName.value = ""
            displayDeliveryDate.value = ""
            displayFlightPlan.value = ""
            displayWaybillNo.value = ""
            displayGoods.value = ""
            displayPc.value = "0"
            displayWeight.value = "0.0"
            displayVolume.value = "0.0"
            displayChargeWeight.value = "0.0"
            displayRemark.value = ""
            return
        }

        // 1. 托运人/交货单位/盖章单位
        displayAgentName.value = maWb.agentName ?: ""

        // 2. 交货日期格式化：Date → "2025年12月03日"
        displayDeliveryDate.value = formatDeliveryDate(maWb.opDate)

        // 3. 计划班期拼接：航班号/日期/目的地
        displayFlightPlan.value = buildFlightPlan(maWb.fno, maWb.fdate, maWb.dest)

        // 4. 货单号拼接：prefix-no
        displayWaybillNo.value = buildWaybillNo(maWb.prefix, maWb.no)

        // 5. 品名（优先中文）
        displayGoods.value = maWb.goodsCn?.ifEmpty { maWb.goods } ?: maWb.goods ?: ""

        // 6. 件数
        displayPc.value = (maWb.pc ?: 0L).toString()

        // 7. 重量
        displayWeight.value = (maWb.weight ?: 0.0).toString()

        // 8. 体积
        displayVolume.value = (maWb.volume ?: 0.0).toString()

        // 9. 计费重量
        displayChargeWeight.value = (dataBean.value?.chargeWeight ?: 0.0).toString()

        // 10. 备注
        displayRemark.value = maWb.remark ?: ""
    }

    /**
     * 格式化交货日期：String → "2025年12月03日"
     */
    private fun formatDeliveryDate(opDate: String?): String {
        if (opDate.isNullOrEmpty()) return ""
        try {
            // opDate格式: "2025-12-03 19:40:51" 或 "2025-12-03"
            val datePart = opDate.split(" ")[0]  // 取日期部分
            val parts = datePart.split("-")
            if (parts.size == 3) {
                val year = parts[0]
                val month = parts[1]
                val day = parts[2]
                return "${year}年${month}月${day}日"
            }
            return ""
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
    }

    /**
     * 构建航班计划：航班号/日期/目的地
     */
    private fun buildFlightPlan(fno: String?, fdate: Date?, dest: String?): String {
        val parts = mutableListOf<String>()

        // 航班号
        if (!fno.isNullOrEmpty()) {
            parts.add(fno)
        }

        // 日期（格式化为yyyy-MM-dd）
        if (fdate != null) {
            try {
                val calendar = java.util.Calendar.getInstance()
                calendar.time = fdate
                val year = calendar.get(java.util.Calendar.YEAR)
                val month = calendar.get(java.util.Calendar.MONTH) + 1
                val day = calendar.get(java.util.Calendar.DAY_OF_MONTH)
                parts.add(String.format("%d-%02d-%02d", year, month, day))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        // 目的地
        if (!dest.isNullOrEmpty()) {
            parts.add(dest)
        }

        return parts.joinToString("/")
    }

    /**
     * 构建货单号：prefix-no
     */
    private fun buildWaybillNo(prefix: String?, no: String?): String {
        return if (!prefix.isNullOrEmpty() && !no.isNullOrEmpty()) {
            "$prefix-$no"
        } else {
            (prefix ?: "") + (no ?: "")
        }
    }
}
