package com.lukouguoji.gjj.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.IntImpStorageUseViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcMaWb
import com.lukouguoji.module_base.bean.GjcStorageUse
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.noNull
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 kotlinx.coroutines.launch

/**
 * 国际进港-仓库 ViewModel
 */
class IntImpStorageUseViewModel : BasePageViewModel() {

    // ========== 筛选条件 ==========
    val flightDate = MutableLiveData("")  // 航班日期，默认为空（可手动选择）
    val flightNo = MutableLiveData("")                 // 航班号
    val clearResult = MutableLiveData("")              // 清仓综合结果
    val clearResultList = MutableLiveData<List<KeyValue>>() // 清仓综合结果列表
    val wbNo = MutableLiveData("")                     // 运单号
    val location = MutableLiveData("")              // 库位号

    // ========== 统计信息 ==========
    val totalWbNumber = MutableLiveData("0")           // 总票数
    val totalPc = MutableLiveData("0")                 // 总件数
    val totalWeight = MutableLiveData("0")             // 总重量

    // ========== 5.5寸手机版专属 ==========
    // 搜索框统一入口（placeholder「搜索运单号/航班号」，phoneSearchClick 分流）
    val phoneSearchKey = MutableLiveData("")

    // 筛选弹层显隐
    val filterVisible = MutableLiveData(false)

    // 筛选条件（fdep 为接口入参；其余 5 项为后端未定义入参，预留传参，见接口问题清单 #25）
    val fdep = MutableLiveData("")             // 始发站
    val agentId = MutableLiveData("")          // 代理（agentCode，预留）
    val spCode = MutableLiveData("")           // 特码（预留）
    val awbType = MutableLiveData("")          // 运单类型（预留）
    val businessType = MutableLiveData("")     // 业务类型（预留）
    val goodsCn = MutableLiveData("")          // 品名(中)（预留）

