package com.lukouguoji.gnj.page.yiku.list

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.gnj.R
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GnjYiKuBean
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 dev.DevUtils
import dev.utils.app.info.KeyValue
import okhttp3.RequestBody

/**
 * 国内进港移库列表 ViewModel
 */
class GnjYiKuListViewModel : BasePageViewModel() {

    // 搜索条件
    val waybillType = MutableLiveData("")         // 运单类型
    val carrier = MutableLiveData("")             // 承运人
    val waybillNo = MutableLiveData("")           // 运单号
    val handoverStatus = MutableLiveData("")      // 移交状态

    // 运单号列表（用于多条结果选择）
    val wbNoList = MutableLiveData<List<String>>()

    // 运单类型下拉列表
    val waybillTypeList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("转国际进港", "CIII"),
            KeyValue("转国内出港", "CICO"),
            KeyValue("转国际出港", "CIIO"),
        )
    )

    // 移交状态下拉列表
    val handoverStatusList = MutableLiveData(
        listOf(
            KeyValue("全部", ""),
            KeyValue("未移交", "0"),
            KeyValue("已移交", "1"),
        )
    )

    // 适配器配置
    val itemViewHolder = GnjYiKuListViewHolder::class.java
    val itemLayoutId = R.layout.item_gnj_yiku_list

    // 统计数据
    val count = MutableLiveData(0)      // 总票数
    val totalPc = MutableLiveData("0")  // 总件数
    val totalWeight = MutableLiveData("0")  // 总重量

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

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

    /**
     * 获取运单号列表（用于扫码或输入后模糊查询）
     */
    fun getWayBillList() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "awbType" to waybillType.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            "carrier" to carrier.value!!.ifEmpty { null },
            "handoverStatus" to handoverStatus.value!!.ifEmpty { null },
        ).toRequestBody()

        launchCollect({
            NetApply.api.getGnjMoveStashWbNoList(requestBody)
        }) {
            onSuccess = {
                val results = it.data!!
                when {
                    results.size == 1 -> {
                        waybillNo.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()
            }
        }
    }

    /**
     * 获取列表数据
     */
    override fun getData() {
        val body = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "awbType" to waybillType.value!!.ifEmpty { null },
            "wbNo" to waybillNo.value!!.ifEmpty { null },
            "carrier" to carrier.value!!.ifEmpty { null },
            "handoverStatus" to handoverStatus.value!!.ifEmpty { null },
        ).toRequestBody()

        launchLoadingCollect({
            NetApply.api.getGnjMoveStashList(body)
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total
            }
        }
        getCountData(body)
    }

    /**
     * 获取统计数据
     */
    private fun getCountData(body: RequestBody) {
        launchCollect({
            NetApply.api.simplePost("DomImpMove/searchTotal", body)
        }) {
            onSuccess = {
                totalPc.value = it.data?.totalPc.noNull("0")
                totalWeight.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 -> {
                    waybillNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }

    /**
     * 批量移库操作
     */
    fun moveStashClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GnjYiKuBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        getTopActivity().showConfirmDialog("确定要移库选中的 ${filter.size} 条数据吗？") {
            launchLoadingCollect({
                NetApply.api.transferGnjYiKu(
                    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<GnjYiKuBean>
        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, _ ->
            waybillNo.value = wbNoList.value!![position]
        }
    }
}
