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.holder.IntArrAirManifestViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjAirManifest
import com.lukouguoji.module_base.bean.GjjDeclareParam
import com.lukouguoji.module_base.bean.GjjImportManifest
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.gjj.dialog.IntImpTallyResetDialogModel
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 IntArrAirManifestViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())
    val flightNo = MutableLiveData("")
    val waybillNo = MutableLiveData("")
    val houseNo = 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<GjjAirManifest> ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
    }

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

    // ========== 适配器配置 ==========
    val itemViewHolder = IntArrAirManifestViewHolder::class.java
    val itemLayoutId = R.layout.item_int_arr_air_manifest

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

    /**
     * 全选按钮点击
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjAirManifest> ?: 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 toggleAllExpand() {
        val shouldExpand = !isAllExpanded.value!!
        isAllExpanded.value = shouldExpand
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjAirManifest> ?: return
        list.forEach { bean ->
            bean.showMore.set(shouldExpand)
        }
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

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

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

    /**
     * 收集选中的主单和分单（独立选择，互不影响）
     * @return Pair<主单列表, 分单列表>，如果无任何选中返回 null
     */
    private fun getSelectedItems(emptyMsg: String): Pair<List<GjjImportManifest>, List<GjjImportManifest>>? {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjAirManifest> ?: return null
        val maWbList = list.filter { it.isSelected }.mapNotNull { it.maWb }
        val haWbList = list.flatMap { it.haWbList ?: emptyList() }.filter { it.isSelected }
        if (maWbList.isEmpty() && haWbList.isEmpty()) {
            showToast(emptyMsg)
            return null
        }
        return Pair(maWbList, haWbList)
    }

    /**
     * 状态重置按钮点击
     */
    fun resetStatusClick() {
        val (maWbList, haWbList) = getSelectedItems("请选择要重置的舱单") ?: return

        val dialog = IntImpTallyResetDialogModel { dialogModel ->
            val param = GjjDeclareParam(
                maWbList = maWbList,
                haWbList = haWbList,
                restStatus = dialogModel.resetStatusCode
            )

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

        dialog.show()
    }

    /**
     * 补充信息按钮点击（只针对主单）
     */
    fun supplementInfoClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjAirManifest> ?: return
        val selectedMainItems = list.filter { it.isSelected }.mapNotNull { it.maWb }

        if (selectedMainItems.isEmpty()) {
            showToast("请选择要补充信息的主单")
            return
        }

        com.lukouguoji.gjj.activity.IntArrSupplementInfoActivity.start(
            getTopActivity(),
            ArrayList(selectedMainItems)
        )
    }

    /**
     * 删除申报按钮点击
     */
    fun deleteDeclarationClick() {
        val (maWbList, haWbList) = getSelectedItems("请选择要删除申报的舱单") ?: return

        // 校验申报状态：只有申报状态为 01 的舱单才能删除申报
        if (maWbList.any { it.mftStatus != "01" } || haWbList.any { it.mftStatus != "01" }) {
            showToast("只能删除申报状态为01的舱单")
            return
        }

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

                val dialog = com.lukouguoji.gjj.dialog.IntArrManifestDeleteDialogModel(deleteReasonList) { dialogModel ->
                    val param = GjjDeclareParam(
                        dcode = dialogModel.deleteReason.value ?: "",
                        dcontactsName = dialogModel.contactName.value ?: "",
                        dcontactsTel = dialogModel.contactPhone.value ?: "",
                        maWbList = maWbList,
                        haWbList = haWbList
                    )

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

                dialog.show()
            }
        }
    }

    /**
     * 舱单申报按钮点击
     */
    fun declareClick() {
        val (maWbList, haWbList) = getSelectedItems("请选择要申报的舱单") ?: return

        val param = GjjDeclareParam(maWbList = maWbList, haWbList = haWbList)

        launchLoadingCollect({ NetApply.api.declareIntArrManifest(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 houseNo.value?.ifEmpty { null }
        )

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

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

        // 获取列表（带Loading，接口直接返回PageInfo，无BaseResultBean包装）
        launchLoadingCollect({ NetApply.api.getIntArrAirManifestList(listParams) }) {
            onSuccess = { result ->
                isAllExpanded.value = false
                // 如果接口未返回航班日期/航班号，用筛选条件填充
                val fd = flightDate.value ?: ""
                val fn = flightNo.value ?: ""
                result.list?.forEach { airManifest ->
                    airManifest.maWb?.let {
                        if (it.fdate.isEmpty()) it.fdate = fd
                        if (it.fno.isEmpty()) it.fno = fn
                    }
                    airManifest.haWbList?.forEach {
                        if (it.fdate.isEmpty()) it.fdate = fd
                        if (it.fno.isEmpty()) it.fno = fn
                    }
                }
                pageModel.handleListBean(result.toBaseListBean()) { updateCheckAllStatus() }
            }
        }

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

    /**
     * 列表项点击事件 - 跳转到详情页
     */
    override fun onItemClick(position: Int, type: Int) {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjAirManifest> ?: return
        val airManifest = list.getOrNull(position) ?: return

        // 获取主单数据
        val manifest = airManifest.maWb ?: return

        // 跳转到详情页
        com.lukouguoji.gjj.activity.IntArrAirManifestDetailsActivity.start(
            getTopActivity(),
            manifest
        )
    }
}