    // 筛选下拉字典（initPhoneExtras 加载，平板不请求）
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))
    val specialCodeList = MutableLiveData<List<KeyValue>>(emptyList())
    val awbTypeList = MutableLiveData<List<KeyValue>>(emptyList())
    val businessTypeList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("普货", "1"),
            KeyValue("特货", "2")
        )
    )

    // 三格统计：未清仓 / 已清仓（复用 pageQueryTotal 按 clearNormal=0/1 各查一次）
    val unclearedCount = MutableLiveData("0")
    val clearedCount = MutableLiveData("0")

    private var phoneExtrasEnabled = false

    /**
     * 手机形态专属初始化（Activity 在 DeviceUtil.isPhone() 时调用）。
     * 平板端不调用，请求次数与行为零变化。
     */
    fun initPhoneExtras() {
        phoneExtrasEnabled = true
        // 代理（国际进港口径）
        DictUtils.getIntImpAgentList(addAll = false) { list ->
            agentList.postValue(listOf(KeyValue("全部", "")) + list)
        }
        // 特码：flag=1 国际；ieFlag 必须留空
        DictUtils.getSpecialCodeList(addAll = false, flag = 1, ieFlag = "") { list ->
            specialCodeList.postValue(listOf(KeyValue("全部", "")) + list)
        }
        // 运单类型（type=II 国际进港）
        DictUtils.getWaybillTypeList(type = Constant.businessType.II, addAll = true) {
            awbTypeList.postValue(it)
        }
    }

    /**
     * 手机搜索框查询：按出港计重实测规则分流——含字母→航班号，其余→运单号
     */
    fun phoneSearchClick() {
        val key = phoneSearchKey.value?.trim() ?: ""
        when {
            key.isEmpty() -> {
                wbNo.value = ""
                flightNo.value = ""
            }
            key.any { it.isLetter() } -> {
                flightNo.value = key
                wbNo.value = ""
            }
            else -> {
                wbNo.value = key
                flightNo.value = ""
            }
        }
        refresh()
    }

    /** 筛选按钮点击 - 打开筛选面板 */
    fun filterClick() {
        filterVisible.value = true
    }

    /** 关闭筛选面板 */
    fun closeFilter() {
        filterVisible.value = false
    }

    /** 重置筛选条件 */
    fun resetFilter() {
        flightDate.value = ""
        flightNo.value = ""
        fdep.value = ""
        agentId.value = ""
        spCode.value = ""
        awbType.value = ""
        businessType.value = ""
        goodsCn.value = ""
    }

    /** 确认筛选 - 关闭面板并刷新 */
    fun confirmFilter() {
        filterVisible.value = false
        refresh()
    }

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

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

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

    // ========== 全局展开状态 ==========
    val isAllExpanded = MutableLiveData(false)

    init {
        clearResultList.value = listOf(
            KeyValue("全部", ""),
            KeyValue("正常", "1"),
            KeyValue("异常", "0")
        )

    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpStorageUseViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_storage_use

    fun searchClick() {
        refresh()
    }

    /**
     * 全选按钮点击（联动勾选所有子列表项）
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcMaWb> ?: return

        val shouldCheckAll = !isAllChecked.value!!

        list.forEach { maWb ->
            maWb.checked.set(shouldCheckAll)
            maWb.storageUseList?.forEach { storageUse ->
                storageUse.checked.set(shouldCheckAll)
            }
        }

        isAllChecked.value = shouldCheckAll

        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    /**
     * 切换全局展开/收起状态
     */
    fun toggleAllExpand() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjcMaWb> ?: return

        val shouldExpand = !isAllExpanded.value!!
        isAllExpanded.value = shouldExpand

        list.forEach { bean ->
            bean.showMore.set(shouldExpand)
        }

        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    fun scanWbNo() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }

    fun clearStorage() {
        // 由Activity显示对话框
    }

    /**
     * 执行清仓操作
     */
    fun performClear(clearNormal: String, maWbListForClear: List<GjcMaWb>) {
        if (maWbListForClear.isEmpty()) {
            showToast("请至少选择一个库位")
            return
        }

        val body = maWbListForClear.toRequestBody()

        launchLoadingCollect({ NetApply.api.clearIntImpStorage(clearNormal, body) }) {
            onSuccess = {
                showToast("清仓成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("清仓失败"))
            }
        }
    }

    fun modifyStorage() {
        // 由Activity显示对话框
    }

    /**
     * 执行修改库位操作
     */
    fun performModifyStorage(
        locationName: String,
        locationId: String,
        storageUse: com.lukouguoji.module_base.bean.GjcStorageUse
    ) {
        if (locationName.isEmpty() || locationId.isEmpty()) {
            showToast("请选择库位")
            return
        }

        val updatedStorage = storageUse.copy(
            location = locationName,
            locationId = locationId.toLongOrNull() ?: 0
        )

        val params = updatedStorage.toRequestBody()

        launchLoadingCollect({ NetApply.api.modifyIntImpStorage(params) }) {
            onSuccess = {
                showToast("修改库位成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("修改库位失败"))
            }
        }
    }

    fun outStorage() {
        // 由Activity显示二次确认对话框
    }

    /**
     * 执行出库操作
     */
    fun performOutStorage(storageUseList: List<GjcStorageUse>) {
        if (storageUseList.isEmpty()) {
            showToast("请选择要出库的库位")
            return
        }

        val params = storageUseList.toRequestBody()

        launchLoadingCollect({ NetApply.api.outIntImpStorage(params) }) {
            onSuccess = {
                showToast("出库成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("出库失败"))
            }
        }
    }

    fun inStorage() {
        // 由Activity显示对话框
    }

    /**
     * 执行入库操作
     */
    fun performInStorage(
        locationName: String,
        locationId: String,
        maWbListForInStorage: List<GjcMaWb>
    ) {
        if (maWbListForInStorage.isEmpty()) {
            showToast("请至少选择一个单据")
            return
        }

        if (locationName.isEmpty() || locationId.isEmpty()) {
            showToast("请选择库位")
            return
        }

        val body = mapOf(
            "location" to locationName,
            "locationId" to locationId.toLongOrNull(),
            "warehouseList" to maWbListForInStorage
        ).toRequestBody()

        launchLoadingCollect({ NetApply.api.inIntImpStorage(body) }) {
            onSuccess = {
                showToast("入库成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("入库失败"))
            }
        }
    }

    override fun getData() {
        // 手机专属 6 项平板恒为空，不进请求；agentCode/spCode/awbType/businessType/goodsCn
        // 为 pageQuery 未定义入参（后端静默忽略，补齐后自动生效，见接口问题清单 #25）
        val filterParams = mapOf(
            "fdate" to flightDate.value?.ifEmpty { null },
            "fno" to flightNo.value?.ifEmpty { null },
            "wbNo" to wbNo.value?.ifEmpty { null },
            "location" to location.value?.ifEmpty { null },
            "clearNormal" to clearResult.value?.ifEmpty { null },
            "fdep" to fdep.value?.ifEmpty { null },
            "agentCode" to agentId.value?.ifEmpty { null },
            "spCode" to spCode.value?.ifEmpty { null },
            "awbType" to awbType.value?.ifEmpty { null },
            "businessType" to businessType.value?.ifEmpty { null },
            "goodsCn" to goodsCn.value?.ifEmpty { null }
        )

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

        val totalParams = filterParams.toRequestBody()

        launchLoadingCollect({ NetApply.api.getIntImpStorageUseList(listParams) }) {
            onSuccess = { result ->
                pageModel.handleDataList(result.list) { updateCheckAllStatus() }
                pageModel.haveMore.postValue((result.pages) > pageModel.page)
                isAllExpanded.value = false
            }
        }

        launchCollect({ NetApply.api.getIntImpStorageUseTotal(totalParams) }) {
            onSuccess = { result ->
                val data = result.data
                totalWbNumber.value = (data?.wbNumber ?: 0).toString()
                totalPc.value = (data?.totalPc ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }

        // 手机专属：未清仓/已清仓分项统计（同条件 + clearNormal=0/1 各查一次，平板不发）
        if (phoneExtrasEnabled) {
            val unclearedParams = (filterParams + mapOf("clearNormal" to "0")).toRequestBody()
            launchCollect({ NetApply.api.getIntImpStorageUseTotal(unclearedParams) }) {
                onSuccess = { unclearedCount.value = (it.data?.wbNumber ?: 0).toString() }
            }
            val clearedParams = (filterParams + mapOf("clearNormal" to "1")).toRequestBody()
            launchCollect({ NetApply.api.getIntImpStorageUseTotal(clearedParams) }) {
                onSuccess = { clearedCount.value = (it.data?.wbNumber ?: 0).toString() }
            }
        }
    }
}
