package com.lukouguoji.aerologic.page.gnj.move.stash.photo

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
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.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.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.util.MediaUtil
import com.lukouguoji.module_base.util.UploadUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * 国内进港移库「拍照上传」ViewModel（5.5 寸手持端专属页面）
 *
 * 图片选择/预览/删除复用 module_base 的 ImageSelectNewViewHolder（末位加号槽位）。
 * 已有照片经 DomImpMove/detail 回填；提交走 DomImpMove/modify 最小体
 * （mawbId/remark/picNumber/pic/originalPic），与平板移交编辑页同一链路。
 */
class GnjMoveStashPhotoViewModel : BaseViewModel(), IOnItemClickListener {

    var mawbId = ""

    /** 运单号（副标题展示，由列表带入） */
    val wbNo = MutableLiveData("")

    /** detail 回填的完整 bean（提交时保留 remark 等原值） */
    private var detailBean = GnjYiKuBean()

    // 图片网格适配器配置（复用公共图片选择组件）
    val itemViewHolder = ImageSelectNewViewHolder::class.java
    val itemLayoutId = com.lukouguoji.module_base.R.layout.item_image_select_new

    var rv: RecyclerView? = null

    fun initOnCreated(intent: Intent) {
        mawbId = intent.getStringExtra(Constant.Key.ID).orEmpty()
        wbNo.value = intent.getStringExtra(Constant.Key.CODE).orEmpty()

        // 已有照片回填（pic 缩略图 + originalPic 原图），末位补加号槽位
        launchCollect({ NetApply.api.getGnjMoveStashDetail(mawbId) }) {
            onSuccess = {
                detailBean = it.data ?: GnjYiKuBean()
                val picList = detailBean.pic.split(",").filter { p -> p.isNotEmpty() }
                val originalList = detailBean.originalPic.split(",").filter { p -> p.isNotEmpty() }
                val images = picList.mapIndexed { index, picUrl ->
                    FileBean(
                        path = MediaUtil.fillUrl(picUrl),
                        url = picUrl,
                        originalPic = MediaUtil.fillUrl(originalList.getOrElse(index) { picUrl })
                    )
                }
                rv?.post {
                    rv?.commonAdapter()?.refresh(images + FileBean())
                }
            }
            onFailed = { _, _ ->
                // 详情取不到也允许直接新增照片
                rv?.post { rv?.commonAdapter()?.refresh(listOf(FileBean())) }
            }
        }
    }

    /**
     * 确认提交：先补传未上传的本地图片，再按三字段规范提交 modify
     */
    fun submitClick() {
        (rv?.commonAdapter()?.items ?: emptyList())
            .asFlow()
            .map { it as FileBean }
            .filter { it.path.isNotEmpty() && it.url.isEmpty() }
            .onEach {
                val data = UploadUtil.upload(it.path).data
                // UploadUtil 返回：newName=原图(较大)，zipFileName=缩略图(较小)
                it.url = data?.zipFileName ?: ""
                it.originalPic = data?.newName ?: ""
            }
            .flowOn(Dispatchers.IO)
            .onStart { showLoading() }
            .catch {
                showToast(it.message.noNull("上传图片失败"))
                dismissLoading()
            }
            .onCompletion {
                launchLoadingCollect({
                    val list = (rv?.commonAdapter()?.items ?: emptyList())
                        .filterIsInstance<FileBean>()
                        .filter { it.path.isNotEmpty() }

                    // 最小体提交：只更新图片三字段（remark 保留 detail 原值），与平板移交编辑页一致
                    val params = mapOf(
                        "mawbId" to mawbId,
                        "remark" to detailBean.remark,
                        "picNumber" to list.size.toString(),
                        "pic" to list.joinToString(",") { MediaUtil.removeUrl(it.url) },
                        "originalPic" to list.joinToString(",") { MediaUtil.removeUrl(it.originalPic) },
                    ).toRequestBody(removeEmptyOrNull = true)

                    NetApply.api.modifyGnjMoveStash(params)
                }) {
                    onSuccess = {
                        showToast("提交成功")
                        viewModelScope.launch {
                            FlowBus.with<String>(ConstantEvent.EVENT_REFRESH).emit("refresh")
                        }
                        getTopActivity().finish()
                    }
                    onFailed = { _, msg ->
                        showToast(msg.noNull("提交失败"))
                    }
                }
            }
            .launchIn(viewModelScope)
    }

    /**
     * 「拍照/上传」按钮：直接唤起图片选择（含拍照入口）
     */
    fun pickClick() {
        MediaUtil.pickImage(getTopActivity(), maxNum = 9) { results ->
            val adapter = rv?.commonAdapter() ?: return@pickImage
            results.forEach { result ->
                // 在加号槽位（最后一项）之前插入
                val insertPos = (adapter.items.size - 1).coerceAtLeast(0)
                adapter.items.add(insertPos, FileBean(path = result.realPath))
                adapter.notifyItemInserted(insertPos)
            }
        }
    }

    /**
     * 图片网格点击回调（长按出删除角标 / 点删除角标移除）
     */
    override fun onItemClick(position: Int, type: Int) {
        val adapter = rv?.commonAdapter() ?: return
        val bean = adapter.getItem(position) as? FileBean ?: return
        when (type) {
            com.lukouguoji.module_base.R.id.rl -> {
                if (bean.path.isNotEmpty()) {
                    bean.canDelete.set(!bean.canDelete.get())
                }
            }

            com.lukouguoji.module_base.R.id.iv_delete -> {
                adapter.removeItem(position)
            }

            else -> {}
        }
    }
}
