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.dialog.IntExpOutWaitingTransDialogModel
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 com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate
import kotlinx.coroutines.launch

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

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val fdest = MutableLiveData("")             // 目的站
    val uldNo = MutableLiveData("")             // ULD编号

    // ========== 手机版（5.5 寸手持端）专用筛选条件 ==========
    // 平板布局不含对应控件，两者保持空值 → 不会进入请求参数，平板查询行为与改造前完全一致
    val handoverState = MutableLiveData("")     // 交接状态："" 全部 / "0" 待交接 / "1" 已交接
    val hoId = MutableLiveData("")              // 交接人（仓管编码）

    /** 交接人下拉数据（仅手机版筛选弹层使用，由 [initPhoneExtras] 触发加载） */
    val hoUserList = MutableLiveData<List<KeyValue>>(emptyList())

    /** 手机版状态 Tab 配置 */
    val handoverStateTabs = MutableLiveData(
        listOf(KeyValue("待交接", "0"), KeyValue("已交接", "1"))
    )

    /** 手机版状态 Tab 角标（与 [handoverStateTabs] 等长） */
    val handoverStateCounts = MutableLiveData(listOf("", ""))

    /**
     * 是否启用手机版专属数据（Tab 角标计数、交接人下拉）。
     *
     * 由 Activity 在手机形态下置 true。平板端保持 false，
     * 因此不会产生任何额外接口请求，平板行为零变化。
     */
    private var phoneExtrasEnabled = false

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

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

    /** 已选数量（手机版底部操作条「已选 N 项」） */
    val selectedCount = MutableLiveData("0")

    /**
     * 开启手机版专属数据：默认停留「待交接」Tab、加载交接人下拉、启用 Tab 角标计数。
     * 仅由手机形态的 Activity 调用。
     */
    fun initPhoneExtras() {
        phoneExtrasEnabled = true
        handoverState.value = "0"
        DictUtils.getWHSUserList(addAll = false) { list ->
            hoUserList.postValue(list)
        }
    }

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

    fun updateCheckAllStatus() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
        updateSelectedCount()
    }

    /** 刷新已选数量 */
    private fun updateSelectedCount() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return
        selectedCount.value = list.count { it.checked.get() }.toString()
    }

    // ========== 适配器配置 ==========
    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
        updateSelectedCount()

        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()
            }
        }
    }

    /**
     * 待配运按钮点击
     */
    fun waitingTransClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcUldUseBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要待配运的ULD")
            return
        }

        // 显示待配运弹框
        showWaitingTransDialog(selectedItems)
    }

    /**
     * 显示待配运弹框
     */
    private fun showWaitingTransDialog(selectedItems: List<GjcUldUseBean>) {
        val dialog = IntExpOutWaitingTransDialogModel { model ->
            // 弹框确定回调
            performWaitingTrans(selectedItems, model.locationId, model.locationName)
        }
        dialog.show()
    }

    /**
     * 执行待配运操作
     */
    private fun performWaitingTrans(
        selectedItems: List<GjcUldUseBean>,
        locationId: String,
        locationName: String
    ) {
        // 构建请求参数
        val params = mapOf(
            "location" to locationName,
            "locationId" to locationId.toLongOrNull(),
            "uldUseList" to selectedItems
        ).toRequestBody()

        launchLoadingCollect({ NetApply.api.waitingTrans(params) }) {
            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 },
            // 以下两项为手机版新增筛选维度，平板端保持空值故不参与查询
            // 参数名以 api-doc 为准：交接状态为 handoverState（integer，0 未交接 / 1 已交接）。
            // hoId（交接人）后端查询入参暂不支持，已记录到 documents/后端接口对接问题清单.xlsx
            "handoverState" to handoverState.value?.ifEmpty { null },
            "hoId" to hoId.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) { updateCheckAllStatus() } }
        }

        // 获取统计信息 (后台请求)
        launchCollect({ NetApply.api.getIntExpOutHandoverTotal(totalParams) }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }

        // 手机版 Tab 角标计数（平板端不触发，无额外请求）
        if (phoneExtrasEnabled) {
            loadTabCounts(filterParams)
        }
    }

    /**
     * 加载「待交接 / 已交接」Tab 角标数量。
     *
     * 复用统计接口，分别以 handoverState=0 / 1 各查一次，且沿用当前其余筛选条件，
     * 保证角标与列表口径一致。仅手机版调用。
     */
    private fun loadTabCounts(filterParams: Map<String, Any?>) {
        listOf("0", "1").forEachIndexed { index, state ->
            val params = (filterParams + mapOf("handoverState" to state)).toRequestBody()
            launchCollect({ NetApply.api.getIntExpOutHandoverTotal(params) }) {
                onSuccess = { result ->
                    val count = (result.data?.wbNumber ?: 0).toString()
                    val current = handoverStateCounts.value?.toMutableList()
                        ?: mutableListOf("", "")
                    if (index < current.size) {
                        current[index] = count
                        handoverStateCounts.value = current
                    }
                }
            }
        }
    }
}
