package com.lukouguoji.gjc.viewModel

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.dialog.GjcInspectionRejectDialogModel
import com.lukouguoji.gjc.holder.GjcInspectionViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcInspectionBean
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.formatDate
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 dev.utils.common.DateUtils
import kotlinx.coroutines.launch
import java.util.Date

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

    // 搜索条件
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())           // 航班日期
    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("退回", "3"),
        )
    )

    // 适配器配置
    val itemViewHolder = GjcInspectionViewHolder::class.java
    val itemLayoutId = R.layout.item_gjc_inspection

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

    // 全选状态
    val isAllChecked = MutableLiveData(false)

    init {
        // 设置航班日期默认值为当前日期
//        flightDate.value = Date().formatDate()
    }

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

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

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

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

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

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

        // 获取统计数据（后台调用，不显示loading）
        launchCollect({
            NetApply.api.getGjcInspectionTotal(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()
                }
            }
        }
    }

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

    /**
     * 批量审核 - 退回
     */
    fun auditRejectClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GjcInspectionBean>
        val filter = list.filter { it.checked.get() }

        // 验证是否选择了数据
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }

        // 验证只能选择一个单据
        if (filter.size > 1) {
            showToast("退回时只能选择一个单据")
            return
        }

        // 弹出退回原因对话框
        val dialog = GjcInspectionRejectDialogModel { reason ->
            // 用户填写完退回原因后，执行退回操作
            performAudit(filter, false, "退回", reason)
        }
        dialog.show()
    }

    /**
     * 执行审核操作
     * @param items 选中的数据列表
     * @param isPass true:通过, false:退回
     * @param action 操作名称（用于提示）
     * @param reason 退回原因（仅退回时使用）
     */
    private fun performAudit(items: List<GjcInspectionBean>, isPass: Boolean, action: String, reason: String) {
        // 构建请求参数：数组对象，包含 maWbId、wbNo、prefix、no、reviewStatus（必传）
        // 使用数据自身的 reviewStatus 值
        val requestData = items.map {
            mapOf(
                "maWbId" to it.maWbId,
                "wbNo" to it.wbNo,
                "prefix" to it.prefix,
                "no" to it.no,
                "reviewStatus" to it.reviewStatus
            )
        }.toRequestBody()

        // 根据审核状态调用不同接口
        launchLoadingCollect({
            if (isPass) {
                NetApply.api.passGjcInspection("", requestData)
            } else {
                NetApply.api.backGjcInspection(reason, requestData)
            }
        }) {
            onSuccess = {
                showToast("${action}成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

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

    /**
     * 更新全选状态
     */
    fun updateCheckAllStatus() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcInspectionBean>
        if (list != null && list.isNotEmpty()) {
            isAllChecked.value = list.all { it.checked.get() }
        } else {
            isAllChecked.value = false
        }
    }

    /**
     * 单个item点击事件（用于更新全选状态）
     */
    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

    /**
     * 初始化代理下拉列表（从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
            }
        }
    }
}
