package com.lukouguoji.gnc.page.distribution.home

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.page.distribution.handover.GncDistributionHandoverActivity
import com.lukouguoji.gnc.page.distribution.home.dialog.GncDistributionBackDialogModel
import com.lukouguoji.gnc.page.distribution.home.dialog.GncDistributionDriverDialogModel
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GncDistributionBean
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.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.logi
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.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 dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils

class GncDistributionHomeViewModel : BasePageViewModel() {

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

    // 查询--开始日期
    val startDate = MutableLiveData(DateUtils.getCurrentTime().formatDate())
    // 查询--结束日期
    val endDate = MutableLiveData("")

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

    // 分配状态
    val distributionStatus = MutableLiveData("")

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

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

    val driver = MutableLiveData("")

    val fDest = MutableLiveData("")

    // 复磅状态列表
    val statusList = DictUtils.reWeightStatusList

    // 分配状态列表
    val distributionStatusList = DictUtils.distributionStatusList

    val driverList = MutableLiveData<List<KeyValue>>().apply {
        DictUtils.getDriverList {
            value = listOf(KeyValue("全部", "")) + it
        }
    }
    private var fDestList = MutableLiveData<List<KeyValue>>()

    val itemLayoutId = R.layout.item_gnc_distribution
    val itemViewHolder = GncDistributionHomeViewHolder::class.java

    private val filterDialogModel by lazy {
        PadFilterDialogModel(
            getTopActivity(), listOf(
                PadFilterModel(
                    data = driver,
                    title = "分配司机",
                    hint = "请选择司机",
                    SearchLayoutType.SPINNER,
                    driverList
                ),
                PadFilterModel(
                    data = status,
                    title = "复磅状态",
                    hint = "请选择复磅状态",
                    SearchLayoutType.SPINNER,
                    MutableLiveData(statusList)
                ),
                PadFilterModel(
                    data = fDest,
                    title = "目的站",
                    hint = "请选择目的站",
                    SearchLayoutType.SPINNER,
                    fDestList
                )
            )
        ) {
            refresh()
        }
    }

    val count = MutableLiveData("0")
    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getGncDistributionList(
                mapOf(
                    "pageNum" to pageModel.page,
                    "pageSize" to pageModel.limit,
                    "startTime" to startDate.value,
                    "endTime" to endDate.value,
                    "fno" to flightNo.value,
                    "allocationStatus" to distributionStatus.value,
                    "copStatus" to status.value,
                    "checkFlag" to status.value,
                    "carId" to car.value,
                    "allocationDriver" to driver.value,
                    "fdest" to fDest.value
                ).toRequestBody()
            )
        }) {
            onSuccess = {
                pageModel.handleListBean(it)
                count.value = it.total.toString()
            }
        }
    }

    /**
     * 平板车 扫描
     */
    fun carScan(view: View) {
        ScanModel.startScan(view.context.getActivity(), Constant.RequestCode.CAR)
    }

    fun onAllSelectClick() {
        CheckUtil.handleAllCheck(pageModel.rv!!.commonAdapter()!!.items as List<GncDistributionBean>)
    }

    fun onFilterClick() {
        filterDialogModel.show()
    }

    /**
     * 平板车 改变
     */
    fun onFnoChange() {
        if ((flightNo.value?.length ?: 0) <= 2) {
            fDestList.value = emptyList()
            fDest.value = ""
            return
        }
        launchCollect({
            NetApply.api.listFlightDest(
                mapOf(
                    "beginDate" to startDate.value,
                    "endDate" to endDate.value,
                    "fno" to flightNo.value,
                ).toRequestBody()
            )
        }) {
            onSuccess = { it ->
                val results = it.data!!
                fDest.value = ""
                when {
                    results.size == 1 -> {
                        fDestList.value = listOf(KeyValue(results[0], results[0]))
                    }
                    results.size > 1 -> {
                        fDestList.value =  results.map { iit -> KeyValue(iit, iit) } + listOf(KeyValue("全部", ""))
                    }
                    else -> {
                        fDestList.value = emptyList()
                    }
                }
            }
        }
//        fDestList.value = listOf(KeyValue("全部", ""), KeyValue("11", "11"))
    }

    fun onBackClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items.filter {
            (it as GncDistributionBean).checked.get()
        } as List<GncDistributionBean>
        if (list.isEmpty()) {
            showToast("请选择需要回退的数据")
            return
        }
        GncDistributionBackDialogModel(
            list.joinToString("、") { it.carId },
        ) { model ->
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "DomExpLoading/backTrans", mapOf(
                        "fdate" to model.date.value,
                        "fno" to model.fno.value,
                        "backDirection" to model.stash.value,
                        "useIdList" to list.map { b -> b.useId },
                        "driver" to model.driver.value,
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("回退成功"))
                    refresh()
                }
            }
        }.show()
    }

    /**
     * 单证交接 点击
     */
    fun onHandoverClick() {
        GncDistributionHandoverActivity.start(getTopActivity())
    }

    /**
     * 分配 点击
     */
    fun onDistributionClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items.filter {
            (it as GncDistributionBean).checked.get()
        } as List<GncDistributionBean>
        if (list.isEmpty()) {
            showToast("请选择需要分配的数据")
            return
        }
        GncDistributionDriverDialogModel(
            list.joinToString("、") { it.carId },
            driverList.value?.filter { it.value != "" } ?: emptyList()
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "DomExpLoading/allocationDriver", mapOf(
                        "driver" to it.driver.value,
                        "useIdList" to list.map { b -> b.useId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("分配成功"))
                    refresh()
                }
            }
        }.show(getTopActivity())
    }


    fun onAddCargo() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val list = (adapter.items as List<GncDistributionBean>).filter { it.checked.get() }
        if (list.isEmpty()) {
            showToast("请选中需要补充机位的信息!")
            return
        }
        getTopActivity().showConfirmDialog("是否确认加货？") {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    url = "DomExpLoading/addCargo",
                    mapOf(
                        "useIdList" to list.map { it.useId },
                    ).toRequestBody()
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("设置待加货成功"))
                    refresh()
                }
            }
        }
    }

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


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