package com.lukouguoji.aerologic.page.coldStorage.list

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.aerologic.R
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.ColdStorageBean
import dev.utils.app.info.KeyValue
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 ColdStorageViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val ieFlag = MutableLiveData("")             // 进出港标识
    val wbNo = MutableLiveData("")               // 运单号
    val status = MutableLiveData("")             // 货物状态
    val outUserName = MutableLiveData("")        // 出库人
    val inUserName = MutableLiveData("")         // 入库人

    // ========== 下拉列表数据源 ==========
    val ieFlagList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("全部", ""),
            KeyValue("进港", "I"),
            KeyValue("出港", "E")
        )
    )
    val statusList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("全部", ""),
            KeyValue("已入库", "已入库"),
            KeyValue("已出库", "已出库")
        )
    )

    // ========== 统计信息 ==========
    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<ColdStorageBean>
                ?: return@observeForever
            list.forEach { it.checked.set(checked) }
            pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = ColdStorageViewHolder::class.java
    val itemLayoutId = R.layout.item_cold_storage

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

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

    /**
     * 全选按钮点击
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<ColdStorageBean> ?: return
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    /**
     * 完成入库
     */
    fun completeIn() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<ColdStorageBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要入库的数据")
            return
        }

        launchLoadingCollect({ NetApply.api.coldStorageCompleteIn(selectedItems.toRequestBody()) }) {
            onSuccess = {
                showToast("入库完成")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 完成出库
     */
    fun completeOut() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<ColdStorageBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要出库的数据")
            return
        }

        launchLoadingCollect({ NetApply.api.coldStorageCompleteOut(selectedItems.toRequestBody()) }) {
            onSuccess = {
                showToast("出库完成")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 获取数据
     */
    override fun getData() {
        val filterParams = mapOf(
            "ieFlag" to ieFlag.value?.ifEmpty { null },
            "wbNo" to wbNo.value?.ifEmpty { null },
            "status" to status.value?.ifEmpty { null },
            "outUserName" to outUserName.value?.ifEmpty { null },
            "inUserName" to inUserName.value?.ifEmpty { null }
        )

        val listParams = (filterParams + mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit
        )).toRequestBody()

        val totalParams = filterParams.toRequestBody()

        // 获取列表
        launchLoadingCollect({ NetApply.api.getColdStorageList(listParams) }) {
            onSuccess = { pageModel.handleListBean(it?.toBaseListBean()) }
        }

        // 获取统计信息
        launchCollect({ NetApply.api.getColdStorageTotal(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()
            }
        }
    }
}
