package com.lukouguoji.gnc.page.assemble.add

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSONArray
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.page.assemble.unload.GncAssembleUnloadListActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlatcarBean
import com.lukouguoji.module_base.bean.GncAssembleListBean
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.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.loge
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.Common
import dev.DevUtils
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class GncAssembleAddViewModel : BasePageViewModel() {

    private var id = ""

    // 平板车
    val car = MutableLiveData<String>()

    // 运单号
    val waybill = MutableLiveData<String>()

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

    // 平板车信息
    val flatcarBean = MutableLiveData(FlatcarBean())

    // 数量
    val count = MutableLiveData(0)

    // 总件数
    val totalCount = MutableLiveData(0)

    // 总重量
    val totalWeight = MutableLiveData(0.0)

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

    fun initOnCreated(intent: Intent) {
        intent.getStringExtra(Constant.Key.DATA)?.let {
            val bean = NetApply.gson.fromJson(it, GncAssembleListBean::class.java)
            id = bean.useId
            bean.warehouseList?.forEach { b ->
                insertWaybill(b)
            }
            car.value = bean.carId
            onCarChange()
        }

        FlowBus.with<List<WaybillBean>>(ConstantEvent.WAYBILL_CHECKED)
            .onEach {
                it.forEach { bean ->
                    insertWaybill(bean)
                }
            }
            .launchIn(viewModelScope)
    }

    override fun getData() {}

    fun onFilterClick() {
        GncAssembleUnloadListActivity.start(getTopActivity())
    }

    /**
     * 平板车 改变
     */
    fun onCarChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        val carid = car.value ?: return
        if (carid.isEmpty()) return

        if (carid.startsWith("x") || carid.startsWith("X")) {
            flatcarBean.value = FlatcarBean().apply {
                carId = carid
                carWeight = "0"
                signWeight = "0"
                maxWeight = "0"
            }
            return
        }

        launchLoadingCollect({
            NetApply.api.getFlatcarInfo(carid)
        }) {
            onSuccess = {
                flatcarBean.value = it.data ?: FlatcarBean()
                if (id.isEmpty()) {
                    // 根据carId查询flatcaruse表中数据
                    launchCollect({
                        NetApply.api.getGncAssembleList(
                            mapOf(
                                "pageNum" to 1,
                                "pageSize" to 1,
                                "carId" to car.value,
                                "activited" to 0
                            ).toRequestBody()
                        )
                    }) {
                        onSuccess = { iit ->
                            val bean = iit.list?.get(0)
                            if (bean != null) {
                                id = bean.useId
                                bean.warehouseList?.forEach { b ->
                                    insertWaybill(b)
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fun onCarScanClick() {
        ScanModel.startScan(
            getTopActivity(),
            Constant.RequestCode.CAR
        )
    }

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

    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as WaybillBean
        when (type) {
            R.id.tv_batch -> {
                if (car.value.isNullOrEmpty()){
                    showToast("请先选择平板车！")
                    return
                }
                GncAssembleBatchDialogModel(bean) {
                    adapter.removeItem(adapter.items.indexOf(bean))
                    getListForWaybillAndInsertForBatch(bean.whId)
                }.show()
            }

            R.id.tv_delete -> {
                getTopActivity().showConfirmDialog("是否删除该条数据?") {
                    adapter.removeItem(position)
                }
            }

            else -> {}
        }
    }

    /**
     * 运单号 改变
     */
    fun onWaybillChange(focused: Boolean = false) {
        if (focused) {
            return
        }
        val code = waybill.value.noNull()
        if(code.isNullOrEmpty()){
            return
        }
        getListForWaybillByCode(code)
    }

    /**
     * 分批后将修改后的仓库记录加入到列表中
     */
    private fun getListForWaybillAndInsertForBatch(code: String) {
//        if (code.length != 11) return
        launchLoadingCollect({
            NetApply.api.getWaybillList(
                "/DomExpLoading/queryWarehouseList",
                mapOf("whId" to code).toRequestBody()
            )
        }) {
            onSuccess = {
                it.list?.forEach { bean ->
                    loge("bean:{}")
                    insertWaybill(bean)
//                    if (bean.location.isNotBlank() && bean.location == flatcarBean.value?.carId){
//                        insertWaybill(bean)
//                    }

                }
            }
        }
    }


    private fun getListForWaybillAndInsert(code: String) {
//        if (code.length != 11) return
        launchLoadingCollect({
            NetApply.api.getWaybillList(
                "/DomExpLoading/queryWarehouse",
                mapOf("whId" to code).toRequestBody()
            )
        }) {
            onSuccess = {
                it.list?.forEach { bean ->
                    insertWaybill(bean)
                }
            }
        }
    }

    private fun getListForWaybillByCode(code: String) {
//        if (code.length != 11) return
        launchLoadingCollect({
            NetApply.api.getWaybillList(
                "/DomExpLoading/queryWarehouse",
                mapOf("wbNo" to code).toRequestBody()
            )
        }) {
            onSuccess = {
                it.list?.forEach { bean ->
                    insertWaybill(bean)
                }
            }
        }
    }



    fun getWaybillList(code: String) {
        if (code.length < 4 || code.length > 8) return
        launchCollect({
            NetApply.api.getWbNoList(
                "/DomExpLoading/queryWarehouseWbList",
                mapOf("wbNo" to code).toRequestBody()
            )
        }) {
            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()
            }
        }
    }

    private fun insertWaybill(bean: WaybillBean) {
        loge("插入数据 ${bean.whId}")
        pageModel.rv?.post {
            pageModel.rv?.commonAdapter()?.let {
                loge("")
                val list = it.items as List<WaybillBean>
                if (list.find { b -> b.whId == bean.whId } == null) {
                    bean.checked.set(false)
                    it.addItem(bean)
                }
            }

            computeCountData()
        }
    }

    private fun computeCountData() {
        var c = 0
        var num = 0
        var w = 0.0
        pageModel.rv?.commonAdapter()?.items?.forEach {
            val bean = it as WaybillBean
            c += 1
            num += (bean.pc.toIntOrNull() ?: 0)
            w += (bean.weight.toDoubleOrNull() ?: 0.0)
        }
        count.value = c
        totalCount.value = num
        totalWeight.value = w
    }

    /**
     * 合并点击
     */
    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("合并成功"))
                val code = list.first().whId
                // 删除合并的数据
                list.forEach { bean ->
                    val adapter = pageModel.rv!!.commonAdapter()!!
                    adapter.removeItem(adapter.items.indexOf(bean))
                }
                // 查询运单下所有数据并插入
                getListForWaybillAndInsert(code)
            }
        }
    }

    /**
     * 装货 点击
     */
    fun onLoadingClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = adapter.items as List<WaybillBean>
        val distinctByWbNo = list.distinctBy { it.wbNo }
        if (list.size != distinctByWbNo.size) {
            showToast("请将相同运单号的货物合并后再进行装货!")
            return
        }
        if (list.isEmpty()) {
            showToast("请添加需要装货的数据!")
            return
        }
        launchLoadingCollect({
            if (id.isEmpty()) {
                NetApply.api.anyPost(
                    "DomExpLoading/insertLoading", mapOf(
                        "carId" to flatcarBean.value?.carId,
                        "warehouseList" to list.map { b ->
                            mapOf("whId" to b.whId)
                        }
                    ).toRequestBody()
                )
            } else {
                NetApply.api.anyPost(
                    "DomExpLoading/updateLoading", mapOf(
                        "useId" to id,
                        "carId" to flatcarBean.value?.carId,
                        "warehouseList" to list.map { b ->
                            mapOf("whId" to b.whId)
                        }
                    ).toRequestBody()
                )
            }
        }) {
            onSuccess = {
                showToast(it.msg.noNull("装货成功"))
                adapter.refresh(emptyList())
                flatcarBean.value = FlatcarBean()
                car.value = ""
                computeCountData()
            }
        }
    }

    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.CAR -> {
                    val id = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                    car.value = id
                    onCarChange()
                }

                Constant.RequestCode.WAYBILL -> {
                    val id = data.getStringExtra(Constant.Result.CODED_CONTENT).noNull()
                    waybill.value = id
                    onWaybillChange()
                }

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

}