package com.lukouguoji.gjc.viewModel

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.GjcBoxWeighingViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcUldUseBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.commonAdapter
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.model.BluetoothDialogModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.PrinterUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate

/**
 * 国际出港板箱过磅 ViewModel
 */
class GjcBoxWeighingViewModel : BasePageViewModel() {

    // 搜索条件
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())           // 航班日期
    val flightNo = MutableLiveData("")             // 航班号
    val wtStatus = MutableLiveData("")             // 过磅状态（""=全部 / "0"=未过磅 / "1"=已过磅）
    val wtStatusList = MutableLiveData(            // 过磅状态选项
        listOf(
            KeyValue("全部", ""),
            KeyValue("未过磅", "0"),
            KeyValue("已过磅", "1")
        )
    )
    val carId = MutableLiveData("")                // 架子车号
    val uld = MutableLiveData("")                  // ULD编号

    // 适配器配置
    val itemViewHolder = GjcBoxWeighingViewHolder::class.java
    val itemLayoutId = R.layout.item_gjc_box_weighing

    // 统计数据
    val totalCount = MutableLiveData("0")          // 合计票数
    val totalPc = MutableLiveData("0")
    val cargoWeight = MutableLiveData("0")// 总件数
    val totalWeight = MutableLiveData("0")         // 总重量

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

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

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

    /**
     * 搜索按钮点击
     */
    fun searchClick() {
        refresh()
    }

    /**
     * 添加按钮点击
     */
    fun addClick() {
        com.lukouguoji.gjc.activity.GjcBoxWeighingAddActivity.startForAdd(getTopActivity())
    }

    /**
     * 挂签打印按钮点击
     */
    fun printClick() {
        // 获取列表中选中的记录
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        // 校验未选择
        if (selectedItems.isEmpty()) {
            showToast("请选择要打印的数据")
            return
        }

        // 校验多选
        if (selectedItems.size > 1) {
            showToast("只能选择一条记录进行打印")
            return
        }

        // 执行打印
        val bean = selectedItems.first()
        BluetoothDialogModel().showCallBack {
            PrinterUtils.printGjcBoxWeighing(bean)
        }
    }

    /**
     * 获取列表数据
     */
    override fun getData() {
        // 构建查询参数（列表接口）
        val listParams = mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit,
            "fdate" to flightDate.value!!.ifEmpty { null },
            "fno" to flightNo.value!!.ifEmpty { null },
            "wtStatus" to wtStatus.value!!.ifEmpty { null },
            "carId" to carId.value!!.ifEmpty { null },
            "uld" to uld.value!!.ifEmpty { null },
        ).toRequestBody()

        // 构建查询参数（统计接口 - 使用相同的搜索条件）
        val totalParams = mapOf(
            "fdate" to flightDate.value!!.ifEmpty { null },
            "fno" to flightNo.value!!.ifEmpty { null },
            "wtStatus" to wtStatus.value!!.ifEmpty { null },
            "carId" to carId.value!!.ifEmpty { null },
            "uld" to uld.value!!.ifEmpty { null },
        ).toRequestBody()

        // 获取列表数据（显示loading）
        launchLoadingCollect({
            NetApply.api.getGjcBoxWeighingList(listParams)
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
            }
        }

        // 获取统计数据（后台调用，不显示loading）
        launchCollect({
            NetApply.api.getGjcBoxWeighingStatistics(totalParams)
        }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPc.value = (data?.totalPc ?: 0).toString()
                cargoWeight.value = (data?.cargoWeight ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }
    }

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