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.dialog.GjcQueryFilterDialogModel
import com.lukouguoji.gjc.holder.GjcQueryViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
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.model.ScanModel
import dev.utils.app.info.KeyValue

/**
 * 国际出港查询ViewModel
 */
class GjcQueryViewModel : BasePageViewModel() {

    // ==================== 搜索条件 ====================
    val flightDateStart = MutableLiveData("")     // 航班日期起
    val flightDateEnd = MutableLiveData("")       // 航班日期止
    val agentId = MutableLiveData("")             // 代理ID
    val outStatus = MutableLiveData("")           // 出库状态
    val waybillNo = MutableLiveData("")           // 运单号

    // ==================== 下拉列表 ====================
    // 代理下拉列表（从API获取）
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))

    // 出库状态下拉列表
    val outStatusList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("未出库", "0"),
            KeyValue("已出库", "1")
        )
    )

    // ==================== 适配器配置 ====================
    val itemViewHolder = GjcQueryViewHolder::class.java
    val itemLayoutId = R.layout.item_gjc_query

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

    // ==================== 筛选条件（预留）====================
    val spCode = MutableLiveData("")           // 特码
    val flightNo = MutableLiveData("")         // 航班号
    val dest = MutableLiveData("")             // 目的港
    val awbType = MutableLiveData("")          // 运单类型
    val businessType = MutableLiveData("")     // 业务类型
    val goodsCn = MutableLiveData("")          // 品名（中）

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

    /**
     * 扫码输入运单号
     */
    fun waybillScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }

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

    /**
     * 筛选按钮点击
     */
    fun filterClick() {
        val filterDialog = GjcQueryFilterDialogModel(
            spCode = spCode,
            flightNo = flightNo,
            dest = dest,
            awbType = awbType,
            businessType = businessType,
            goodsCn = goodsCn,
            onConfirm = { refresh() }
        )
        filterDialog.show()
    }

    /**
     * 获取列表数据
     * 核心方法：调用API获取数据并转换PageInfo为BaseListBean
     */
    override fun getData() {
        // 构建查询参数（列表接口）
        val listParams = mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit,
            "fdateStart" to flightDateStart.value!!.ifEmpty { null },
            "fdateEnd" to flightDateEnd.value!!.ifEmpty { null },
            "agentCode" to agentId.value!!.ifEmpty { null },
            "outState" to outStatus.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            // 筛选条件（暂未使用）
            "spCode" to spCode.value!!.ifEmpty { null },
            "flightNo" to flightNo.value!!.ifEmpty { null },
            "dest" to dest.value!!.ifEmpty { null },
            "awbType" to awbType.value!!.ifEmpty { null },
            "businessType" to businessType.value!!.ifEmpty { null },
            "goodsCn" to goodsCn.value!!.ifEmpty { null }
        ).toRequestBody()

        // 构建查询参数（统计接口 - 使用相同的搜索条件）
        val totalParams = mapOf(
            "fdateStart" to flightDateStart.value!!.ifEmpty { null },
            "fdateEnd" to flightDateEnd.value!!.ifEmpty { null },
            "agentCode" to agentId.value!!.ifEmpty { null },
            "outState" to outStatus.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            // 筛选条件
            "spCode" to spCode.value!!.ifEmpty { null },
            "flightNo" to flightNo.value!!.ifEmpty { null },
            "dest" to dest.value!!.ifEmpty { null },
            "awbType" to awbType.value!!.ifEmpty { null },
            "businessType" to businessType.value!!.ifEmpty { null },
            "goodsCn" to goodsCn.value!!.ifEmpty { null }
        ).toRequestBody()

        // 获取列表数据（显示loading）
        launchLoadingCollect({
            NetApply.api.getGjcQueryList(listParams)
        }) {
            onSuccess = { pageInfo ->
                // ⚠️ 核心：使用toBaseListBean()转换PageInfo为BaseListBean
                pageModel.handleListBean(pageInfo.toBaseListBean())
            }
        }

        // 获取统计数据（后台调用，不显示loading）
        launchCollect({
            NetApply.api.getGjcQueryTotal(totalParams)
        }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPc.value = (data?.totalPc ?: 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.WAYBILL -> {
                    waybillNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }

    /**
     * 初始化代理下拉列表（从API获取）
     */
    fun initAgentList() {
        launchCollect({
            NetApply.api.getIntExpAgentList()
        }) {
            onSuccess = { result ->
                val list = mutableListOf(KeyValue("全部", ""))
                result.data?.forEach {
                    list.add(KeyValue(it.name ?: "", it.code ?: ""))
                }
                agentList.value = list
            }
        }
    }
}
