package com.lukouguoji.gjj.viewModel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.IntImpAccidentVisaViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.IntImpAccidentVisaBean
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.ConfirmDialogModel
import com.lukouguoji.module_base.model.ScanModel
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import kotlinx.coroutines.launch

/**
 * 国际进港-事故签证 ViewModel
 */
class IntImpAccidentVisaViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())
    val flightNo = MutableLiveData("")
    val fdep = MutableLiveData("")                          // 始发站（下拉）
    val fdepList = MutableLiveData<List<KeyValue>>(emptyList())
    val fdest = MutableLiveData("")                         // 目的站（禁止编辑，由航班查询返回）
    val wbNo = MutableLiveData("")                          // 运单号

    // ========== 航班查询 ==========
    private var lastQueriedFlight = ""

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

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

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

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

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpAccidentVisaViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_accident_visa

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

    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!!
                    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()))
                    }
                    fdepList.value = list
                    fdep.value = flight.fdep.noNull()
                } else {
                    fdest.value = ""
                    fdepList.value = emptyList()
                    fdep.value = ""
                    showToast(it.msg.noNull("获取航班信息失败"))
                }
            }

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

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

    fun addClick() {
        com.lukouguoji.gjj.activity.IntImpAccidentVisaEditActivity.start(getTopActivity())
    }

    fun searchClick() {
        refresh()
    }

    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpAccidentVisaBean> ?: return
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    fun deleteClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpAccidentVisaBean> ?: return
        val selected = list.filter { it.isSelected }
        if (selected.isEmpty()) {
            showToast("请选择要删除的数据")
            return
        }
        ConfirmDialogModel(
            message = "确定要删除选中的 ${selected.size} 条数据吗？",
            title = "提示"
        ) {
            doDelete(selected)
        }.show()
    }

    fun singleDelete(bean: IntImpAccidentVisaBean) {
        ConfirmDialogModel(
            message = "确定要删除运单号 ${bean.wbNo} 的事故签证吗？",
            title = "提示"
        ) {
            doDelete(listOf(bean))
        }.show()
    }

    private fun doDelete(list: List<IntImpAccidentVisaBean>) {
        launchLoadingCollect({ NetApply.api.deleteIntImpAccidentVisa(list.toRequestBody()) }) {
            onSuccess = {
                showToast("删除成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
        }
    }

    override fun getData() {
        val filterParams = mapOf<String, Any?>(
            "fdate" to flightDate.value?.ifEmpty { null },
            "fno" to flightNo.value?.ifEmpty { null },
            "fdep" to fdep.value?.ifEmpty { null },
            "fdest" to fdest.value?.ifEmpty { null },
            "wbNo" to wbNo.value?.ifEmpty { null }
        )

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

        launchLoadingCollect({ NetApply.api.getIntImpAccidentVisaList(listParams) }) {
            onSuccess = { pageInfo ->
                pageModel.handleListBean(pageInfo.toBaseListBean()) { updateCheckAllStatus() }
                totalCount.value = (pageInfo.total ?: 0).toString()
            }
        }
    }
}
