package com.lukouguoji.gjj.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.dialog.IntImpTallyDeleteDialogModel
import com.lukouguoji.gjj.dialog.IntImpTallyResetDialogModel
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.gjj.holder.IntImpTallyViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjDeclareParam
import com.lukouguoji.module_base.bean.GjjImportTally
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 kotlinx.coroutines.launch

/**
 * 国际进港理货报告 ViewModel
 */
class IntImpTallyViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val waybillNo = MutableLiveData("")         // 运单号
    val hno = MutableLiveData("")               // 分单号

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

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

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

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

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpTallyViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_tally

    /**
     * 搜索按钮点击
     */
    fun searchClick() {
        refresh()
    }

    /**
     * 全选按钮点击（切换全选状态）
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjImportTally> ?: return

        // 切换全选状态（联动子列表）
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach {
            it.checked.set(shouldCheckAll)
            it.haWbList?.forEach { sub -> sub.checked.set(shouldCheckAll) }
        }
        isAllChecked.value = shouldCheckAll

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

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

    /**
     * 扫码分单号
     */
    fun scanHno() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.HNO)
    }

    /**
     * 收集选中的主单和分单
     */
    private fun getSelectedData(): Pair<List<GjjImportTally>, List<GjjImportTally>> {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjImportTally>
            ?: return Pair(emptyList(), emptyList())
        val selectedMaWb = list.filter { it.isSelected }
        val selectedHaWb = mutableListOf<GjjImportTally>()
        list.forEach { maWb ->
            maWb.haWbList?.forEach { haWb ->
                if (haWb.isSelected) selectedHaWb.add(haWb)
            }
        }
        return Pair(selectedMaWb, selectedHaWb)
    }

    /**
     * 人工放行
     */
    fun manualReleaseClick() {
        val (selectedMaWb, selectedHaWb) = getSelectedData()

        if (selectedMaWb.isEmpty() && selectedHaWb.isEmpty()) {
            showToast("请选择要放行的记录")
            return
        }

        val param = GjjDeclareParam(
            mtallyList = if (selectedMaWb.isNotEmpty()) selectedMaWb else null,
            htallyList = if (selectedHaWb.isNotEmpty()) selectedHaWb else null
        )

        launchLoadingCollect({ NetApply.api.intImpTallyCustomCommand(param.toRequestBody()) }) {
            onSuccess = {
                showToast("人工放行成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 状态重置
     */
    fun statusResetClick() {
        val (selectedMaWb, selectedHaWb) = getSelectedData()

        if (selectedMaWb.isEmpty() && selectedHaWb.isEmpty()) {
            showToast("请选择要重置的记录")
            return
        }

        val dialog = IntImpTallyResetDialogModel { dialogModel ->
            val param = GjjDeclareParam(
                mtallyList = if (selectedMaWb.isNotEmpty()) selectedMaWb else null,
                htallyList = if (selectedHaWb.isNotEmpty()) selectedHaWb else null,
                restStatus = dialogModel.resetStatusCode
            )

            launchLoadingCollect({ NetApply.api.intImpTallyResetDeclare(param.toRequestBody()) }) {
                onSuccess = {
                    showToast("状态重置成功")
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }
                    refresh()
                }
            }
        }

        dialog.show()
    }

    /**
     * 删除理货
     */
    fun deleteTallyClick() {
        val (selectedMaWb, selectedHaWb) = getSelectedData()

        if (selectedMaWb.isEmpty() && selectedHaWb.isEmpty()) {
            showToast("请选择要删除的记录")
            return
        }

        // 校验所选单据状态是否为 01（已申报）
        val invalidMaWb = selectedMaWb.firstOrNull { it.status != "01" }
        if (invalidMaWb != null) {
            showToast("运单 ${invalidMaWb.getWaybillNo()} 理货未申报，不允许删除理货")
            return
        }
        val invalidHaWb = selectedHaWb.firstOrNull { it.status != "01" }
        if (invalidHaWb != null) {
            showToast("运单 ${invalidHaWb.getWaybillNo()} 理货未申报，不允许删除理货")
            return
        }

        // 从接口获取删除原因列表
        launchLoadingCollect({ NetApply.api.getDelReasonList() }) {
            onSuccess = { result ->
                val changeReasonList = result.data?.map { it.toKeyValue() } ?: emptyList()

                val dialog = IntImpTallyDeleteDialogModel(changeReasonList) { dialogModel ->
                    val param = GjjDeclareParam(
                        dcode = dialogModel.changeReason.value ?: "",
                        dcontactsName = dialogModel.contactName.value ?: "",
                        dcontactsTel = dialogModel.contactPhone.value ?: "",
                        mtallyList = if (selectedMaWb.isNotEmpty()) selectedMaWb else null,
                        htallyList = if (selectedHaWb.isNotEmpty()) selectedHaWb else null
                    )

                    launchLoadingCollect({ NetApply.api.intImpTallyDeleteDeclare(param.toRequestBody()) }) {
                        onSuccess = {
                            showToast("删除申报成功")
                            viewModelScope.launch {
                                FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                            }
                            refresh()
                        }
                    }
                }

                dialog.show()
            }
        }
    }

    /**
     * 理货申报
     */
    fun tallyDeclareClick() {
        val (selectedMaWb, selectedHaWb) = getSelectedData()

        if (selectedMaWb.isEmpty() && selectedHaWb.isEmpty()) {
            showToast("请选择要申报的记录")
            return
        }

        val param = GjjDeclareParam(
            mtallyList = if (selectedMaWb.isNotEmpty()) selectedMaWb else null,
            htallyList = if (selectedHaWb.isNotEmpty()) selectedHaWb else null
        )

        launchLoadingCollect({ NetApply.api.intImpTallyDeclare(param.toRequestBody()) }) {
            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 },
            "wbNo" to waybillNo.value?.ifEmpty { null },
            "hno" to hno.value?.ifEmpty { null }
        )

        // 列表参数（含分页）
        val listParams = (filterParams + mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit
        )).toRequestBody()

        // 统计参数（无分页）
        val totalParams = filterParams.toRequestBody()

        // 获取列表（带Loading）
        launchLoadingCollect({
            NetApply.api.getIntImpTallyList(listParams)
        }) {
            onSuccess = { pageInfo ->
                // ⚠️ 核心：使用toBaseListBean()转换PageInfo为BaseListBean
                pageModel.handleListBean(pageInfo.toBaseListBean()) { updateCheckAllStatus() }
            }
        }

        // 获取统计信息（后台请求，不阻塞列表）
        launchCollect({ NetApply.api.getIntImpTallyTotal(totalParams) }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPc.value = (data?.totalPc ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }
    }
}
