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.GjjManifestAddActivity
import com.lukouguoji.gjj.activity.IntImpManifestSubEditActivity
import com.lukouguoji.gjj.holder.IntImpManifestViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjjHaWb
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.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.gjj.dialog.IntImpModifyStorageDialogModel
import com.lukouguoji.module_base.model.ConfirmDialogModel
import dev.utils.app.info.KeyValue
import com.lukouguoji.module_base.model.ScanModel
import kotlinx.coroutines.launch

/**
 * 国际进港舱单 ViewModel
 */
class IntImpManifestViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    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.searchFlightList(
                mapOf(
                    "fdate" to fdate,
                    "fno" to fno,
                    "status" to "1",
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (it.verifySuccess() && !it.data.isNullOrEmpty()) {
                    val dataList = it.data!!
                    if (dataList.size > 1) {
                        showToast("存在多个航班记录，请核实")
                        fid = ""
                        fdep = ""
                        fdest.value = ""
                        sendAddressList.value = emptyList()
                        sendAddress.value = ""
                    } else {
                        val flight = dataList[0]
                        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 isAllExpanded = MutableLiveData(false)

    // ========== 分单管理模式 ==========
    val isSubManagementMode = MutableLiveData(false)

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpManifestViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_manifest

    /**
     * 搜索按钮点击
     * 先查询航班信息获取FID，再刷新列表
     */
    fun searchClick() {
        val fdate = flightDate.value
        val fno = flightNo.value

        // 校验航班号必填
        if (fno.isNullOrEmpty()) {
            showToast("请输入航班号")
            return
        }

        // 校验始发站、目的站是否已查询到
        if (sendAddress.value.isNullOrEmpty() || fdest.value.isNullOrEmpty()) {
            showToast("请先查询航班信息，获取始发站和目的站")
            return
        }

        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()
            }
        }
    }

    /**
     * 全选按钮点击（切换全选状态，联动子列表）
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: 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<GjjManifest> ?: return

        if (shouldExpand) {
            // 展开：对没有分单数据的项按需加载
            list.forEach { bean ->
                if (bean.haWbList.isNullOrEmpty()) {
                    loadHaWbList(bean)
                } else {
                    bean.showMore.set(true)
                }
            }
        } else {
            // 收起
            list.forEach { it.showMore.set(false) }
        }
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

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

    /**
     * 新增按钮点击
     */
    fun onAddClick() {
        GjjManifestAddActivity.start(
            context = getTopActivity(),
            fid = fid,
            dep = sendAddress.value ?: "",
            dest = fdest.value ?: "",
            flightDate = flightDate.value ?: "",
            flightNo = flightNo.value ?: ""
        )
    }

    /**
     * Item点击处理（侧滑按钮 + 列表项点击）
     */
    override fun onItemClick(position: Int, type: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? GjjManifest ?: return

        when (type) {
            101 -> {
                // 编辑（传递整个Bean对象 + 当前筛选的航班日期和航班号）
                GjjManifestAddActivity.startForEdit(
                    getTopActivity(), bean,
                    flightDate = flightDate.value ?: "",
                    flightNo = flightNo.value ?: ""
                )
            }
            102 -> {
                // 删除
                deleteManifest(bean)
            }
            103 -> {
                // 展开 - 加载分单数据
                loadHaWbList(bean)
            }
            else -> {
                // 列表项点击 - 跳转详情页
                com.lukouguoji.gjj.activity.IntImpManifestDetailsActivity.start(
                    getTopActivity(), bean
                )
            }
        }
    }

    /**
     * 删除单个舱单（通过批量删除接口，传单元素数组）
     */
    private fun deleteManifest(bean: GjjManifest) {
        ConfirmDialogModel(
            message = "确定要删除运单号 ${bean.getWaybillNo()} 的舱单吗？",
            title = "提示"
        ) {
            doDelete(listOf(bean), emptyList())
        }.show()
    }

    /**
     * 批量删除按钮点击
     */
    fun onDeleteClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return

        val selectedManifests = list.filter { it.isSelected }
        val selectedHawbs = list.flatMap { it.haWbList?.filter { hawb -> hawb.isSelected } ?: emptyList() }

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

        // 构建确认提示信息
        val msgParts = mutableListOf<String>()
        if (selectedManifests.isNotEmpty()) {
            msgParts.add("${selectedManifests.size} 条主单")
        }
        if (selectedHawbs.isNotEmpty()) {
            msgParts.add("${selectedHawbs.size} 条分单")
        }

        ConfirmDialogModel(
            message = "确定要删除选中的 ${msgParts.joinToString("和")} 吗？",
            title = "批量删除确认"
        ) {
            doDelete(selectedManifests, selectedHawbs)
        }.show()
    }

    /**
     * 执行删除：先删分单，再删主单（串行执行）
     */
    private fun doDelete(manifests: List<GjjManifest>, hawbs: List<GjjHaWb>) {
        viewModelScope.launch {
            try {
                showLoading()

                // 第一步：删除分单（如果有选中的分单）
                if (hawbs.isNotEmpty()) {
                    val hawbResult = NetApply.api.intImpManifestDeleteHawb(hawbs.toRequestBody())
                    if (!hawbResult.verifySuccess()) {
                        showToast(hawbResult.msg.noNull("分单删除失败"))
                        refresh()
                        return@launch
                    }
                }

                // 第二步：删除主单（分单删除成功后才执行）
                if (manifests.isNotEmpty()) {
                    val manifestResult = NetApply.api.intImpManifestDeleteManifest(manifests.toRequestBody())
                    if (!manifestResult.verifySuccess()) {
                        showToast(manifestResult.msg.noNull("分单已删除，但主单删除失败"))
                        refresh()
                        return@launch
                    }
                }

                showToast("删除成功")
                isAllChecked.value = false
                FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
            } catch (e: Exception) {
                showToast("删除失败：${e.message}")
            } finally {
                dismissLoading()
            }
        }
    }

    /**
     * 分单管理按钮点击 - 进入分单管理模式
     */
    fun subManagementClick() {
        isSubManagementMode.value = true
    }

    /**
     * 分单管理模式 - 返回按钮点击
     */
    fun subManagementBackClick() {
        isSubManagementMode.value = false
    }

    /**
     * 新增分单 - 选中一个主单后打开新增页面
     */
    fun addSubWaybillClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择一个主单")
            return
        }
        if (selectedItems.size > 1) {
            showToast("只能选择一个主单")
            return
        }

        val manifest = selectedItems[0]
        if (manifest.haWbList == null) {
            // 分单列表未加载，先加载再跳转
            launchLoadingCollect({ NetApply.api.getIntImpManifestHaWbList(manifest.toRequestBody()) }) {
                onSuccess = { result ->
                    manifest.haWbList = result.data ?: emptyList()
                    IntImpManifestSubEditActivity.startForAdd(getTopActivity(), manifest)
                }
            }
        } else {
            IntImpManifestSubEditActivity.startForAdd(getTopActivity(), manifest)
        }
    }

    /**
     * 修改分单 - 选中一个分单后打开编辑页面
     */
    fun modifySubWaybillClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return

        // 收集所有已选中的分单及其所属主单
        val selectedPairs = mutableListOf<Pair<GjjManifest, com.lukouguoji.module_base.bean.GjjHaWb>>()
        list.forEach { manifest ->
            manifest.haWbList?.forEach { haWb ->
                if (haWb.isSelected) {
                    selectedPairs.add(manifest to haWb)
                }
            }
        }

        if (selectedPairs.isEmpty()) {
            showToast("请选择一个分单")
            return
        }
        if (selectedPairs.size > 1) {
            showToast("只能选择一个分单")
            return
        }

        val (parentManifest, selectedHaWb) = selectedPairs[0]
        IntImpManifestSubEditActivity.startForModify(getTopActivity(), parentManifest, selectedHaWb)
    }

    /**
     * 分拣理货（跳转装机单页面）
     */
    fun sortingTallyClick() {
        com.alibaba.android.arouter.launcher.ARouter.getInstance()
            .build(com.lukouguoji.module_base.router.ARouterConstants.ACTIVITY_URL_INT_IMP_LOADING_LIST)
            .withString("fid", fid)
            .withString("fdep", fdep)
            .withString("fdate", flightDate.value ?: "")
            .withString("fno", flightNo.value ?: "")
            .withString("fdest", fdest.value ?: "")
            .navigation()
    }

    /**
     * 货物发放
     */
    fun cargoReleaseClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要发放的运单")
            return
        }

        IntImpModifyStorageDialogModel { dialog ->
            val params = mapOf(
                "location" to dialog.locationName,
                "locationId" to dialog.locationId.toLongOrNull(),
                "manifestList" to selectedItems
            ).toRequestBody()

            launchLoadingCollect({ NetApply.api.intImpManifestPutUpCargo(params) }) {
                onSuccess = {
                    if (it.verifySuccess()) {
                        showToast(it.msg.noNull("货物发放成功"))
                        refresh()
                    } else {
                        showToast(it.msg.noNull("货物发放失败"))
                    }
                }
            }
        }.show()
    }

    /**
     * 获取数据（重写BasePageViewModel）
     * 通过FID查询列表，而不是直接通过航班号和航班日期
     */
    override fun getData() {
        // 构建搜索条件（使用FID代替fdate/fno）
        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.getIntImpManifestList(listParams) }) {
            onSuccess = { result ->
                pageModel.handleListBean(result.toBaseListBean()) { updateCheckAllStatus() }
            }
        }

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

    /**
     * 加载主单下的分单列表（按需加载，加载完成后自动展开）
     */
    private fun loadHaWbList(bean: GjjManifest) {
        val params = bean.toRequestBody()

        launchLoadingCollect({ NetApply.api.getIntImpManifestHaWbList(params) }) {
            onSuccess = { result ->
                bean.haWbList = result.data ?: emptyList()
                bean.showMore.set(true)
                pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
            }
        }
    }
}
