package com.lukouguoji.gnj.page.yiku.edit

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lukouguoji.gnj.R
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.FileBean
import com.lukouguoji.module_base.bean.GnjYiKuBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.ConstantEvent
import com.lukouguoji.module_base.common.DetailsPageType
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.FlowBus
import com.lukouguoji.module_base.impl.ImageSelectViewHolder
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import com.lukouguoji.module_base.ktx.verifyNullOrEmpty
import com.lukouguoji.module_base.util.UploadUtil
import dev.utils.app.info.KeyValue
import kotlinx.coroutines.launch

/**
 * 国内进港移库编辑 ViewModel
 */
class GnjYiKuEditViewModel : BaseViewModel(), IOnItemClickListener {

    val pageType = MutableLiveData(DetailsPageType.Add)
    var id = ""

    val dataBean = MutableLiveData(GnjYiKuBean())

    // 运单类型下拉列表
    val waybillTypeList = MutableLiveData(
        listOf(
            KeyValue("转国际进港", "CIII"),
            KeyValue("转国内出港", "CICO"),
            KeyValue("转国际出港", "CIIO"),
        )
    )

    // 图片列表（初始添加一个空的FileBean用于显示"添加图片"按钮）
    val imageList = MutableLiveData<MutableList<FileBean>>(
        mutableListOf(FileBean())
    )

    // 图片适配器配置
    val imageItemLayoutId = R.layout.item_image_select
    val imageItemViewHolder = ImageSelectViewHolder::class.java

    fun initOnCreated(intent: Intent) {
        // 获取页面类型
        pageType.value = DetailsPageType.valueOf(
            intent.getStringExtra(Constant.Key.PAGE_TYPE) ?: DetailsPageType.Add.name
        )

        // 如果是编辑或详情，加载数据
        if (pageType.value != DetailsPageType.Add) {
            id = intent.getStringExtra(Constant.Key.ID) ?: ""
            loadData()
        }
    }

    private fun loadData() {
        launchLoadingCollect({
            NetApply.api.getGnjYiKuDetails(id)
        }) {
            onSuccess = {
                val bean = it.data ?: GnjYiKuBean()
                dataBean.value = bean

                // 处理图片列表
                val images = bean.getImageList().map { url ->
                    FileBean(path = url)
                }.toMutableList()

                // 如果是编辑模式，添加一个空的FileBean用于添加新图片
                if (pageType.value == DetailsPageType.Modify) {
                    images.add(FileBean())
                }

                imageList.value = images
            }
        }
    }

    /**
     * 提交保存
     */
    fun submit() {
        val bean = dataBean.value ?: return

        // 验证必填项
        if (bean.wbNo.verifyNullOrEmpty("请输入运单号")) return
        if (bean.pc.verifyNullOrEmpty("请输入件数")) return
        if (bean.weight.verifyNullOrEmpty("请输入重量")) return

        // 获取所有非空图片
        val images = imageList.value!!.filter { it.path.isNotEmpty() }

        // 检查图片数量限制（最多7张）
        if (images.size > 7) {
            showToast("最多上传7张图片")
            return
        }

        launchLoadingCollect({
            // 1. 上传图片
            val uploadedUrls = mutableListOf<String>()
            images.forEach { fileBean ->
                // 判断是否为已上传的图片（在线URL）
                if (fileBean.path.startsWith("http")) {
                    uploadedUrls.add(fileBean.path)
                } else {
                    // 本地图片需要上传
                    val result = UploadUtil.upload(fileBean.path)
                    if (result.verifySuccess()) {
                        uploadedUrls.add(result.data?.newName ?: "")
                    }
                }
            }

            // 2. 提交表单数据
            val params = mapOf(
                "id" to id,
                "wbNo" to bean.wbNo,
                "pc" to bean.pc,
                "weight" to bean.weight,
                "spCode" to bean.spCode,
                "agentCode" to bean.agentCode,
                "goods" to bean.goods,
                "flight" to bean.flight,
                "route" to bean.route,
                "awbType" to bean.awbType,
                "telegramNo" to bean.telegramNo,
                "remark" to bean.remark,
                "images" to uploadedUrls.joinToString(","),
            ).toRequestBody(removeEmptyOrNull = true)

            NetApply.api.saveGnjYiKu(params)
        }) {
            onSuccess = {
                showToast(if (pageType.value == DetailsPageType.Add) "新增成功" else "保存成功")

                // 发送刷新事件
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH_GNJ_YIKU_LIST).emit("refresh")
                }

                // 关闭页面
                getTopActivity().finish()
            }
        }
    }

    /**
     * 处理图片删除点击事件
     */
    override fun onItemClick(position: Int, type: Int) {
        val list = imageList.value!!
        if (type == R.id.iv_delete && position < list.size) {
            list.removeAt(position)
            imageList.value = list
        }
    }
}
