package com.lukouguoji.gjc.viewModel

import android.text.InputType
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.holder.IntExpAssembleViewHolder
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.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.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.router.ARouterConstants
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate
import kotlinx.coroutines.launch

/**
 * 国际出港-出港组装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 = IntExpAssembleViewHolder::class.java
    val itemLayoutId = R.layout.item_int_exp_assemble_uld

    // ========== 底部统计 ==========
    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
        bean.isExpanded = !bean.isExpanded

        if (bean.isExpanded && bean.waybillDetails == null) {
            // 首次展开，加载运单明细
            loadWaybillDetails(position, bean)
        } else {
            // 已有数据，直接刷新item显示/隐藏
            pageModel.rv?.commonAdapter()?.notifyItemChanged(position)
        }
    }

    /**
     * 加载运单明细
     */
    private fun loadWaybillDetails(position: Int, bean: GjcUldUseBean) {
        val params = mapOf("useId" to bean.useId).toRequestBody()

        launchCollect({ NetApply.api.getIntExpAssembleWaybillDetails(params) }) {
            onSuccess = { result ->
                bean.waybillDetails = result.data ?: mutableListOf()
                pageModel.rv?.commonAdapter()?.notifyItemChanged(position)
            }
            onFailed = { _, msg ->
                bean.isExpanded = false  // 加载失败，恢复展开状态
                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) {
        if (type == 1000) {  // 展开/收起操作
            toggleExpand(position)
        }
    }

    /**
     * 加号按钮点击 - 跳转到开始组装页面
     */
    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
        }

        // 显示确认对话框
        val activity = getTopActivity()
        AlertDialog.Builder(activity)
            .setTitle("删除确认")
            .setMessage("确定要删除选中的 ${selectedItems.size} 条记录吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteSelectedItems(selectedItems)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 删除选中项
     */
    private fun deleteSelectedItems(items: List<GjcUldUseBean>) {
        val ids = items.mapNotNull { it.useId }.joinToString(",")

        launchLoadingCollect({ NetApply.api.deleteIntExpAssemble(ids) }) {
            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("请选择要回填重量的记录")
            return
        }

        // 显示输入对话框
        showBackfillWeightDialog(selectedItems)
    }

    /**
     * 显示回填重量对话框
     */
    private fun showBackfillWeightDialog(items: List<GjcUldUseBean>) {
        val activity = getTopActivity()

        // 创建输入框
        val input = EditText(activity).apply {
            hint = "请输入重量(KG)"
            inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
            setPadding(40, 40, 40, 40)
        }

        AlertDialog.Builder(activity)
            .setTitle("回填重量")
            .setMessage("共选中 ${items.size} 条记录")
            .setView(input)
            .setPositiveButton("确定") { _, _ ->
                val weight = input.text.toString()
                if (weight.verifyNullOrEmpty("请输入重量")) return@setPositiveButton
                backfillWeight(items, weight)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 回填重量API调用
     */
    private fun backfillWeight(items: List<GjcUldUseBean>, weight: String) {
        val ids = items.mapNotNull { it.useId }.joinToString(",")
        val params = mapOf(
            "ids" to ids,
            "weight" to weight
        ).toRequestBody()

        launchLoadingCollect({ NetApply.api.backfillIntExpAssembleWeight(params) }) {
            onSuccess = {
                showToast("回填重量成功")
                refresh()
            }
        }
    }
}
