package com.sixin.module_p.ui.gnj.xieji.details

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.GnjUnloadListBean
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.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.sixin.module_p.R
import android.view.View
import android.widget.CompoundButton
import androidx.databinding.ObservableBoolean
import com.lukouguoji.module_base.interfaces.ICheck
import com.lukouguoji.module_base.util.CheckUtil


class PdaGnjXieJiDetailsViewModel : BasePageViewModel() {
    // 详情信息
    val dataBean = MutableLiveData<GnjUnloadListBean>()

    //    单证交警--类型
    val handover = MutableLiveData("")

    val itemViewHolder = PdaGnjXieJiDetailsViewHolder::class.java
    val itemLayoutId = R.layout.item_pda_gnj_xieji_car_list

    // 确认按钮是否可用
    val confirmEnable = MutableLiveData(true)
    val isAllSelected = MutableLiveData(false)
//    val carList = MutableList(List<GnjUnloadListBean>)

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

    fun initOnCreated(intent: Intent) {
        val dataBeanString = intent.getStringExtra(Constant.Key.DATA) ?: ""
        dataBean.value = NetApply.gson.fromJson(dataBeanString, GnjUnloadListBean::class.java)
        refresh()
    }

    override fun getData() {
        launchLoadingCollect({
            NetApply.api.getGnjUnloadCarList(
                mapOf(
                    "fid" to dataBean.value?.fid,
                    "fdate" to dataBean.value?.fdate
                ).toRequestBody())
        }) {
            onSuccess = {
                launchCollect({NetApply.api.getHandover(dataBean.value!!.fid)}) {
                    onSuccess = { itt ->
                        if (itt.data == null) handover.value = "" else handover.value = "业务袋"
                    }
                }
                setItems(it.list as List<GnjUnloadListBean>)
                pageModel.handleListBean(it)
                isAllSelected.value = false
            }
        }
    }

    // 添加数据到列表
    fun setItems(items: List<GnjUnloadListBean>) {
        items.forEach { bean ->
            // 设置监听器
            bean.onCheckedChangeListener = object : GnjUnloadListBean.OnCheckedChangeListener {
                override fun onCheckedChanged(bean: GnjUnloadListBean, isChecked: Boolean) {
                    println("Hello, World!")
                    updateSelectAllState()
                }
            }
        }
        updateSelectAllState()
    }

    // 更新全选按钮状态
    private fun updateSelectAllState() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        val filter: List<GnjUnloadListBean> =
            adapter.items.filter { (it as GnjUnloadListBean).checked.get() } as List<GnjUnloadListBean>
        if (filter.isEmpty()) {
            isAllSelected.value = false
            return
        }
        if (filter.size == adapter.items.size){
            isAllSelected.value = true
        }else{
            isAllSelected.value = false
        }
    }

    fun onAllSelectClick() {
        val adapter = pageModel.rv!!.commonAdapter()!!
        if (isAllSelected.value == true){
            CheckUtil.checkAll(adapter.items as List<ICheck>)
        }else{
            CheckUtil.unCheckAll(adapter.items as List<ICheck>)
        }
    }

    fun onDistributionClick() {
        val list = pageModel.rv!!.commonAdapter()!!.items as List<GnjUnloadListBean>
        val filter = list.filter { it.checked.get() }
        if (filter.isEmpty()) {
            showToast("请选择数据")
            return
        }
        val carList = filter.joinToString("、") { it.carId }
        val transDest = filter.get(0).transDest
        var isTrue = false
        for (t in filter) { // T 替换为实际类型（如 YourModel）
            if (!t.transDest.equals(transDest)) { // 假设 transDest 是基本类型或需用 != 比较
                    isTrue = true
                    break // 发现符合条件可立即终止循环（优化性能）
                }
        }
        if (isTrue){
            showToast("请选择同一转运目的地")
            return
        }
        PdaGnjXieJiDetailsAllocationDialogModel(
            carList,
            transDest
        ) {
            launchLoadingCollect({
                NetApply.api.anyPost(
                    "unloadingAirCraft/update", mapOf(
                        "transDest" to it.transDest.value,
                        "airCraftIdList" to filter.map { b -> b.id },
                    ).toRequestBody(true)
                )
            }) {
                onSuccess = {
                    showToast(it.msg.noNull("分配转运目的地成功"))
                    refresh()
                }
            }
        }.show(getTopActivity())

    }
}