package com.lukouguoji.aerologic.page.uld.list

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.aerologic.R
import com.lukouguoji.aerologic.page.uld.edit.UldEditActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.ULDBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.ktx.commonAdapter
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.model.ConfirmDialogModel
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.DictUtils
import dev.DevUtils
import dev.utils.app.info.KeyValue

class UldListViewModel : BasePageViewModel() {

    // 搜索条件
    val status = MutableLiveData("")
    val uldSuffix = MutableLiveData("")
    val uldNo = MutableLiveData("")

    // ========== 手机版（5.5 寸手持端）专用筛选条件 ==========
    // 平板布局无对应控件，恒为空 → 不进请求参数，平板查询行为与改造前完全一致。
    // 三个入参后端暂不支持（api-doc 已核对），已登记 documents/后端接口对接问题清单.xlsx，
    // 按「以设计为准」的约定照传（后端静默忽略无副作用），后端支持后自动生效。
    val checkInDateFilter = MutableLiveData("")   // 入库时间
    val ifNoFilter = MutableLiveData("")          // 进港航班号
    val sourceFilter = MutableLiveData("")        // 来源：空运 / 陆运

    /** 来源下拉（本地枚举，后端字段需求已登记清单） */
    val sourceList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("全部", ""),
            KeyValue("空运", "空运"),
            KeyValue("陆运", "陆运"),
        )
    )

    // ========== 手机版批量选择状态 ==========
    val isAllChecked = MutableLiveData(false)
    val selectedCount = MutableLiveData("0")

    // 状态下拉列表
    val statusList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("全部", ""),
            KeyValue("正常", "0"),
            KeyValue("故障", "1"),
        )
    )

    // 所属航司下拉列表（数据源：POST /typeCode/intCarrier）
    val carrierList = MutableLiveData<List<KeyValue>>(listOf(KeyValue("全部", "")))

    // 合计数量
    val count = MutableLiveData(0L)

    val itemLayoutId = R.layout.item_uld_list
    val itemViewHolder = UldListViewHolder::class.java

    init {
        // 加载所属航司列表（addAll=true 保留“全部”作为筛选默认项）
        DictUtils.getIntCarrierList(addAll = true) {
            carrierList.value = it
        }
    }

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getUldList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "status" to status.value?.ifEmpty { null },
                    "uldSuffix" to uldSuffix.value?.ifEmpty { null },
                    "uld" to uldNo.value?.ifEmpty { null },
                    // 手机版筛选维度（平板恒空不参与）；后端暂不支持这三个入参，已登记清单
                    "checkInDate" to checkInDateFilter.value?.ifEmpty { null },
                    "ifNo" to ifNoFilter.value?.ifEmpty { null },
                    "source" to sourceFilter.value?.ifEmpty { null },
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it.toBaseListBean()) { updateCheckAllStatus() }
                count.value = it.total
            }
        }
    }

    // ========== 手机版：多选与批量删除 ==========

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

    fun updateCheckAllStatus() {
        val list = pageModel.rv?.commonAdapter()?.items?.filterIsInstance<ULDBean>() ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
        selectedCount.value = list.count { it.checked.get() }.toString()
    }

    fun toggleSelectAll() {
        val list = pageModel.rv?.commonAdapter()?.items?.filterIsInstance<ULDBean>() ?: return
        val shouldCheckAll = !(isAllChecked.value ?: false)
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        selectedCount.value = (if (shouldCheckAll) list.size else 0).toString()
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    fun getSelectedItems(): List<ULDBean> =
        pageModel.rv?.commonAdapter()?.items?.filterIsInstance<ULDBean>()
            ?.filter { it.checked.get() } ?: emptyList()

    /**
     * 批量删除选中的 ULD。
     *
     * 后端仅有单条删除接口（/eqm/uld/deleteUld，批量接口需求已登记清单），
     * 此处按队列逐条串行调用，全部完成后统一刷新；中途失败即停并提示。
     */
    fun deleteSelected() {
        val ulds = getSelectedItems().map { it.uld }
        if (ulds.isEmpty()) {
            showToast("请选择要删除的ULD")
            return
        }
        deleteQueue(ulds, 0)
    }

    private fun deleteQueue(ulds: List<String>, index: Int) {
        if (index >= ulds.size) {
            showToast("已删除 ${ulds.size} 条")
            refresh()
            return
        }
        launchLoadingCollect({ NetApply.api.deleteUld(ulds[index]) }) {
            onSuccess = { deleteQueue(ulds, index + 1) }
            onFailed = { _, msg ->
                showToast("删除 ${ulds[index]} 失败：${msg.noNull("未知错误")}")
                refresh()
            }
        }
    }

    fun onUldScanClick() {
        ScanModel.startScan(DevUtils.getTopActivity(), Constant.RequestCode.ULD)
    }

    fun onAddClick() {
        UldEditActivity.start(DevUtils.getTopActivity())
    }

    override fun onItemClick(position: Int, type: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? ULDBean ?: return
        when (type) {
            R.id.ll_content -> UldEditActivity.start(DevUtils.getTopActivity(), bean.uld)
            R.id.tv_modify -> UldEditActivity.start(DevUtils.getTopActivity(), bean.uld, true)
            R.id.tv_delete -> deleteUld(bean.uld)
            else -> {}
        }
    }

    private fun deleteUld(uld: String) {
        ConfirmDialogModel("是否确定删除该ULD记录？") {
            launchLoadingCollect({
                NetApply.api.deleteUld(uld)
            }) {
                onSuccess = {
                    showToast("删除成功")
                    refresh()
                }
            }
        }.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.ULD -> {
                    uldNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                }
                else -> {}
            }
        }
    }
}
