package com.lukouguoji.gnc.page.assemble.unload

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.page.assemble.add.GncAssembleAddViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GjcWaybillBean
import com.lukouguoji.module_base.bean.WaybillBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.getActivity
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.refresh
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.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.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 dev.utils.common.DateUtils
import java.util.Collections.emptyList

class GncAssembleUnloadListViewModel : BasePageViewModel() {

    val date = MutableLiveData("")
    val fno = MutableLiveData("")

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

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

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

    // 特码
    val specialCode = MutableLiveData("")

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

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

    val agentList = MutableLiveData<List<KeyValue>>(emptyList()).apply {
        DictUtils.getGncAgentList(addAll = false) {
            value = it
        }
    }
    val specialCodeList = MutableLiveData<List<KeyValue>>(emptyList()).apply {
        DictUtils.getSpecialCodeList(addAll = false) {
            val list = arrayListOf<KeyValue>()
            it.find { b -> b.key.contains("普通货物") }?.let { b ->
                list.add(b)
            }
            list.addAll(it.filter { b -> !b.key.contains("普通货物") })
            value = it
        }
    }

    // 选中条数
    val count = MutableLiveData(0)
    // 是否只可查看---从国内出港组装页面进入即为false
    val modify = MutableLiveData(true)

    val itemLayoutId = R.layout.item_gnc_assemble_add_no_right
    val itemViewHolder = GncAssembleUnloadViewHolder::class.java

    private val filterModel by lazy {
        PadFilterDialogModel(
            DevUtils.getTopActivity(), listOf(
                PadFilterModel(
                    agent,
                    title = "代理",
                    hint = "请选择代理",
                    type = SearchLayoutType.SPINNER,
                    list = agentList
                ),
                PadFilterModel(
                    specialCode,
                    title = "特码",
                    hint = "请选择特码",
                    type = SearchLayoutType.SPINNER,
                    list = specialCodeList
                ),
            )
        ) {
            refresh()
        }
    }

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

    fun getWayBillList() {
        val body = mapOf(
            "pageNum" to pageModel.page,
            "pageSize" to pageModel.limit,
            "dest" to dest.value,
            "agentCode" to agent.value,
            "spCode" to specialCode.value,
            "wbNo" to waybill.value,
            "fdate" to date.value,
            "fno" to fno.value,
            "by1" to carrier.value,
        ).toRequestBody()
        launchCollect({
            NetApply.api.getWbNoList(
                "/DomExpLoading/queryWarehouseWbList",
                body
            )
        }) {
            onSuccess = {
                val results = it.data!!
                when {
                    results.size == 1 -> {
                        waybill.value = results[0]
                        wbNoList.value = kotlin.collections.emptyList()
                    }
                    results.size > 1 -> {
                        wbNoList.value = results
                        showWbNoListSelect()
                    }
                    else -> {
                        wbNoList.value = kotlin.collections.emptyList()
                    }
                }
            }
            onFailed = { i: Int, s: String ->
                wbNoList.value = kotlin.collections.emptyList()
            }
        }
    }


    fun initOnCreated(intent: Intent) {
        modify.value = intent.getBooleanExtra(Constant.Key.MODIFY, true)
        getData()
    }

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getWaybillList(
                "/DomExpLoading/queryWarehouse", mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "dest" to dest.value,
                    "agentCode" to agent.value,
                    "spCode" to specialCode.value,
                    "wbNo" to waybill.value,
                    "fdate" to date.value,
                    "fno" to fno.value,
                    "by1" to carrier.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                if (modify.value == false) {
                    it.list?.forEach { iit -> iit.needCheck = false }
                }
                pageModel.handleListBean(it)
                count.value = it.total
            }
        }
    }

    /**
     * 搜索点击
     */
    fun searchClick(view: View) {
        refresh()
    }

    fun filterClick() {
        filterModel.show()
    }

    /**
     * 运单号 扫描
     */
    fun waybillNoScanClick(view: View) {
        ScanModel.startScan(view.context.getActivity(), Constant.RequestCode.WAYBILL)
    }

    /**
     * 全选 点击
     */
    fun checkAllClick(view: View) {
        CheckUtil.handleAllCheck(
            pageModel.rv?.commonAdapter()?.items as? List<GjcWaybillBean> ?: emptyList()
        )
    }

    fun onMergeClick() {
        val list = getCheckedList()
        if (list.size < 2) {
            showToast("请选择两个以上数据")
            return
        }
        if (list.groupBy { it.wbNo }.size > 1) {
            showToast("合并数据运单号必须一致")
            return
        }
        if (list.groupBy { it.dest }.size > 1) {
            showToast("合并数据目的港必须一致")
            return
        }
        launchLoadingCollect({
            NetApply.api.anyPost(
                "DomExpLoading/mergeWarehouseList",
                list.map { it.whId }.toRequestBody()
            )
        }) {
            onSuccess = {
                showToast(it.msg.noNull("合并成功"))
                refresh()
            }
        }
    }

    fun onConfirmClick() {
        val list = getCheckedList()
        if (list.isEmpty()) {
            showToast("请选择数据")
            return
        }
        FlowBus.with<List<WaybillBean>>(ConstantEvent.WAYBILL_CHECKED)
            .tryEmit(list)
        getTopActivity().finish()
    }

    private fun getCheckedList(): List<WaybillBean> {
        return (pageModel.rv?.commonAdapter()?.items?.filter { (it as WaybillBean).checked.get() }
            ?: emptyList()) as List<WaybillBean>
    }

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

                else -> {}
            }
        }
    }

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

}