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.IntImpPickUpRecordViewHolder
import com.lukouguoji.module_base.base.BasePageViewModel
import com.lukouguoji.module_base.bean.IntImpPickUpRecordBean
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.noNull
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.formatDate
import com.lukouguoji.module_base.model.ScanModel
import com.lukouguoji.module_base.util.DictUtils
import dev.utils.common.DateUtils
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国际进港-提取记录 ViewModel
 */
class IntImpPickUpRecordViewModel : BasePageViewModel() {

    // ========== 筛选条件 ==========
    val paymentDateStart = MutableLiveData(DateUtils.getCurrentTime().formatDate())  // 缴费日期起
    val paymentDateEnd = MutableLiveData("")          // 缴费日期止
    val agentCode = MutableLiveData("")               // 代理人
    val spCode = MutableLiveData("")                  // 特码
    val wbNo = MutableLiveData("")                    // 运单号

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

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

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

    fun onItemCheckChanged() {
        updateCheckAllStatus()
    }

    fun updateCheckAllStatus() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpRecordBean> ?: return
        isAllChecked.value = list.isNotEmpty() && list.all { it.checked.get() }
    }

    // ========== 适配器配置 ==========
    val itemViewHolder = IntImpPickUpRecordViewHolder::class.java
    val itemLayoutId = R.layout.item_int_imp_pick_up_record

    /**
     * 初始化代理人列表
     */
    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 initSpecialCodeList() {
        DictUtils.getSpecialCodeList(
            flag = 1,           // 国际
            ieFlag = "",
            parentcode = ""
        ) {
            spCodeList.value = it
        }
    }

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

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

    /**
     * 全选按钮点击
     */
    fun checkAllClick() {
        val list = pageModel.rv?.commonAdapter()?.items as? List<IntImpPickUpRecordBean> ?: return

        val shouldCheckAll = !isAllChecked.value!!
        list.forEach { it.checked.set(shouldCheckAll) }
        isAllChecked.value = shouldCheckAll
        pageModel.rv?.commonAdapter()?.notifyDataSetChanged()
    }

    /**
     * 清除提货操作
     */
    fun clearPickUp(selectedItems: List<IntImpPickUpRecordBean>) {
        if (selectedItems.isEmpty()) {
            showToast("请选择要清除提货的记录")
            return
        }

        val params = selectedItems.toRequestBody()

        launchLoadingCollect({ NetApply.api.clearIntImpPickUp(params) }) {
            onSuccess = {
                showToast("清除提货成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                }
                refresh()
            }
            onFailed = { _, msg ->
                showToast(msg.noNull("清除提货失败"))
            }
        }
    }

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

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

        val totalParams = filterParams.toRequestBody()

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

        launchCollect({ NetApply.api.getIntImpPickUpRecordTotal(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()
                }
            }
        }
    }
}
