package com.lukouguoji.aerologic.page.gnj.manifest.list

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.aerologic.R
import com.lukouguoji.aerologic.page.gnj.manifest.add.GnjManifestAddActivity
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.FlightBean
import com.lukouguoji.module_base.bean.GnjManifestBean
import com.lukouguoji.module_base.common.Constant
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.launchCollect
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.model.ConfirmDialogModel
import com.lukouguoji.module_base.util.CheckUtil
import dev.utils.common.DateUtils
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class GnjManifestListViewModel : BasePageViewModel() {

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

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

    val itemViewHolder = GnjManifestListViewHolder::class.java
    val itemLayoutId = R.layout.item_gnj_manifest_list

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

    val flightBean = MutableLiveData(FlightBean())

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

    fun onCreated() {
        FlowBus.with<Any>(Constant.Key.FNJ_MANIFEST_ADD)
            .onEach {
                refresh()
            }.launchIn(viewModelScope)
    }

    override fun getData() {
        if (date.value.verifyNullOrEmpty("请选择航班日期")
            || fNo.value.verifyNullOrEmpty("请输入航班号")
        ) {
            return
        }
        launchCollect({
            NetApply.api.getGnFlightBean(
                mapOf(
                    "fdate" to date.value,
                    "fno" to fNo.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                flightBean.value = it.data ?: FlightBean()
                launchLoadingCollect({
                    NetApply.api.getGnjManifestList(
                        mapOf(
                            "page" to pageModel.page,
                            "limit" to pageModel.limit,
                            "fdate" to date.value,
                            "fno" to fNo.value,
                            "fid" to flightBean.value?.fid,
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = { res ->
                        pageModel.handleListBean(res)
                        count.value = res.total

                        getCountData()
                    }
                }
            }

            onFailed = { _, message ->
                showToast(message)
                flightBean.value = FlightBean()
            }
        }

    }

    private fun getCountData() {
        launchCollect({
            NetApply.api.getGnjManifestCount(flightBean.value?.fid.noNull())
        }) {
            onSuccess = {
                number.value = it.data?.totalPc.noNull("0")
                weight.value = it.data?.totalWeight.noNull("0")
            }
        }
    }

    /**
     * 查询航班信息
     */
    fun queryFlight() {

    }

    fun addClick() {
        if (verifyNoFlight()) {
            showToast("该航班信息不存在，请核实！")
            return
        }
        val bean = flightBean.value!!
        GnjManifestAddActivity.start(
            getTopActivity(),
            fid = bean.fid,
            dep = bean.fdep,
            dest = bean.fdest
        )
    }

    private fun verifyNoFlight() = flightBean.value == null || flightBean.value!!.fid.isEmpty()

    fun deleteClick() {
        pageModel.rv?.commonAdapter()?.let {
            val list =
                it.items.filter { b -> (b as GnjManifestBean).checked.get() } as List<GnjManifestBean>
            if (list.isNotEmpty()) {
                ConfirmDialogModel("确定删除选中的数据吗？") {
                    launchLoadingCollect({
                        NetApply.api.anyPost(
                            "DomImpManiFest/deleteList",
                            list.map { b -> b.mfId }.toRequestBody()
                        )
                    }) {
                        onSuccess = { result ->
                            showToast(result.msg.noNull("删除成功"))
                            refresh()
                        }
                    }
                }.show()
            } else {
                showToast("请选择需要删除的数据")
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as GnjManifestBean
        when (type) {
            R.id.tv_delete -> {
                ConfirmDialogModel("是否删除该条记录？") {
                    launchLoadingCollect({
                        NetApply.api.anyPostForId("/DomImpManiFest/deleteFest", bean.mfId)
                    }) {
                        onSuccess = {
                            showToast(it.msg.noNull("删除成功"))
                            refresh()
                        }
                    }
                }.show()
            }

            R.id.tv_modify -> {
                GnjManifestAddActivity.start(getTopActivity(), bean.mfId, modify = true)
            }

            R.id.ll -> {
                GnjManifestAddActivity.start(getTopActivity(), bean.mfId)
            }

            else -> {}
        }
    }

    fun checkAllClick() {
        pageModel.rv?.commonAdapter()?.let {
            CheckUtil.handleAllCheck(it.items as List<GnjManifestBean>)
        }
    }

    fun sendClick() {
        val list = (pageModel.rv!!.commonAdapter()!!.items as List<GnjManifestBean>).filter {
            it.checked.get()
        }
        if (list.isEmpty()) {
            showToast("请选择数据")
            return
        }
        launchLoadingCollect({
            NetApply.api.anyPost("DomImpManiFest/provide", mapOf(
                "fid" to flightBean.value?.fid,
                "ids" to list.map { b -> b.mfId }
            ).toRequestBody())
        }) {
            onSuccess = {
                showToast(it.msg.noNull("货物发放成功"))
                refresh()
            }
        }
    }
}