package com.lukouguoji.gnc.page.query.list

import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.page.query.details.GncQueryDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncQueryBean
import com.lukouguoji.module_base.bean.SimpleCheckBean
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.formatDate
import com.lukouguoji.module_base.ktx.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.toJson
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.PadFilterDialogModel
import com.lukouguoji.module_base.model.PadFilterModel
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.ui.weight.search.layout.SearchLayoutType
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.DictUtils
import dev.DevUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import okhttp3.RequestBody

class GncQueryListViewModel : BasePageViewModel() {

    // 日期
    val date = MutableLiveData(DateUtils.getCurrentTime().formatDate())
    val dateEnd = MutableLiveData("")

    // 运单号
    val waybill = MutableLiveData("")

    // 运单号列表
    val wbNoList = MutableLiveData<List<String>>()

    // 日期类型
    val dateType = MutableLiveData("0")
    val dateTypeList = MutableLiveData(
        listOf(
            KeyValue("入库", "0"),
            KeyValue("离港", "1"),
        )
    )

    // 特码
    val spCode = MutableLiveData("")
    val spCodeList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getSpecialCodeList(parentcode = "ALL") {
            value = it
        }
    }

    // 代理
    val agent = MutableLiveData("")
    val agentList = MutableLiveData(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getGncAgentList {
            value = it
        }
    }

    // 航班号
    val fNo = MutableLiveData("")

    // 目的港
    val dest = MutableLiveData("")

    // 运单类型
    val waybillType = MutableLiveData("")
    val waybillTypeList = MutableLiveData(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getWaybillTypeList2(ieFlag = "E", type = "Co") {
            value = it
        }
    }

    // 业务类型
    val businessType = MutableLiveData("")
    val businessTypeList = MutableLiveData(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getBusinessTypeList(type = "CO") {
            value = it
        }
    }

    // 危险品描述
    val wxDesc = MutableLiveData("")
    val wxDescList = MutableLiveData(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getWxDescList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }

    // 危险品库
    val wxKuType = MutableLiveData("")
    val wxKuTypeList = MutableLiveData(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getWxKuList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }

    // 品名
    val goodsName = MutableLiveData("")

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

    private val filterDialogModel: PadFilterDialogModel by lazy {
        PadFilterDialogModel(
            DevUtils.getTopActivity(), listOf(
                PadFilterModel(
                    data = agent,
                    title = "代理",
                    hint = "请选择代理",
                    type = SearchLayoutType.SPINNER,
                    list = agentList
                ),
                PadFilterModel(
                    data = fNo,
                    title = "航班号",
                    hint = "请输入航班号",
                    forcedCap = true
                ),
                PadFilterModel(
                    data = dest,
                    title = "目的港",
                    hint = "请输入目的港",
                    forcedCap = true
                ),
                PadFilterModel(
                    data = waybillType,
                    title = "运单类型",
                    hint = "请选择运单类型",
                    type = SearchLayoutType.SPINNER,
                    list = waybillTypeList
                ),
                PadFilterModel(
                    data = businessType,
                    title = "业务类型",
                    hint = "请选择业务类型",
                    type = SearchLayoutType.SPINNER,
                    list = businessTypeList
                ),
                PadFilterModel(
                    data = wxDesc,
                    title = "危险品描述",
                    hint = "请选择危险品描述",
                    type = SearchLayoutType.SPINNER,
                    list = wxDescList
                ),
                PadFilterModel(
                    data = wxKuType,
                    title = "危险品库",
                    hint = "请选择危险品库",
                    type = SearchLayoutType.SPINNER,
                    list = wxKuTypeList
                ),
                PadFilterModel(data = goodsName, title = "品名", hint = "请输入品名"),
            )
        ) {
            refresh()
        }
    }

    val itemLayoutId = R.layout.item_gnc_query_list
    val itemViewHolder = GncQueryListViewHolder::class.java

    val countDesc = MutableLiveData("合计：0条，总件数：0，总重量：0KG")

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


    fun getWayBillList() {
        val body = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "beginDate" to date.value,
            "endDate" to dateEnd.value,
            // 日期类型
            "dateType" to dateType.value,
            "spCode" to spCode.value,
            "wbNo" to waybill.value,
            "agentCode" to agent.value,
            "fno" to fNo.value,
            "dest" to dest.value,
            "awbType" to waybillType.value,
            "businessType" to businessType.value,
            "dgrDetail" to wxDesc.value,
            "dgrLocation" to wxKuType.value,
            "goods" to goodsName.value,
        ).toRequestBody()
        launchCollect({
            NetApply.api.getWbNoList(
                "/DomExpSearch/searchWbList",
                body
            )
        }) {
            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()
            }
        }
    }

    override fun getData() {
        val body = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "beginDate" to date.value,
            "endDate" to dateEnd.value,
            // 日期类型
            "dateType" to dateType.value,
            "spCode" to spCode.value,
            "wbNo" to waybill.value,
            "agentCode" to agent.value,
            "fno" to fNo.value,
            "dest" to dest.value,
            "awbType" to waybillType.value,
            "businessType" to businessType.value,
            "dgrDetail" to wxDesc.value,
            "dgrLocation" to wxKuType.value,
            "goods" to goodsName.value,
        ).toRequestBody()
        launchLoadingCollect({
            NetApply.api.getGncQueryList(
                body
            )
        }) {
            onSuccess = {
                it.data?.let { data ->
                    pageModel.handleListBean(data)
                    count.value = data.total
                    getCountData(body)
                }
            }
        }
    }

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

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

    fun onFilterClick() {
        filterDialogModel.show()
    }

    override fun onItemClick(position: Int, type: Int) {
        val bean = pageModel.rv!!.commonAdapter()!!.getItem(position) as GncQueryBean
        GncQueryDetailsActivity.start(getTopActivity(), bean.mawbId)
    }

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