package com.lukouguoji.gjc.viewModel

import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.IntExpMoveViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcMove
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
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.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.util.CheckUtil
import dev.utils.app.info.KeyValue

/**
 * 国际出港移库ViewModel
 */
class IntExpMoveViewModel : BasePageViewModel(), IOnItemClickListener {

    // ========== 搜索字段 ==========
    val awbType = MutableLiveData("")              // 运单类型
    val by1 = MutableLiveData("")                  // 承运人
    val dest1 = MutableLiveData("")                // 卸货站
    val moveState = MutableLiveData("")            // 移库状态
    val waybillNo = MutableLiveData("")            // 运单号

    // ========== 运单类型下拉数据 ==========
    val awbTypeList = MutableLiveData<List<KeyValue>>().apply {
        value = listOf(
            KeyValue("", "全部"),
            KeyValue("IOCO", "国际出港(经国内航班出境)"),
            KeyValue("IOSO", "国际出港(国际航班出境)")
        )
    }

    // ========== 移库状态下拉数据 ==========
    val moveStateList = MutableLiveData<List<KeyValue>>().apply {
        value = listOf(
            KeyValue("", "全部"),
            KeyValue("0", "未移交"),
            KeyValue("1", "已移交")
        )
    }

    // ========== 底部统计 ==========
    val totalCount = MutableLiveData("0")       // 合计票数
    val totalPieces = MutableLiveData("0")      // 总件数
    val totalWeight = MutableLiveData("0")      // 总重量

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

    // ========== 适配器配置 ==========
    val itemViewHolder = IntExpMoveViewHolder::class.java
    val itemLayoutId = R.layout.item_int_exp_move

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

    /**
     * 扫码运单号（在Activity中实现）
     */
    fun scanWaybill() {
        // 由Activity处理扫码逻辑
    }

    /**
     * 全选/取消全选
     */
    fun toggleSelectAll() {
        val adapter = pageModel.rv?.commonAdapter() ?: return
        val list = adapter.items.filterIsInstance<GjcMove>()

        // 使用CheckUtil处理全选逻辑
        CheckUtil.handleAllCheck(list)

        // 更新全选状态
        updateCheckAllStatus()

        // 刷新UI
        adapter.notifyDataSetChanged()
    }

    /**
     * 更新全选状态
     */
    fun updateCheckAllStatus() {
        val adapter = pageModel.rv?.commonAdapter() ?: return
        val list = adapter.items.filterIsInstance<GjcMove>()

        if (list.isNotEmpty()) {
            isAllChecked.value = list.all { it.checked.get() }
        } else {
            isAllChecked.value = false
        }
    }

    /**
     * 单个item选择变化时调用(从Activity接收事件)
     */
    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

    /**
     * 获取选中的运单
     */
    fun getSelectedItems(): List<GjcMove> {
        val adapter = pageModel.rv?.commonAdapter() ?: return emptyList()
        return adapter.items.filterIsInstance<GjcMove>().filter { it.checked.get() }
    }

    /**
     * 提交移库（在Activity中显示确认对话框后调用）
     */
    fun submitMove() {
        val selectedItems = getSelectedItems()

        if (selectedItems.isEmpty()) {
            showToast("请至少选择一条运单")
            return
        }

        val params = selectedItems.toRequestBody()

        launchLoadingCollect({ NetApply.api.submitIntExpMove(params) }) {
            onSuccess = {
                showToast("移库成功")
                refresh()  // 刷新列表
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("移库失败"))
            }
        }
    }

    /**
     * 获取列表数据
     */
    override fun getData() {
        // 构建筛选参数
        val filterParams = mapOf(
            "awbType" to awbType.value.noNull(),
            "by1" to by1.value.noNull(),
            "dest1" to dest1.value.noNull(),
            "moveState" to moveState.value.noNull(),
            "likeNo" to waybillNo.value.noNull()
        )

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

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

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

        // 获取统计（后台调用）
        getTotalData(totalParams)
    }

    /**
     * 获取统计数据（无Loading）
     */
    private fun getTotalData(params: okhttp3.RequestBody) {
        launchCollect({ NetApply.api.getIntExpMoveTotal(params) }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPieces.value = (data?.totalPc ?: 0L).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }
    }

    /**
     * Item点击事件处理（现已改为图标点击，此方法暂时保留兼容）
     */
    override fun onItemClick(position: Int, type: Int) {
        // 图标点击已在ViewHolder中处理，此处不再需要
    }
}
