package com.lukouguoji.aerologic.page.transport

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.aerologic.R
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GoodsTransportBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.interfaces.ICheck
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.formatDate
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.toRequestBody
import com.lukouguoji.module_base.model.GoodsTransportModifyDialogModel
import com.lukouguoji.module_base.model.GoodsTransportReturnDialogModel
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.DictUtils
import com.lukouguoji.module_base.util.HandlerUtils
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils

class GoodsTransportViewModel : BasePageViewModel() {

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

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

    // 司机
    val driver = MutableLiveData("")

    // 类型
    val type = MutableLiveData("")

    // 状态
    val status = MutableLiveData("")

    // 板车号
    val car = MutableLiveData("")

    // 状态列表
    val statusList = MutableLiveData<List<KeyValue>>(emptyList()).apply {
        DictUtils.getTransStatusList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }

    // 司机列表
    val driverList = MutableLiveData<List<KeyValue>>(emptyList()).apply {
        DictUtils.getDriverList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }

    // 类型列表
    val typeList = MutableLiveData<List<KeyValue>>(emptyList()).apply {
        DictUtils.getTransTypeListByRole {
            value = it
            type.value = it.firstOrNull()?.value ?: ""
            refresh()
        }
    }

    val itemLayoutId = R.layout.item_goods_transport
    val itemViewHolder = GoodsTransportViewHolder::class.java

    private val filterModel by lazy {
        PadFilterDialogModel(
            getTopActivity(), listOf(
                PadFilterModel(
                    driver,
                    title = "司机",
                    list = driverList,
                    type = SearchLayoutType.SPINNER,
                    hint = "请选择司机"
                )
            )
        ) {
            refresh()
        }
    }

    val count = MutableLiveData("0")

    // 补位补充是否可用
    val supplementEnable = MutableLiveData(false)

    // 确认按钮是否可用
    val confirmEnable = MutableLiveData(true)

    // 退回按钮是否可用
    val returnEnable = MutableLiveData(false)

    // 确认文字
    val confirmText = MutableLiveData("开始运输")

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

    override fun getData() {
        if(type.value.isNullOrEmpty()){
            return
        }
        launchLoadingCollect({
            NetApply.api.getGoodsTransportList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "fdate" to date.value,
                    "fno" to flightNo.value,
                    "transStatus" to status.value,
                    "transType" to type.value,
                    "driver" to driver.value,
                    "carId" to car.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total.toString()
                HandlerUtils.postRunnable({
                    computeEnableState()
                }, 100)
            }
        }
    }

    /**
     * 平板车 扫描
     */
    fun carScan() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.CAR)
    }

    /**
     * 全选
     */
    fun onAllSelectClick() {
        val list = getAdapter().items as List<GoodsTransportBean>
        if (list.groupBy { it.transStatus }.size > 1 || list.groupBy { it.endFlag }.size > 1) {
            showToast("数据存在多种状态,无法全选")
            return
        }
        CheckUtil.handleAllCheck(pageModel.rv!!.commonAdapter()!!.items as List<ICheck>)
        computeEnableState()
    }

    fun onFilterClick() {
        filterModel.show()
    }

    fun onAddCargo() {
        val list = (getAdapter().items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要补充机位的平板车信息!")
            return
        }
        getTopActivity().showConfirmDialog("是否完成加货?") {
            var canAddCargo = true
            for (obj in list) {
                if (obj.addCargoFlag != "1") {
                    showToast("平板车不可加货!")
                    canAddCargo = false
                    break
                }
            }
            if (canAddCargo) {
                launchLoadingCollect({
                    NetApply.api.anyPost(
                        url = "DomExpLoading/updateAddCargo",
                        mapOf(
                            "useIdList" to list.map { it.useId },
                        ).toRequestBody()
                    )
                }) {
                    onSuccess = {
                        showToast(it.msg.noNull("完成加货成功"))
                        refresh()
                    }
                }
            }
        }
    }

    fun returnClick() {
        val list = (getAdapter().items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选择数据")
            return
        }
        val inOutStatus = list.first().status
        GoodsTransportReturnDialogModel(
            list.joinToString("、") { it.carId }
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = if (inOutStatus == "0") "DomExpLoading/backTrans" else "unloadingAirCraft/backTrans",
                    mapOf(
                        "backDirection" to it.data.value,
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId }
                    ).toRequestBody())
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("退回成功"))
                    refresh()
                }
            }
        }.show()
    }

    fun onSupplementClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要补充机位的平板车信息!")
            return
        }
        val inOutStatus = list.first().status
        GoodsTransportModifyDialogModel(
            list.joinToString("、") { it.carId }
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = "DomExpLoading/updateStandId",
                    mapOf(
                        "status" to inOutStatus,
                        "standId" to it.data.value,
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("补充机位成功"))
                    refresh()
                }
            }
        }.show()
    }

    fun onConfirmClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GoodsTransportBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要转运的平板车信息!")
            return
        }
        val inOutStatus = list.first().status
        getTopActivity().showConfirmDialog("是否确定${confirmText.value}？") {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = if (inOutStatus == "0") {
                        if (confirmText.value == "开始运输") "/DomExpLoading/startTrans" else "/DomExpLoading/finishTrans"
                    } else {
                        if (confirmText.value == "开始运输") "/unloadingAirCraft/startTrans" else "/unloadingAirCraft/finishTrans"
                    },
                    mapOf(
                        "fdate" to date.value,
                        "transType" to list.first().transType,
                        "useIdList" to list.map { it.useId }
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("操作成功"))
                    refresh()
                }
            }
        }
    }

    override fun onItemClick(position: Int, type: Int) {
        val list = getAdapter().items as List<GoodsTransportBean>
        val bean = list[position]
        if (!bean.canReturn() && bean.endFlag == "1") {
            // 不能退回且已结束的数据不允许点击
            return
        }
        when (type) {
            R.id.iv_icon -> {
                val checkedStatus = list.firstOrNull { it.checked.get() }?.transStatus ?: ""
                // 没有选中,或选中状态一致,则处理逻辑
                if (checkedStatus.isEmpty() || checkedStatus == bean.transStatus) {
                    bean.checked.set(!bean.checked.get())
                }
            }

            else -> {}
        }
        computeEnableState()
    }

    /**
     * 计算可用信息
     */
    private fun computeEnableState() {
        val list = getAdapter().items as List<GoodsTransportBean>
        // 补充机位是否可用
        supplementEnable.value = list.firstOrNull()?.transType in listOf("2", "8", "9")

        loge("判断补充机位是否可用 : ${supplementEnable.value}")
        // 选中结束状态的数据,则不展示
        confirmEnable.value = list.firstOrNull { it.checked.get() }?.endFlag != "1"
        // 确认是否可用
        confirmText.value = if (list.firstOrNull { it.checked.get() }?.transStatus == "1") {
            "完成运输"
        } else {
            "开始运输"
        }

        // 退回是否可用
//        returnEnable.value = list.firstOrNull { it.checked.get() }?.canReturn() == true
    }

    private fun getAdapter() = pageModel.rv!!.commonAdapter()!!

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

                else -> {}
            }
        }
    }
}