package com.lukouguoji.gjj.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.IntImpLoadingListViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjManifest
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.interfaces.IOnItemClickListener
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 dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国际进港装机单 ViewModel
 */
class IntImpLoadingListViewModel : BasePageViewModel(), IOnItemClickListener {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData("")        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val sendAddress = MutableLiveData("")       // 始发站（选中值）
    val sendAddressList = MutableLiveData<List<KeyValue>>(emptyList()) // 始发站下拉列表
    val fdest = MutableLiveData("")             // 目的站
    val waybillNo = MutableLiveData("")         // 运单号

    // ========== 航班级联查询 ==========
    private var lastQueriedFlight = ""
    var fid = ""
    var fdep = ""

    fun onFlightDateInputComplete() {
        lastQueriedFlight = ""
        queryFlightIfReady()
    }

    fun onFlightNoInputComplete() {
        queryFlightIfReady()
    }

    private fun queryFlightIfReady() {
        val fdate = flightDate.value
        val fno = flightNo.value
        if (fdate.isNullOrEmpty() || fno.isNullOrEmpty()) return

        val key = "$fdate-$fno"
        if (key == lastQueriedFlight) return
        lastQueriedFlight = key

        launchCollect({
            NetApply.api.getGjFlightBean(
                mapOf(
                    "fdate" to fdate,
                    "fno" to fno,
                    "ieFlag" to "I",
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess() && it.data != null) {
                    val flight = it.data!!
                    fid = flight.fid.noNull()
                    fdep = flight.fdep.noNull()
                    fdest.value = flight.fdest.noNull()

                    // 构建始发站下拉列表：fdep + jtz（经停港）
                    val list = mutableListOf(
                        KeyValue(flight.fdep.noNull(), flight.fdep.noNull()),
                    )
                    if (!flight.jtz.isNullOrEmpty()) {
                        list.add(KeyValue(flight.jtz.noNull(), flight.jtz.noNull()))
                    }
                    sendAddressList.value = list
                    sendAddress.value = flight.fdep.noNull()
                } else {
                    fid = ""
                    fdep = ""
                    fdest.value = ""
                    sendAddressList.value = emptyList()
                    sendAddress.value = ""
                    showToast(it.msg.noNull("获取航班信息失败"))
                }
            }

            onFailed = { _, _ ->
                fid = ""
                fdep = ""
                fdest.value = ""
                sendAddressList.value = emptyList()
                sendAddress.value = ""
            }
        }
    }

    // ========== 统计信息 ==========
    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<GjjManifest> ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpLoadingListViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_loading_list

    /**
     * 搜索按钮点击
     * 先查询航班信息获取FID，再刷新列表（与父页面逻辑保持一致）
     */
    fun searchClick() {
        val fdate = flightDate.value
        val fno = flightNo.value
        if (!fdate.isNullOrEmpty() && !fno.isNullOrEmpty()) {
            val key = "$fdate-$fno"
            if (key != lastQueriedFlight || fid.isEmpty()) {
                // 先查询航班信息获取FID
                lastQueriedFlight = key
                launchLoadingCollect({
                    NetApply.api.getGjFlightBean(
                        mapOf(
                            "fdate" to fdate,
                            "fno" to fno,
                            "ieFlag" to "I",
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = {
                        if (it.verifySuccess() && it.data != null) {
                            val flight = it.data!!
                            fid = flight.fid.noNull()
                            fdep = flight.fdep.noNull()
                            fdest.value = flight.fdest.noNull()
                            val list = mutableListOf(
                                KeyValue(flight.fdep.noNull(), flight.fdep.noNull()),
                            )
                            if (!flight.jtz.isNullOrEmpty()) {
                                list.add(KeyValue(flight.jtz.noNull(), flight.jtz.noNull()))
                            }
                            sendAddressList.value = list
                            sendAddress.value = flight.fdep.noNull()
                        } else {
                            fid = ""
                            fdep = ""
                            fdest.value = ""
                            sendAddressList.value = emptyList()
                            sendAddress.value = ""
                            showToast(it.msg.noNull("获取航班信息失败"))
                        }
                        refresh()
                    }
                    onFailed = { _, _ ->
                        fid = ""
                        fdep = ""
                        fdest.value = ""
                        sendAddressList.value = emptyList()
                        sendAddress.value = ""
                        refresh()
                    }
                }
            } else {
                refresh()
            }
        } else {
            fid = ""
            fdep = ""
            refresh()
        }
    }

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

        // 切换全选状态
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll

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

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

    /**
     * 修改库位（由 Activity 调用 Dialog 后回调）
     */
    fun performModifyStorage(
        locationName: String,
        locationId: String,
        selectedItems: List<GjjManifest>
    ) {
        if (locationName.isEmpty() || locationId.isEmpty()) {
            showToast("请选择库位")
            return
        }

        val params = mapOf(
            "location" to locationName,
            "locationId" to locationId.toLongOrNull(),
            "manifestList" to selectedItems
        ).toRequestBody()

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

    /**
     * 入库（由 Activity 调用 Dialog 后回调）
     */
    fun performInStorage(
        locationName: String,
        locationId: String,
        selectedItems: List<GjjManifest>
    ) {
        if (selectedItems.isEmpty()) {
            showToast("请至少选择一个单据")
            return
        }

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

        val params = mapOf(
            "location" to locationName,
            "locationId" to locationId.toLongOrNull(),
            "manifestList" to selectedItems
        ).toRequestBody()

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

    /**
     * 列表项点击回调（侧滑菜单）
     */
    override fun onItemClick(position: Int, type: Int) {
        when (type) {
            2000 -> {
                // 编辑操作
                val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return
                val bean = list.getOrNull(position) ?: return
                com.lukouguoji.gjj.activity.IntImpLoadingListEditActivity.start(getTopActivity(), bean)
            }
        }
    }

    /**
     * 获取数据（重写BasePageViewModel）
     * 查询参数与父页面（国际进港舱单）保持一致：使用FID和FDGP
     */
    override fun getData() {
        // 构建搜索条件（与父页面一致：fid + fdep + wbNo）
        val filterParams = mapOf(
            "fid" to fid.ifEmpty { null },
            "fdep" to fdep.ifEmpty { null },
            "wbNo" to waybillNo.value?.ifEmpty { null }
        )

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

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

        // 获取列表（带Loading）
        launchLoadingCollect({ NetApply.api.getIntImpLoadingList(listParams) }) {
            onSuccess = { result ->
                pageModel.handleListBean(result.toBaseListBean()) { updateCheckAllStatus() }
            }
        }

        // 获取统计信息（后台请求，不阻塞列表）
        launchCollect({ NetApply.api.getIntImpLoadingTotal(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()
            }
        }
    }
}
