package com.lukouguoji.gjj.viewModel

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.activity.IntImpQueryEditActivity
import com.lukouguoji.gjj.holder.IntImpQueryViewHolder
import com.lukouguoji.gjj.activity.IntImpQueryDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.IntImpQueryBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
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.model.ScanModel
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import com.lukouguoji.module_base.ktx.formatDate

/**
 * 国际进港查询ViewModel
 */
class IntImpQueryViewModel : BasePageViewModel(), IOnItemClickListener {

    // ==================== 搜索条件 ====================
    val flightDateStart = MutableLiveData<String>(DateUtils.getCurrentTime().formatDate())
    val flightDateEnd = MutableLiveData("")
    val agentId = MutableLiveData("")
    val outStatus = MutableLiveData("")
    val waybillNo = MutableLiveData("")

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

    val outStatusList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("未出库", "0"),
            KeyValue("已出库", "1")
        )
    )

    // ==================== 适配器配置 ====================
    val itemViewHolder = IntImpQueryViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_query

    // ==================== 统计数据 ====================
    val totalCount = MutableLiveData("0")
    val totalPc = MutableLiveData("0")
    val totalWeight = MutableLiveData("0")

    // ==================== 特码下拉 ====================
    val spCodeList = MutableLiveData<List<KeyValue>>(emptyList())

    // ==================== 筛选面板 ====================
    val filterVisible = MutableLiveData(false)
    val awbTypeList = MutableLiveData<List<KeyValue>>(emptyList())
    val businessTypeList = MutableLiveData<List<KeyValue>>(emptyList())

    // ==================== 5.5寸手机版专属 ====================
    // 三格统计：已入库 / 已出库（总票数复用 totalCount，为服务端全量口径）
    // pageQueryTotal 无分项统计出参——已入库/已出库为「已加载数据」客户端计数口径，
    // 与卡片状态标签同一判定（dlvTime / inDate，见 IntImpQueryBean）
    val storedCount = MutableLiveData("0")
    val outboundCount = MutableLiveData("0")

    private var phoneExtrasEnabled = false
    private var phoneLoadedList: List<IntImpQueryBean> = emptyList()

    /**
     * 手机形态专属初始化（Activity 在 DeviceUtil.isPhone() 时调用）。
     * 平板端不调用，请求次数与行为零变化。
     */
    fun initPhoneExtras() {
        phoneExtrasEnabled = true
    }

    // ==================== 筛选条件 ====================
    val spCode = MutableLiveData("")
    val flightNo = MutableLiveData("")
    val origin = MutableLiveData("")
    val awbType = MutableLiveData("")
    val businessType = MutableLiveData("")
    val goodsCn = MutableLiveData("")

    // 是否有筛选条件（任意一个非空则为 true）
    val hasFilter: MediatorLiveData<Boolean> = MediatorLiveData<Boolean>().apply {
        val update = { _: Any? ->
            value = listOf(spCode, flightNo, origin, awbType, businessType, goodsCn)
                .any { !it.value.isNullOrEmpty() }
        }
        addSource(spCode, update)
        addSource(flightNo, update)
        addSource(origin, update)
        addSource(awbType, update)
        addSource(businessType, update)
        addSource(goodsCn, update)
    }

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    fun waybillScanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }

    fun searchClick() {
        refresh()
    }

    fun filterClick() {
        filterVisible.value = true
    }

    fun closeFilter() {
        filterVisible.value = false
    }

    fun resetFilter() {
        spCode.value = ""
        flightNo.value = ""
        origin.value = ""
        awbType.value = ""
        businessType.value = ""
        goodsCn.value = ""
    }

    fun confirmFilter() {
        filterVisible.value = false
        refresh()
    }

    fun initFilterLists() {
        DictUtils.getWaybillTypeList(type = "II", addAll = true, checkedValue = awbType.value) {
            awbTypeList.postValue(it)
        }
        DictUtils.getBusinessTypeList(type = "II", addAll = true, checkedValue = businessType.value) {
            businessTypeList.postValue(it)
        }
    }

    override fun getData() {
        val listParams = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "beginDate" to flightDateStart.value!!.ifEmpty { null },
            "endDate" to flightDateEnd.value!!.ifEmpty { null },
            "agentCode" to agentId.value!!.ifEmpty { null },
            "outState" to outStatus.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            "spCode" to spCode.value!!.ifEmpty { null },
            "fno" to flightNo.value!!.ifEmpty { null },
            "origin" to origin.value!!.ifEmpty { null },
            "awbType" to awbType.value!!.ifEmpty { null },
            "businessType" to businessType.value!!.ifEmpty { null },
            "goods" to goodsCn.value!!.ifEmpty { null }
        ).toRequestBody()

        val totalParams = mapOf(
            "beginDate" to flightDateStart.value!!.ifEmpty { null },
            "endDate" to flightDateEnd.value!!.ifEmpty { null },
            "agentCode" to agentId.value!!.ifEmpty { null },
            "outState" to outStatus.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            "spCode" to spCode.value!!.ifEmpty { null },
            "fno" to flightNo.value!!.ifEmpty { null },
            "origin" to origin.value!!.ifEmpty { null },
            "awbType" to awbType.value!!.ifEmpty { null },
            "businessType" to businessType.value!!.ifEmpty { null },
            "goods" to goodsCn.value!!.ifEmpty { null }
        ).toRequestBody()

        launchLoadingCollect({
            NetApply.api.getIntImpQueryList(listParams)
        }) {
            onSuccess = { pageInfo ->
                pageModel.handleListBean(pageInfo.toBaseListBean())

                // 手机三格统计：对已加载数据做客户端计数（平板不触发）
                if (phoneExtrasEnabled) {
                    val pageItems = pageInfo.list ?: emptyList()
                    phoneLoadedList =
                        if (pageModel.page <= 1) pageItems else phoneLoadedList + pageItems
                    updatePhoneCounts()
                }
            }
        }

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

    /**
     * 手机三格统计（已入库/已出库）：与卡片状态标签同一判定口径（dlvTime / inDate），
     * 统计范围为已加载的列表数据。
     */
    private fun updatePhoneCounts() {
        outboundCount.value = phoneLoadedList.count { it.isQueryOutbound }.toString()
        storedCount.value =
            phoneLoadedList.count { !it.isQueryOutbound && it.isQueryStored }.toString()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.WAYBILL -> {
                    waybillNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpQueryBean> ?: return
        val bean = list.getOrNull(position) ?: return

        when (type) {
            2000 -> {
                // 侧滑菜单 - 修改操作
                IntImpQueryEditActivity.start(getTopActivity(), bean.maWbId, bean.prefix, bean.no)
            }
            else -> {
                // 默认点击 - 进入详情
                IntImpQueryDetailsActivity.start(getTopActivity(), bean.prefix, bean.no)
            }
        }
    }

    fun initSpecialCodeList() {
        DictUtils.getSpecialCodeList(
            flag = 1,
            ieFlag = "",
            parentcode = ""
        ) {
            spCodeList.value = it
        }
    }

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