package com.lukouguoji.gjj.viewModel

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.holder.IntImpPickUpDLVViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.IntImpPickUpDLVBean
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.showToast
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.model.ConfirmDialogModel
import com.lukouguoji.module_base.model.ScanModel
import dev.utils.app.info.KeyValue
import dev.utils.common.DateUtils
import kotlinx.coroutines.launch

/**
 * 国际进港-提取出库 ViewModel
 */
class IntImpPickUpDLVViewModel : BasePageViewModel() {

    // ========== 搜索条件 ==========
    val paymentDateStart = MutableLiveData(DateUtils.getCurrentTime().formatDate())    // 缴费日期起
    val paymentDateEnd = MutableLiveData("")      // 缴费日期止
    val agentCode = MutableLiveData("")           // 代理人
    val wbNo = MutableLiveData("")               // 运单号
    val pickUpNo = MutableLiveData("")           // 提货单号

    // ========== 下拉列表数据源 ==========
    val agentList = MutableLiveData(listOf(KeyValue("全部", "")))

    // ========== 统计信息 ==========
    val totalCount = MutableLiveData("0")        // 合计票数
    val totalPc = MutableLiveData("0")           // 总件数
    val totalWeight = MutableLiveData("0")       // 总重量

    // ========== 全选状态 ==========
    val isAllChecked = MutableLiveData(false)

    init {
        isAllChecked.observeForever { checked ->
            val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpDLVBean>
                ?: return@observeForever
            list.forEach { it.checked.set(checked) }
            pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
        }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpPickUpDLVViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_pick_up_dlv

    /**
     * 初始化代理人列表
     */
    fun initAgentList() {
        launchCollect({ NetApply.api.getIntImpAgentList() }) {
            onSuccess = { result ->
                val list = mutableListOf(KeyValue("全部", ""))
                result.data?.forEach {
                    list.add(KeyValue(it.name ?: "", it.code ?: ""))
                }
                agentList.value = list
            }
        }
    }

    /**
     * 搜索按钮点击
     */
    fun searchClick() {
        refresh()
    }

    /**
     * 扫码运单号
     */
    fun scanWbNo() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.WAYBILL)
    }

    /**
     * 扫码提货单号
     */
    fun scanPickUpNo() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.gnj_chu_ku_list)
    }

    /**
     * 全选按钮点击
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpDLVBean> ?: return
        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    /**
     * 确认出库
     */
    fun confirmOutbound() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpDLVBean> ?: return
        val selectedItems = list.filter { it.isSelected }

        if (selectedItems.isEmpty()) {
            showToast("请选择要出库的记录")
            return
        }

        ConfirmDialogModel(
            message = "确定要将选中的${selectedItems.size}条记录确认出库吗？",
            title = "确认出库"
        ) {
            launchLoadingCollect({ NetApply.api.confirmIntImpPickUpDLV(selectedItems.toRequestBody()) }) {
                onSuccess = {
                    showToast("确认出库成功")
                    viewModelScope.launch {
                        FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                    }
                    refresh()
                }
            }
        }.show()
    }

    /**
     * 获取列表数据
     */
    override fun getData() {
        val filterParams = mapOf(
            "beginDate" to paymentDateStart.value?.ifEmpty { null },
            "endDate" to paymentDateEnd.value?.ifEmpty { null },
            "agentCode" to agentCode.value?.ifEmpty { null },
            "no" to wbNo.value?.ifEmpty { null },
            "pkId" to pickUpNo.value?.ifEmpty { null }
        )

        val listParams = (filterParams + mapOf(
            "page" to pageModel.page,
            "limit" to pageModel.limit
        )).toRequestBody()

        val totalParams = filterParams.toRequestBody()

        launchLoadingCollect({ NetApply.api.getIntImpPickUpDLVList(listParams) }) {
            onSuccess = { result ->
                pageModel.handleDataList(result.list)
                pageModel.haveMore.postValue((result.pages) > pageModel.page)
            }
        }

        launchCollect({ NetApply.api.getIntImpPickUpDLVTotal(totalParams) }) {
            onSuccess = { result ->
                val data = result.data
                totalCount.value = (data?.wbNumber ?: 0).toString()
                totalPc.value = (data?.totalPc ?: 0).toString()
                totalWeight.value = (data?.totalWeight ?: 0.0).toString()
            }
        }
    }

    /**
     * 处理扫码结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                Constant.RequestCode.WAYBILL -> {
                    wbNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
                Constant.RequestCode.gnj_chu_ku_list -> {
                    pickUpNo.value = data.getStringExtra(Constant.Result.CODED_CONTENT)
                    refresh()
                }
            }
        }
    }
}
