package com.lukouguoji.aerologic.page.gnj.move.stash.list

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.aerologic.R
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.MoveStashBean
import com.lukouguoji.module_base.common.Constant
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.noNull
import com.lukouguoji.module_base.ktx.showConfirmDialog
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.CheckUtil
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import dev.DevUtils
import dev.utils.app.info.KeyValue
import okhttp3.RequestBody

class GnjMoveStashListViewModel : BasePageViewModel() {

    val businessType = MutableLiveData("")
    val carrier = MutableLiveData("")
    val waybill = MutableLiveData("")

    val wbNoList = MutableLiveData<List<String>>()

    val businessTypeList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("转国内出港", "CICO"),
            KeyValue("转国际进港", "CIII"),
            KeyValue("转国际出港", "CIIO"),
        )
    )

    val itemViewHolder = GnjMoveStashListViewHolder::class.java
    val itemLayoutId = R.layout.item_gnj_move_stash_list

    val count = MutableLiveData(0)
    val number = MutableLiveData("0")
    val weight = MutableLiveData("0")

    // ========== 5.5 寸手持端专属字段（平板布局不绑定，默认值保证平板行为零变化） ==========

    /** 移库状态 Tab："0" 待移库（DomImpMove/search）/ "1" 已移库（DomImpMove/searchMoved） */
    val moveState = MutableLiveData("0")

    /** 手机筛选弹层：航班日期 / 航班号 / 特码（默认空 → 不进请求） */
    val flightDate = MutableLiveData("")
    val flightNo = MutableLiveData("")
    val spCode = MutableLiveData("")
    val spCodeList = MutableLiveData<List<KeyValue>>(emptyList())

    val moveStateTabs = MutableLiveData(
        listOf(KeyValue("待移库", "0"), KeyValue("已移库", "1"))
    )

    /** 状态 Tab 角标（与 [moveStateTabs] 等长，取两端点分页 total） */
    val moveStateCounts = MutableLiveData(listOf("", ""))

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

    /** 全选状态（手机 PhoneBottomBar 勾选图标） */
    val isAllChecked = MutableLiveData(false)

    /** 手机专属的额外请求（Tab 角标、特码字典）开关，仅手机形态在 Activity 中开启 */
    private var phoneExtrasEnabled = false

    fun initPhoneExtras() {
        phoneExtrasEnabled = true
        // 特码字典：flag=0 国内、ieFlag=I 进港（是否生效待实测，见问题清单）
        DictUtils.getSpecialCodeList(addAll = false, flag = 0, ieFlag = "I") { list ->
            spCodeList.postValue(listOf(KeyValue("全部", "")) + list)
        }
    }

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

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


    fun getWayBillList() {
        val requestBody = mapOf(
                "page" to pageModel.page,
            "limit" to pageModel.limit,
            "awbType" to businessType.value!!.ifEmpty { null },
            "wbNo" to waybill.value!!.ifEmpty { null },
            "carrier" to carrier.value!!.ifEmpty { null },
        ).toRequestBody()
        launchCollect({
            NetApply.api.getGnjMoveStashWbNoList(
                requestBody
            )
        }) {
            onSuccess = {
                val results = it.data!!
                when {
                    results.size == 1 -> {
                        waybill.value = results[0]
                        wbNoList.value = emptyList()
                    }
                    results.size > 1 -> {
                        wbNoList.value = results
                        showWbNoListSelect()
                    }
                    else -> {
                        wbNoList.value = emptyList()
                    }
                }
            }
            onFailed = { i: Int, s: String ->
                wbNoList.value = emptyList()
            }
        }

    }


    /** 查询条件（分页参数除外），search / searchMoved / searchTotal 三处共用同一套入参 */
    private fun buildFilterParams(): Map<String, Any?> = mapOf(
        "awbType" to businessType.value!!.ifEmpty { null },
        "wbNo" to waybill.value!!.ifEmpty { null },
        "carrier" to carrier.value!!.ifEmpty { null },
        // 以下为手机筛选弹层字段，平板恒为空串 → 恒传 null，行为不变
        "fdate" to flightDate.value?.ifEmpty { null },
        "fno" to flightNo.value?.ifEmpty { null },
        "spCode" to spCode.value?.ifEmpty { null },
    )

    override fun getData() {
        val body = (buildFilterParams() + mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
        )).toRequestBody()
        val moved = moveState.value == "1"
        launchLoadingCollect({
            // 平板 moveState 恒为 "0" → 恒走 search（原行为）；已移库 Tab 走 searchMoved
            if (moved) NetApply.api.getGnjMoveStashMovedList(body)
            else NetApply.api.getGnjMoveStashList(body)
        }) {
            onSuccess = {
                // searchMoved 出参无移库标识，按端点打标（卡片形态/详情移库信息卡依赖）
                it.list?.forEach { bean -> bean.isMoved = moved }
                pageModel.handleListBean(it) { updateCheckAllStatus() }
                count.value = it.total
            }
        }
        getCountData(body)
        if (phoneExtrasEnabled) loadTabCounts()
    }

    /** Tab 角标：search / searchMoved 各以 limit=1 查一次取分页 total（仅手机形态发起） */
    private fun loadTabCounts() {
        val body = (buildFilterParams() + mapOf("page" to 1, "limit" to 1)).toRequestBody()
        launchCollect({ NetApply.api.getGnjMoveStashList(body) }) {
            onSuccess = { updateTabCount(0, it.total) }
        }
        launchCollect({ NetApply.api.getGnjMoveStashMovedList(body) }) {
            onSuccess = { updateTabCount(1, it.total) }
        }
    }

    private fun updateTabCount(index: Int, total: Int?) {
        val current = moveStateCounts.value?.toMutableList() ?: mutableListOf("", "")
        if (index < current.size) {
            current[index] = (total ?: 0).toString()
            moveStateCounts.value = current
        }
    }

    // ========== 手机端全选 / 已选计数 ==========

    fun toggleSelectAll() {
        val list = pageModel.rv?.commonAdapter()?.items
            ?.filterIsInstance<MoveStashBean>() ?: return
        CheckUtil.handleAllCheck(list)
        updateCheckAllStatus()
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    fun updateCheckAllStatus() {
        val list = pageModel.rv?.commonAdapter()?.items
            ?.filterIsInstance<MoveStashBean>() ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
        selectedCount.value = list.count { it.checked.get() }.toString()
    }

    private fun getCountData(body: RequestBody) {
        launchCollect({
            NetApply.api.simplePost("DomImpMove/searchTotal", body)
        }) {
            onSuccess = {
                number.value = it.data?.totalPc.noNull("0")
                weight.value = it.data?.totalWeight.noNull("0")
            }
        }
    }

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

    fun moveStashClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<MoveStashBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        getTopActivity().showConfirmDialog("是否移库选中数据") {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "DomImpMove/move", mapOf(
                        "fid" to "0",
                        "ids" to filter.map { it.mawbId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("移库成功"))
                    refresh()
                }
            }
        }
    }

    fun checkAllClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<MoveStashBean>
        CheckUtil.handleAllCheck(list)
    }

    private fun showWbNoListSelect() {
        Common.singleSelect(
            DevUtils.getTopActivity(),
            "选择运单号",
            JSONArray.parseArray(wbNoList.value!!.map {
                mapOf(
                    "name" to it,
                    "code" to it,
                )
            }.toList().toJson(false)),
            null
        ) { position, _ ->
            waybill.value = wbNoList.value!![position]
        }
    }

}