package com.lukouguoji.aerologic.page.gnj.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.aerologic.page.gnj.stash.details.GnjStashDetailsActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GnjStashBean
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.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.noNull
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 okhttp3.RequestBody

class GnjStashListViewModel : BasePageViewModel() {

    val sort = MutableLiveData("0")

    // 代理人
    val agent = MutableLiveData("")

    // 承运人
    val carrier = MutableLiveData("")

    // 上一航程
    val lastFlight = MutableLiveData("")

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

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


    // 库位
    val stash = MutableLiveData("")

    val sortList = MutableLiveData<List<KeyValue>>(
        listOf(
            KeyValue("全部", ""),
            KeyValue("入库时间", "0"),
            KeyValue("航程", "1"),
            KeyValue("库位", "2"),
        )
    )
    val agentList = MutableLiveData<List<KeyValue>>(listOf(KeyValue("占位", "1"))).apply {
        DictUtils.getAgentList {
            value = it
        }
    }

    val itemViewHolder = GnjStashListViewHolder::class.java
    val itemLayoutId = R.layout.item_gnj_stash_list

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

    private val filterModel by lazy {
        PadFilterDialogModel(
            getTopActivity(), listOf(
                PadFilterModel(
                    stash,
                    "库位",
                    "请输入库位",
                    type = SearchLayoutType.INPUT
                )
            )
        ) {
            refresh()
        }
    }

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

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

    fun getWayBillList() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "agentCode" to agent.value,
            "carrier" to carrier.value,
            "by1" to carrier.value,
            "fdep" to lastFlight.value,
            "wbNo" to waybill.value,
            "location" to stash.value,
        ).toRequestBody()
        launchCollect({
            NetApply.api.getGnjStashWbNoList(
                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()
            }
        }
    }

    override fun getData() {
        val requestBody = mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit,
            "orderBy" to sort.value,
            "agentCode" to agent.value,
            "carrier" to carrier.value,
            "by1" to carrier.value,
            "fdep" to lastFlight.value,
            "wbNo" to waybill.value,
            "location" to stash.value,
        ).toRequestBody()
        launchLoadingCollect({
            NetApply.api.getGnjStashList(
                requestBody
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)

                getCountData(requestBody)
            }
        }
    }

    private fun getCountData(requestBody: RequestBody) {
        launchCollect({
            NetApply.api.simplePost("/DomImpWareHouse/total", requestBody)
        }) {
            onSuccess = {
                it.data?.let { data ->
                    count.value = data.total.noNull("0")
                    number.value = data.pc.noNull("0")
                    weight.value = data.weight.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)
                }
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as GnjStashBean
        GnjStashDetailsActivity.start(getTopActivity(), bean.whId)
    }

    fun filterClick() {
        filterModel.show()
    }


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