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.activity.GjcWeighingRecordListActivity
import com.lukouguoji.gjc.activity.GjcWeighingStartActivity
import com.lukouguoji.gjc.holder.GjcWeighingViewHolder
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 com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue

/**
 * 国际出港计重 ViewModel
 */
class GjcWeighingViewModel : BasePageViewModel() {

    // 搜索条件
    val flightDate = MutableLiveData("")           // 航班日期
    val flightNo = MutableLiveData("")             // 航班号
    val agentCode = MutableLiveData("")            // 代理人
    val spCode = MutableLiveData("")               // 特码
    val waybillNo = MutableLiveData("")            // 运单号

    // 下拉列表数据源
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))
    val spCodeList = MutableLiveData<List<KeyValue>>(emptyList())

    // 适配器配置
    val itemViewHolder = GjcWeighingViewHolder::class.java
    val itemLayoutId = R.layout.item_gjc_weighing

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

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

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

    /**
     * 初始化特码下拉列表（从API获取）
     */
    fun initSpecialCodeList() {
        DictUtils.getSpecialCodeList(
            flag = 1,           // 国际
            ieFlag = "",        // 空字符串
            parentcode = ""     // 无父级
        ) {
            spCodeList.value = it
        }
    }

    /**
     * 扫码输入航班号
     */
    fun flightNoScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.FLIGHT_NO)
    }

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

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

    /**
     * 添加按钮点击（跳转到开始计重页面）
     */
    fun addClick() {
        GjcWeighingStartActivity.startForAdd(getTopActivity())
    }

    /**
     * 计重记录按钮点击
     */
    fun recordClick() {
        GjcWeighingRecordListActivity.start(getTopActivity())
    }

    /**
     * 提前运抵
     */
    fun arrivedAhead() {

    }

    /**
     * 获取列表数据
     */
    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 },
            "agentCode" to agentCode.value!!.ifEmpty { null },
            "spCode" to spCode.value!!.ifEmpty { null },
            "likeNo" to waybillNo.value!!.ifEmpty { null },
        ).toRequestBody()

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

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

        // 获取统计数据（后台调用，不显示loading）
        launchCollect({
            NetApply.api.getGjcWeighingStatistics(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.FLIGHT_NO -> {
                    flightNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
                Constant.RequestCode.WAYBILL -> {
                    waybillNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }
}
