package com.lukouguoji.gnc.page.inspection

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gnc.R
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncInspectionBean
import com.lukouguoji.module_base.bean.StatisticsBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
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.noNull
import com.lukouguoji.module_base.ktx.showConfirmDialog
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.CheckUtil
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国内出港收运检查 ViewModel
 */
class GncInspectionViewModel : BasePageViewModel() {

    // 搜索条件
    val flightDate = MutableLiveData("")           // 航班日期
    val flightNo = MutableLiveData("")             // 航班号
    val agentId = MutableLiveData("")              // 代理ID
    val auditStatus = MutableLiveData("")          // 审核状态
    val waybillNo = MutableLiveData("")            // 运单号

    // 代理下拉列表（需要从API获取，暂时用空列表）
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))

    // 审核状态下拉列表
    val auditStatusList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("已通过", "1"),
            KeyValue("退回", "2"),
            KeyValue("未审核", "0"),
        )
    )

    // 适配器配置
    val itemViewHolder = GncInspectionViewHolder::class.java
    val itemLayoutId = R.layout.item_gnc_inspection

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

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

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

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

    /**
     * 获取列表数据
     */
    override fun getData() {
        val body = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "flightDate" to flightDate.value!!.ifEmpty { null },
            "flightNo" to flightNo.value!!.ifEmpty { null },
            "agentId" to agentId.value!!.ifEmpty { null },
            "auditStatus" to auditStatus.value!!.ifEmpty { null },
            "waybillNo" to waybillNo.value!!.ifEmpty { null },
        ).toRequestBody()

        launchLoadingCollect({
            NetApply.api.getGncInspectionList(body)
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
            }
        }
        getStatistics(body)
    }

    /**
     * 获取统计数据
     */
    private fun getStatistics(body: okhttp3.RequestBody) {
        launchCollect({
            NetApply.api.getGncInspectionStatistics(body)
        }) {
            onSuccess = {
                val stats = it.data ?: StatisticsBean()
                totalCount.value = stats.totalCount.noNull("0")
                totalPc.value = stats.totalPc.noNull("0")
                totalWeight.value = stats.totalWeight.noNull("0")
            }
        }
    }

    /**
     * 处理扫码结果
     */
    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()
                }
            }
        }
    }

    /**
     * 批量审核 - 通过
     */
    fun auditPassClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GncInspectionBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        getTopActivity().showConfirmDialog("确定要通过选中的 ${filter.size} 条数据吗？") {
            performAudit(filter, "1", "通过")
        }
    }

    /**
     * 批量审核 - 退回
     */
    fun auditRejectClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GncInspectionBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        getTopActivity().showConfirmDialog("确定要退回选中的 ${filter.size} 条数据吗？") {
            performAudit(filter, "2", "退回")
        }
    }

    /**
     * 执行审核操作
     */
    private fun performAudit(items: List<GncInspectionBean>, status: String, action: String) {
        launchLoadingCollect({
            NetApply.api.auditGncInspection(
                mapOf(
                    "ids" to items.map { it.id },
                    "auditStatus" to status,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                showToast(it.msg.noNull("${action}成功"))
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 全选/全不选
     */
    fun checkAllClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GncInspectionBean>
        CheckUtil.handleAllCheck(list)
    }

    /**
     * 初始化代理下拉列表（从API获取）
     */
    fun initAgentList() {
        // TODO: 调用API获取代理列表
        // 暂时使用模拟数据
        agentList.value = listOf(
            KeyValue("全部", ""),
            KeyValue("SF", "SF"),
            KeyValue("YTO", "YTO"),
            KeyValue("ZTO", "ZTO"),
        )
    }
}
