package com.lukouguoji.gjc.viewModel

import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.AssembleInfoViewHolder
import com.lukouguoji.gjc.holder.AssemblePositionViewHolder
import com.lukouguoji.gjc.holder.AssembleWaybillViewHolder
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.*
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.model.ScanModel

/**
 * 国际出港-开始组装ViewModel（静态数据）
 */
class IntExpAssembleStartViewModel : BaseViewModel() {

    // ========== 搜索条件 ==========
    val searchText = MutableLiveData("")

    // ========== 左侧组装信息列表 ==========
    val assembleInfoList = MutableLiveData<MutableList<AssembleInfoBean>>()
    val assembleInfoLayoutId = R.layout.item_assemble_info
    val assembleInfoViewHolder = AssembleInfoViewHolder::class.java

    // ========== 左侧组装位置列表 ==========
    val assemblePositionList = MutableLiveData<MutableList<AssemblePositionBean>>()
    val assemblePositionLayoutId = R.layout.item_assemble_position
    val assemblePositionViewHolder = AssemblePositionViewHolder::class.java

    // ========== 选中的组装位置 ==========
    val selectedPosition = MutableLiveData<AssemblePositionBean?>()

    // ========== 右侧运单列表 ==========
    val waybillList = MutableLiveData<MutableList<AssembleWaybillBean>>()
    val waybillLayoutId = R.layout.item_assemble_waybill
    val waybillViewHolder = AssembleWaybillViewHolder::class.java

    // ========== ULD信息 ==========
    val uldInfo = MutableLiveData(UldInfoBean())

    // ========== 运单信息 ==========
    val waybillInfo = MutableLiveData(WaybillInfoBean())

    /**
     * 初始化模拟数据（已废弃）
     */
    fun initMockData() {
        // 不再加载mock数据
    }

    /**
     * 加载组装位置列表
     */
    fun loadAssemblePosition() {
        launchLoadingCollect({ NetApply.api.getDictListByLocation("GJCLOAD") }) {
            onSuccess = { result ->
                val list = result.data?.mapIndexed { index, dictBean ->
                    AssemblePositionBean().apply {
                        positionName = dictBean.name
                        isSelected = (index == 0)  // 默认选中第一项
                    }
                }?.toMutableList() ?: mutableListOf()

                assemblePositionList.value = list

                // 保存默认选中的第一项
                if (list.isNotEmpty()) {
                    selectedPosition.value = list[0]
                }
            }
        }
    }

    /**
     * 组装位置点击（单选切换）
     */
    fun onPositionItemClick(position: Int) {
        val list = assemblePositionList.value ?: return

        // 取消所有选中状态
        list.forEach { it.isSelected = false }

        // 选中当前项
        if (position in list.indices) {
            list[position].isSelected = true
            selectedPosition.value = list[position]
        }

        // 刷新列表
        assemblePositionList.value = list
    }

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

    /**
     * 加载待组装运单列表
     */
    fun loadWaitingAssembleWaybills() {
        val wbNo = searchText.value?.trim() ?: ""

        // 验证运单号不能为空
        if (wbNo.isEmpty()) {
            showToast("请输入运单号")
            return
        }

        // 发起网络请求
        launchLoadingCollect({ NetApply.api.queryWaitingAssemble(wbNo) }) {
            onSuccess = { result ->
                // 数据转换: GjcWarehouse -> AssembleWaybillBean
                val warehouseList = result.data ?: mutableListOf()
                val waybillBeanList = warehouseList.map { warehouse ->
                    AssembleWaybillBean().apply {
                        waybillNo = warehouse.no
                        pieces = warehouse.pc.toString()
                        weight = String.format("%.1f", warehouse.weight)
                        flight = warehouse.flight
                        isMarked = false
                    }
                }.toMutableList()

                // 更新列表
                waybillList.value = waybillBeanList

                // 结果反馈
                if (waybillBeanList.isEmpty()) {
                    showToast("未找到待组装运单")
                } else {
                    showToast("查询成功，共${waybillBeanList.size}条记录")
                }
            }
            onFailed = { code, message ->
                showToast("查询失败: $message")
                waybillList.value = mutableListOf()
            }
        }
    }

    /**
     * 初始化加载待组装运单列表（页面打开时调用）
     */
    fun loadInitialWaitingAssemble() {
        launchLoadingCollect({ NetApply.api.queryWaitingAssemble("") }) {
            onSuccess = { result ->
                val warehouseList = result.data ?: mutableListOf()
                val waybillBeanList = warehouseList.map { warehouse ->
                    AssembleWaybillBean().apply {
                        waybillNo = warehouse.no
                        pieces = warehouse.pc.toString()
                        weight = String.format("%.1f", warehouse.weight)
                        flight = warehouse.flight
                        isMarked = false
                    }
                }.toMutableList()

                waybillList.value = waybillBeanList

                if (waybillBeanList.isEmpty()) {
                    showToast("暂无待组装运单")
                }
            }
            onFailed = { code, message ->
                showToast("加载失败: $message")
                waybillList.value = mutableListOf()
            }
        }
    }


    /**
     * 卸货按钮点击
     */
    fun onUnloadClick() {
        showToast("卸货操作（静态页面暂不实现）")
    }

    /**
     * 装货按钮点击
     */
    fun onLoadClick() {
        showToast("装货操作（静态页面暂不实现）")
    }
}
