package com.lukouguoji.gjj.viewModel

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.IntImpPickUpDLVViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.IntImpPickUpDLVBean
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.showToast
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ConfirmDialogModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import kotlinx.coroutines.launch

/**
 * 国际进港-提取出库 ViewModel
 */
class IntImpPickUpDLVViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val paymentDateStart = MutableLiveData(DateUtils.getCurrentTime().formatDate())    // 缴费日期起
    val paymentDateEnd = MutableLiveData("")      // 缴费日期止
    val agentCode = MutableLiveData("")           // 代理人
    val wbNo = MutableLiveData("")               // 运单号
    val spCode = MutableLiveData("")             // 特码

    // ========== 下拉列表数据源 ==========
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))

    // ========== 统计信息 ==========
    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<IntImpPickUpDLVBean> ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
        selectedCountText.value = "已选 ${list.count { it.checked.get() }} 项"
    }

    // ========== 5.5寸手机版专属 ==========
    // 状态 Tab：待出库/已出库（outState 为 pageQuery 真实入参，0：未出库，1：已出库；平板恒空不进请求）
    val outState = MutableLiveData("")
    val tabList = MutableLiveData(listOf(KeyValue("待出库", "0"), KeyValue("已出库", "1")))
    val tabCounts = MutableLiveData(listOf("0", "0"))

    // 底部操作条「已选 N 项」
    val selectedCountText = MutableLiveData("已选 0 项")

    // 筛选弹层显隐
    val filterVisible = MutableLiveData(false)

    // 筛选条件（flightDate 为 pageQuery 未定义入参 fdate，预留传参，见接口问题清单）
    val flightDate = MutableLiveData("")
    val flightNo = MutableLiveData("")

    // 特码下拉字典（initPhoneExtras 加载，平板为扫码输入不加载）
    val specialCodeList = MutableLiveData<List<KeyValue>>(emptyList())

    private var phoneExtrasEnabled = false

    /**
     * 手机形态专属初始化（Activity 在 DeviceUtil.isPhone() 时调用）。
     * 平板端不调用，请求次数与行为零变化。
     */
    fun initPhoneExtras() {
        phoneExtrasEnabled = true
        // 默认进「待出库」Tab
        outState.value = "0"
        // 平板默认按当天缴费日期过滤，设计稿无此默认——手机端清空查全量
        paymentDateStart.value = ""
        // 特码字典：flag=1 国际；ieFlag 必须留空
        DictUtils.getSpecialCodeList(addAll = false, flag = 1, ieFlag = "") { list ->
            specialCodeList.postValue(listOf(KeyValue("全部", "")) + list)
        }
    }

    /** 筛选按钮点击 - 打开筛选面板 */
    fun filterClick() {
        filterVisible.value = true
    }

    /** 关闭筛选面板 */
    fun closeFilter() {
        filterVisible.value = false
    }

    /** 重置筛选条件 */
    fun resetFilter() {
        flightDate.value = ""
        flightNo.value = ""
        agentCode.value = ""
        spCode.value = ""
    }

    /** 确认筛选 - 关闭面板并刷新 */
    fun confirmFilter() {
        filterVisible.value = false
        refresh()
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpPickUpDLVViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_pick_up_dlv

    /**
     * 初始化代理人列表
     */
    fun initAgentList() {
        launchCollect({ NetApply.api.getIntImpAgentList() }) {
            onSuccess = { result ->
                val list = mutableListOf(KeyValue("全部", ""))
                result.data?.forEach {
                    list.add(KeyValue(it.name ?: "", it.code ?: ""))
                }
                agentList.value = list
            }
        }
    }

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

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

    /**
     * 扫码特码
     */
    fun scanSpCode() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.gnj_chu_ku_list)
    }

    /**
     * 全选按钮点击
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpDLVBean> ?: return
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        // 同步手机版底部条「已选 N 项」（平板布局不绑定该字段，无影响）
        selectedCountText.value = "已选 ${list.count { it.checked.get() }} 项"
    }

    /**
     * 确认出库
     */
    fun confirmOutbound() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpDLVBean> ?: return
        val selectedItems = list.filter { it.isSelected }

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

        ConfirmDialogModel(
            message = "确定要将选中的${selectedItems.size}条记录确认出库吗？",
            title = "确认出库"
        ) {
            launchLoadingCollect({ NetApply.api.confirmIntImpPickUpDLV(selectedItems.toRequestBody()) }) {
                onSuccess = {
                    showToast("确认出库成功")
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }
                    refresh()
                }
            }
        }.show()
    }

    /**
     * 获取列表数据
     */
    override fun getData() {
        // 手机专属 3 项平板恒为空，不进请求；fdate 为 pageQuery 未定义入参
        //（后端静默忽略，补齐后自动生效，见接口问题清单）
        val filterParams = mapOf(
            "beginDate" to paymentDateStart.value?.ifEmpty { null },
            "endDate" to paymentDateEnd.value?.ifEmpty { null },
            "agentCode" to agentCode.value?.ifEmpty { null },
            "no" to wbNo.value?.ifEmpty { null },
            "spCode" to spCode.value?.ifEmpty { null },
            "outState" to outState.value?.ifEmpty { null },
            "fno" to flightNo.value?.ifEmpty { null },
            "fdate" to flightDate.value?.ifEmpty { null }
        )

        val listParams = (filterParams + mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit
        )).toRequestBody()

        val totalParams = filterParams.toRequestBody()

        launchLoadingCollect({ NetApply.api.getIntImpPickUpDLVList(listParams) }) {
            onSuccess = { result ->
                pageModel.handleDataList(result.list) { updateCheckAllStatus() }
                pageModel.haveMore.postValue((result.pages) > pageModel.page)
            }
        }

        launchCollect({ NetApply.api.getIntImpPickUpDLVTotal(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()
            }
        }

        // 手机专属：Tab 角标计数（同条件 + outState=0/1 各查一次，平板不发）
        if (phoneExtrasEnabled) {
            val pendingParams = (filterParams + mapOf("outState" to "0")).toRequestBody()
            launchCollect({ NetApply.api.getIntImpPickUpDLVTotal(pendingParams) }) {
                onSuccess = { result ->
                    tabCounts.value = listOf(
                        (result.data?.wbNumber ?: 0).toString(),
                        tabCounts.value?.getOrNull(1) ?: "0"
                    )
                }
            }
            val shippedParams = (filterParams + mapOf("outState" to "1")).toRequestBody()
            launchCollect({ NetApply.api.getIntImpPickUpDLVTotal(shippedParams) }) {
                onSuccess = { result ->
                    tabCounts.value = listOf(
                        tabCounts.value?.getOrNull(0) ?: "0",
                        (result.data?.wbNumber ?: 0).toString()
                    )
                }
            }
        }
    }

    /**
     * 处理扫码结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.WAYBILL -> {
                    wbNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
                Constant.RequestCode.gnj_chu_ku_list -> {
                    spCode.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }
}
