package com.lukouguoji.gjc.viewModel

import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.IntExpAssembleItemViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcUldUseBean
import com.lukouguoji.module_base.http.net.NetApply
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.showConfirmDialog
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.router.ARouterConstants
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils

/**
 * 国际出港-出港组装ViewModel
 */
class IntExpAssembleViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val flightDate = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())        // 航班日期
    val flightNo = MutableLiveData("")          // 航班号
    val uldNo = MutableLiveData("")             // ULD编号

    val reweighStatus = MutableLiveData("") // 复磅状态
    val reweighStatusList = MutableLiveData(    // 复磅状态选项
        listOf(
            KeyValue("全部", ""),
            KeyValue("未复磅", "0"),
            KeyValue("已复磅", "1")
        )
    )
    val assembler = MutableLiveData("")         // 组装人
    val assemblerList = MutableLiveData<List<KeyValue>>(emptyList())  // 组装人列表

    // ========== 适配器配置 ==========
    val itemViewHolder = IntExpAssembleItemViewHolder::class.java
    val itemLayoutId = R.layout.item_int_exp_assemble

    // ========== 底部统计 ==========
    val totalCount = MutableLiveData("0")       // 合计票数
    val totalPieces = MutableLiveData("0")      // 总件数
    val totalWeight = MutableLiveData("0")      // 总重量

    /**
     * 初始化组装人下拉列表
     */
    fun initAssemblerList() {
        launchCollect({ NetApply.api.getIntExpAssemblerList() }) {
            onSuccess = { result ->
                val list = mutableListOf<KeyValue>()
                result.data?.forEach { name ->
                    list.add(KeyValue(name, name))
                }
                assemblerList.value = list
            }
        }
    }

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

    /**
     * 切换展开/收起状态
     * 首次展开时加载运单明细数据
     */
    fun toggleExpand(position: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? GjcUldUseBean ?: return
        val isCurrentlyExpanded = bean.showMore.get()

        if (isCurrentlyExpanded) {
            // 当前是展开状态，收起
            bean.showMore.set(false)
        } else {
            // 当前是收起状态，展开
            bean.showMore.set(true)
            // 如果未加载过数据，则加载
            if (!bean.waybillDetailsLoaded) {
                loadWaybillDetails(position, bean)
            }
        }
    }

    /**
     * 加载运单明细
     * 使用接口: /IntExpAssemble/queryAssembledByUld
     */
    private fun loadWaybillDetails(position: Int, bean: GjcUldUseBean) {
        // 设置加载中状态
        bean.isLoading.set(true)
        pageModel.rv?.commonAdapter()?.notifyItemChanged(position)

        // 构建请求参数 - 传递完整的GjcUldUseBean信息
        val params = mapOf(
            "useId" to bean.useId,
            "uld" to bean.uld,
            "fdate" to bean.fdate,
            "fno" to bean.fno
        ).toRequestBody()

        launchCollect({ NetApply.api.getAssembledWaybillsByUld(params) }) {
            onSuccess = { result ->
                bean.waybillDetails = result.data?.toMutableList()
                bean.waybillDetailsLoaded = true
                bean.isLoading.set(false)
                pageModel.rv?.commonAdapter()?.notifyItemChanged(position)
            }
            onFailed = { _, msg ->
                bean.waybillDetailsLoaded = true  // 标记为已加载（即使失败也显示暂无数据）
                bean.waybillDetails = mutableListOf()  // 设置空列表
                bean.isLoading.set(false)
                pageModel.rv?.commonAdapter()?.notifyItemChanged(position)
                showToast(msg)
            }
        }
    }

    /**
     * 获取数据（列表 + 统计）
     */
    override fun getData() {
        // 构建筛选参数
        val filterParams = mapOf(
            "fdate" to flightDate.value!!.ifEmpty { null },
            "fno" to flightNo.value!!.ifEmpty { null },
            "uld" to uldNo.value!!.ifEmpty { null },
            "ldUserName" to assembler.value!!.ifEmpty { null }
        )

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

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

        // 获取列表（显示loading）
        launchLoadingCollect({ NetApply.api.getIntExpAssembleList(listParams) }) {
            onSuccess = { pageModel.handleListBean(it) }
        }

        // 获取统计（后台调用）
        launchCollect({ NetApply.api.getIntExpAssembleTotal(totalParams) }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPieces.value = (data?.totalPc ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }
    }

    /**
     * Item点击事件处理
     */
    override fun onItemClick(position: Int, type: Int) {
        when (type) {
            1000 -> toggleExpand(position)      // 展开/收起操作
            2000 -> onEditItem(position)        // 修改操作
            2001 -> onDeleteSingleItem(position) // 删除操作
        }
    }

    /**
     * 修改单个列表项 - 跳转到开始组装页面（修改模式）
     * ULD 编号将被锁定，整个页面生命周期内不可编辑
     * 同时传递组装位置，用于自动选中对应项
     */
    private fun onEditItem(position: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? GjcUldUseBean ?: return
        com.lukouguoji.gjc.page.assemble.IntExpAssembleStartActivity.startForEdit(
            getTopActivity(),
            bean.uld,
            bean.loadArea
        )
    }

    /**
     * 删除单个列表项（侧滑操作）
     */
    private fun onDeleteSingleItem(position: Int) {
        val bean = pageModel.rv?.commonAdapter()?.getItem(position) as? GjcUldUseBean ?: return

        getTopActivity().showConfirmDialog("确定要删除该条记录吗？") {
            deleteSingleItem(bean)
        }
    }

    /**
     * 执行单项删除
     */
    private fun deleteSingleItem(bean: GjcUldUseBean) {
        val requestData = listOf(bean).toRequestBody()

        launchLoadingCollect({ NetApply.api.deleteIntExpAssemble(requestData) }) {
            onSuccess = {
                showToast("删除成功")
                refresh()
            }
        }
    }

    /**
     * 加号按钮点击 - 跳转到开始组装页面
     */
    fun onAddClick() {
        ARouter.getInstance()
            .build(ARouterConstants.ACTIVITY_URL_INT_EXP_ASSEMBLE_START)
            .navigation()
    }

    /**
     * 删除按钮点击
     */
    fun onDeleteClick() {
        // 获取选中的数据
        val adapter = pageModel.rv?.commonAdapter() ?: return
        val allItems = adapter.items
        val selectedItems = allItems
            .filterIsInstance<GjcUldUseBean>()
            .filter { it.isSelected }

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

        // 显示确认对话框
        getTopActivity().showConfirmDialog("确定要删除选中的 ${selectedItems.size} 条记录吗？") {
            deleteSelectedItems(selectedItems)
        }
    }

    /**
     * 删除选中项
     */
    private fun deleteSelectedItems(items: List<GjcUldUseBean>) {
        val requestData = items.toRequestBody()

        launchLoadingCollect({ NetApply.api.deleteIntExpAssemble(requestData) }) {
            onSuccess = {
                showToast("删除成功")
                refresh()
            }
        }
    }

    /**
     * 回填重量按钮点击 - 跳转到修改组装重量页面
     */
    fun onBackfillWeightClick() {
        // 获取选中的数据
        val adapter = pageModel.rv?.commonAdapter() ?: return
        val allItems = adapter.items
        val selectedItems = allItems
            .filterIsInstance<GjcUldUseBean>()
            .filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要修改重量的ULD")
            return
        }

        if (selectedItems.size > 1) {
            showToast("每次只能选择一个ULD进行重量修改")
            return
        }

        // 跳转到修改组装重量页面
        val bean = selectedItems.first()
        com.lukouguoji.gjc.activity.GjcAssembleWeightEditActivity.start(getTopActivity(), bean)
    }
}
