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.formatDate
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 dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch
import java.util.Date

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

    // ========== 筛选条件 ==========
    val flightDate = MutableLiveData(Date().formatDate())  // 航班日期，默认今天
    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")             // 总重量

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

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

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

        isAllChecked.observeForever { checked ->
            val list =
                pageModel.rv?.commonAdapter()?.items as? List<GjcMaWb> ?: return@observeForever
            list.forEach { it.checked.set(checked) }
            pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        }
    }

    // ========== 适配器配置 ==========
    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 ->
            if (!bean.storageUseList.isNullOrEmpty()) {
                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 = maWbListForInStorage.toRequestBody()

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

    override fun getData() {
        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 }
        )

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