package com.lukouguoji.gnj.page.yiku.handover

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.ImageSelectNewViewHolder
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.launchLoadingCollect
import com.lukouguoji.module_base.ktx.showToast
import com.lukouguoji.module_base.ktx.toRequestBody
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.module_base.util.MediaUtil
import com.lukouguoji.module_base.util.UploadUtil
import kotlinx.coroutines.launch

/**
 * 国内进港移交编辑/详情 ViewModel
 */
class GnjYiKuHandoverViewModel : BaseViewModel(), IOnItemClickListener {

    val pageType = MutableLiveData(DetailsPageType.Modify)
    var mawbId = ""

    val dataBean = MutableLiveData(GnjYiKuBean())

    // 图片列表
    val imageList = MutableLiveData<MutableList<FileBean>>(mutableListOf())

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

    // 详情模式下无图片时显示占位提示
    val showNoImage = MutableLiveData(false)

    // 图片 RecyclerView 引用（用于从 adapter 实时获取图片）
    var rvImages: RecyclerView? = null

    fun initOnCreated(intent: Intent) {
        pageType.value = DetailsPageType.valueOf(
            intent.getStringExtra(Constant.Key.PAGE_TYPE) ?: DetailsPageType.Modify.name
        )
        mawbId = intent.getStringExtra(Constant.Key.ID) ?: ""
        loadData()
    }

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

                // 处理图片列表（同时保留缩略图和原图信息，确保二次编辑时不丢失）
                val picList = bean.pic.split(",").filter { it.isNotEmpty() }
                val originalPicList = bean.originalPic.split(",").filter { it.isNotEmpty() }
                val images = if (picList.isNotEmpty()) {
                    picList.mapIndexed { index, picUrl ->
                        val originalUrl = originalPicList.getOrElse(index) { picUrl }
                        FileBean(
                            path = MediaUtil.fillUrl(originalUrl),
                            url = picUrl,
                            originalPic = originalUrl
                        )
                    }.toMutableList()
                } else {
                    originalPicList.map { url ->
                        FileBean(path = MediaUtil.fillUrl(url), url = url, originalPic = url)
                    }.toMutableList()
                }

                // 编辑模式添加空 FileBean 用于显示"添加照片"按钮
                if (pageType.value == DetailsPageType.Modify) {
                    images.add(FileBean())
                }

                imageList.value = images

                // 详情模式下无图片时显示占位提示
                if (pageType.value == DetailsPageType.Details && images.isEmpty()) {
                    showNoImage.value = true
                }
            }
        }
    }

    /**
     * 提交保存（只保存备注和图片）
     */
    fun submit() {
        val bean = dataBean.value ?: return

        // 从 adapter 实时获取所有非空图片（ViewHolder 新增图片直接操作 adapter items）
        val allItems = (rvImages?.commonAdapter()?.items as? List<*>)
            ?.filterIsInstance<FileBean>() ?: imageList.value!!
        val images = allItems.filter { it.path.isNotEmpty() }

        if (images.size > 7) {
            showToast("最多上传7张图片")
            return
        }

        launchLoadingCollect({
            // 上传图片
            images.forEach { fileBean ->
                if (fileBean.url.isNotEmpty()) {
                    // 已上传的图片，保持原有的 url 和 originalPic
                } else {
                    // 本地新图片需要上传
                    // UploadUtil 返回：newName=原图(较大)，zipFileName=缩略图(较小)
                    // FileBean.url 用作缩略图标识，FileBean.originalPic 用作原图标识
                    val data = UploadUtil.upload(fileBean.path).data
                    fileBean.url = data?.zipFileName ?: ""
                    fileBean.originalPic = data?.newName ?: ""
                }
            }

            // 提交（只更新备注和图片）
            val params = mapOf(
                "mawbId" to mawbId,
                "remark" to bean.remark,
                "picNumber" to images.size.toString(),
                "pic" to images.joinToString(",") { MediaUtil.removeUrl(it.url) },
                "originalPic" to images.joinToString(",") { MediaUtil.removeUrl(it.originalPic) },
            ).toRequestBody(removeEmptyOrNull = true)

            NetApply.api.modifyGnjMoveStash(params)
        }) {
            onSuccess = {
                showToast("保存成功")
                viewModelScope.launch {
                    FlowBus.with<String>(ConstantEvent.EVENT_REFRESH_GNJ_YIKU_LIST).emit("refresh")
                }
                getTopActivity().finish()
            }
        }
    }

    /**
     * 处理图片删除点击事件
     */
    override fun onItemClick(position: Int, type: Int) {
        if (type == R.id.iv_delete) {
            val adapter = rvImages?.commonAdapter() ?: return
            if (position < adapter.items.size) {
                adapter.removeItem(position)
            }
        }
    }
}
