package com.lukouguoji.gjc.viewModel

import android.app.Activity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.IntExpOutHandoverViewHolder
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.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.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ScanModel
import kotlinx.coroutines.launch

/**
 * 国际出港-出库交接 ViewModel
 */
class IntExpOutHandoverViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData("")        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val fdest = MutableLiveData("")             // 目的站
    val uldNo = MutableLiveData("")             // ULD编号

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

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

    init {
        // 监听全选状态,自动更新所有列表项
        isAllChecked.observeForever { checked ->
            val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return@observeForever
            list.forEach { it.checked.set(checked) }
            pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntExpOutHandoverViewHolder::class.java
    val itemLayoutId = R.layout.item_int_exp_out_handover

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

    /**
     * 全选按钮点击 (切换全选状态)
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return

        // 切换全选状态
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll

        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    /**
     * 扫码ULD
     */
    fun scanUld() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.ULD)
    }

    /**
     * 完成交接
     */
    fun completeHandover() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要交接的ULD")
            return
        }

        val requestData = selectedItems.toRequestBody()

        launchLoadingCollect({ NetApply.api.completeHandover(requestData) }) {
            onSuccess = {
                showToast("交接完成")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 获取数据 (重写BasePageViewModel)
     */
    override fun getData() {
        // 构建搜索条件
        val filterParams = mapOf(
            "fdate" to flightDate.value?.ifEmpty { null },
            "fno" to flightNo.value?.ifEmpty { null },
            "fdest" to fdest.value?.ifEmpty { null },
            "uld" to uldNo.value?.ifEmpty { null }
        )

        // 列表参数 (含分页)
        val listParams = (filterParams + mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit
        )).toRequestBody()

        // 统计参数 (无分页)
        val totalParams = filterParams.toRequestBody()

        // 获取列表 (带Loading)
        launchLoadingCollect({ NetApply.api.getIntExpOutHandoverList(listParams) }) {
            onSuccess = { pageModel.handleListBean(it) }
        }

        // 获取统计信息 (后台请求)
        launchCollect({ NetApply.api.getIntExpOutHandoverTotal(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()
            }
        }
    }
}
