package com.lukouguoji.gjj.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.gjj.activity.IntArrTelegramDetailsActivity
import com.lukouguoji.gjj.holder.IntImpMsgParseViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlightBean
import com.lukouguoji.module_base.bean.MsgReceivePool
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 dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国际进港-电报解析 ViewModel
 */
class IntImpMsgParseViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val sendAddress = MutableLiveData("")       // 发站（择始发站）
    val sendAddressList = MutableLiveData<List<KeyValue>>(emptyList())
    val receiveAddress = MutableLiveData("")    // 收报地址（目的站，由航班查询返回）
    val msgType = MutableLiveData("")           // 报文类型
    val msgTypeList = MutableLiveData<List<KeyValue>>(emptyList())

    // ========== 航班查询 ==========
    private var fid: String = ""                // 航班ID
    private var lastQueriedFlight = ""          // 避免重复查询

    // ========== 统计信息 ==========
    val totalCount = MutableLiveData("0")       // 合计条数

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

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

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

    init {
        // 初始化报文类型静态数据
        msgTypeList.value = listOf(
            KeyValue("FFM", "FFM"),
            KeyValue("FWB/FHL", "FWB/FHL")
        )

    }

    // ========== 航班级联查询 ==========

    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()
                    receiveAddress.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 = ""
                    receiveAddress.value = ""
                    sendAddressList.value = emptyList()
                    sendAddress.value = ""
                    showToast(it.msg.noNull("获取航班信息失败"))
                }
            }

            onFailed = { _, _ ->
                fid = ""
                receiveAddress.value = ""
                sendAddressList.value = listOf(KeyValue("全部", ""))
                sendAddress.value = ""
            }
        }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpMsgParseViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_msg_parse

    /**
     * 搜索按钮点击
     */
    fun searchClick() {
        if (msgType.value.isNullOrEmpty()) {
            showToast("请选择报文类型")
            return
        }
        refresh()
    }

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

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

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

    /**
     * 电报生成（解析电报）
     */
    fun generateMsg() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<MsgReceivePool> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要生成的电报")
            return
        }

        if (fid.isEmpty()) {
            showToast("请先查询航班信息")
            return
        }

        val requestData = mapOf(
            "fid" to fid.toLongOrNull(),
            "msgList" to selectedItems
        ).toRequestBody()

        launchLoadingCollect({ NetApply.api.analyseMsg(requestData) }) {
            onSuccess = {
                showToast("电报生成成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    /**
     * 获取数据（重写BasePageViewModel）
     */
    override fun getData() {
        // 构建搜索条件：优先用 fid，否则用 fdate + fno
        val filterParams = mutableMapOf<String, Any?>(
            "sendAddress" to sendAddress.value?.ifEmpty { null },
            "receiveAddress" to receiveAddress.value?.ifEmpty { null },
            "msgType" to msgType.value?.ifEmpty { null }
        )
        if (fid.isNotEmpty()) {
            filterParams["fid"] = fid
        } else {
            filterParams["fdate"] = flightDate.value?.ifEmpty { null }
            filterParams["fno"] = flightNo.value?.ifEmpty { null }
        }

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

        // 获取列表（带Loading）
        launchLoadingCollect({ NetApply.api.getIntImpMsgList(listParams) }) {
            onSuccess = { pageInfo ->
                pageModel.handleListBean(pageInfo.toBaseListBean()) { updateCheckAllStatus() }
                totalCount.value = (pageInfo.total ?: 0).toString()
            }
        }
    }

    /**
     * 列表项点击 — 跳转电报详情页
     */
    override fun onItemClick(position: Int, type: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? MsgReceivePool ?: return
        IntArrTelegramDetailsActivity.start(getTopActivity(), bean, fid)
    }
}
