package com.lukouguoji.gjj.viewModel

import android.app.Activity
import androidx.appcompat.app.AlertDialog
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.holder.IntImpManifestViewHolder
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.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 kotlinx.coroutines.launch

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

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val fdep = MutableLiveData("")              // 始发站
    val waybillNo = MutableLiveData("")         // 运单号

    // ========== 统计信息 ==========
    val totalCount = MutableLiveData("0")       // 合计票数
    val totalPc = MutableLiveData("0")          // 总件数
    val totalWeight = MutableLiveData("0")      // 总重量

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

    init {
        // 监听全选状态，自动更新所有列表项
        isAllChecked.observeForever { checked ->
            val list = pageModel.rv?.commonAdapter()?.items as? List<GjjManifest> ?: return@observeForever
            list.forEach { it.checked.set(checked) }
            pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        }
    }

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

    /**
     * 搜索按钮点击
     */
    fun searchClick() {
        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)
    }

    /**
     * 新增按钮点击
     */
    fun onAddClick() {
        // 获取当前航班信息
        val fid = getCurrentFlightId()

        GjjManifestAddActivity.start(
            context = getTopActivity(),
            fid = fid,
            dep = fdep.value ?: "",
            dest = ""  // 目的站暂时留空
        )
    }

    /**
     * 获取当前航班ID（从列表第一项获取）
     */
    private fun getCurrentFlightId(): String {
        val firstItem = pageModel.rv?.commonAdapter()?.items?.firstOrNull() as? GjjManifest
        return firstItem?.fid?.toString() ?: ""
    }

    /**
     * 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)
            }
            102 -> {
                // 删除
                deleteManifest(bean)
            }
        }
    }

    /**
     * 删除单个舱单
     */
    private fun deleteManifest(bean: GjjManifest) {
        AlertDialog.Builder(getTopActivity())
            .setTitle("提示")
            .setMessage("确定要删除运单号 ${bean.getWaybillNo()} 的舱单吗？")
            .setPositiveButton("确定") { _, _ ->
                val params = mapOf("mfId" to bean.mfId).toRequestBody()

                launchLoadingCollect({ NetApply.api.gjjManifestDelete(params) }) {
                    onSuccess = {
                        if (it.verifySuccess()) {
                            showToast("删除成功")
                            viewModelScope.launch {
                                FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                            }
                            refresh()
                        } else {
                            showToast(it.msg.noNull("删除失败"))
                        }
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

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

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

        showToast("删除功能开发中")
    }

    /**
     * 分单管理（暂不实现）
     */
    fun subManagementClick() {
        showToast("分单管理功能开发中")
    }

    /**
     * 分拣理货（跳转装机单页面）
     */
    fun sortingTallyClick() {
        com.alibaba.android.arouter.launcher.ARouter.getInstance()
            .build(com.lukouguoji.module_base.router.ARouterConstants.ACTIVITY_URL_INT_IMP_LOADING_LIST)
            .navigation()
    }

    /**
     * 货物发放（暂不实现）
     */
    fun cargoReleaseClick() {
        showToast("货物发放功能开发中")
    }

    /**
     * 获取数据（重写BasePageViewModel）
     */
    override fun getData() {
        // 构建搜索条件
        val filterParams = mapOf(
            "fdate" to flightDate.value?.ifEmpty { null },
            "fno" to flightNo.value?.ifEmpty { null },
            "fdep" to fdep.value?.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 ->
                // 处理PageInfo结构
                val pageInfo = result.data
                if (pageInfo != null) {
                    val list = pageInfo.list ?: emptyList()
                    val pages = pageInfo.pages ?: 1

                    // 处理分页数据
                    pageModel.handleDataList(list)
                    pageModel.haveMore.postValue(pages > pageModel.page)
                } else {
                    pageModel.handleDataList(emptyList())
                    pageModel.haveMore.postValue(false)
                }
            }
        }

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