package com.lukouguoji.aerologic.page.accident.visa.details

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.aerologic.R
import com.lukouguoji.module_base.base.BaseViewModel
import com.lukouguoji.module_base.bean.AccidentVisaBean
import com.lukouguoji.module_base.bean.FileBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.DetailsPageType
import com.lukouguoji.module_base.http.net.NetApply
import com.lukouguoji.module_base.impl.ImageSelectViewHolder
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.loge
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.verifyNullOrEmpty
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


class AccidentVisaDetailsViewModel : BaseViewModel(), IOnItemClickListener {

    var id = ""

    val pageType = MutableLiveData(DetailsPageType.Add)

    val itemLayoutId = R.layout.item_image_select
    val itemViewHolder = ImageSelectViewHolder::class.java

    var rv: RecyclerView? = null

    val dataBean = MutableLiveData(AccidentVisaBean())

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    fun initOnCreate(intent: Intent) {
        id = intent.getStringExtra(Constant.Key.ID) ?: ""
        val modify = intent.getBooleanExtra(Constant.Key.DATA, false)
        pageType.value = if (id.isEmpty()) DetailsPageType.Add
        else if (modify) DetailsPageType.Modify else DetailsPageType.Details

        if (id.isNotEmpty()) {
            getData()
        }
        rv?.post {
            loge("获取页面类型 : ${pageType.value?.title}")
            if (pageType.value != DetailsPageType.Details) {
                rv?.commonAdapter()?.addItem(FileBean())
            }
        }
    }

    private fun getData() {
        launchLoadingCollect({
            NetApply.api.getGnAccidentVisaDetails(id)
        }) {
            onSuccess = {
                dataBean.value = it.data ?: AccidentVisaBean()

                // 渲染图片：pic 存缩略图文件名，originalPic 存原图文件名
                val picList = dataBean.value!!.pic.split(",").filter { it.isNotEmpty() }
                val originalPicList = dataBean.value!!.originalPic.split(",").filter { it.isNotEmpty() }
                val list = picList.mapIndexed { index, picFilename ->
                    val originalFilename = originalPicList.getOrElse(index) { picFilename }
                    FileBean(
                        path = MediaUtil.fillUrl(picFilename),
                        url = picFilename,
                        originalPic = MediaUtil.fillUrl(originalFilename)
                    )
                }
                rv?.commonAdapter()?.loadMore(list)
            }
        }
    }

    fun onSaveClick() {
        val bean = dataBean.value!!
        if (bean.fno.verifyNullOrEmpty("请输入航班号")) {
            return
        }

        (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=缩略图(较小)
                // FileBean.url 用作缩略图标识，FileBean.originalPic 用作原图标识
                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 as List<FileBean>).filter { it.path.isNotEmpty() }
                    bean.picnumber = list.size.toString()
                    bean.pic = list.joinToString(separator = ",") { MediaUtil.removeUrl(it.url) }
                    bean.originalPic = list.joinToString(separator = ",") { MediaUtil.removeUrl(it.originalPic) }

                    NetApply.api.anyPost(
                        url = if (pageType.value == DetailsPageType.Add) "GnAccidentVisa/saveVisa" else "GnAccidentVisa/updateVisa",
                        body = bean.toRequestBody()
                    )
                }) {
                    onSuccess = {
                        showToast(it.msg.noNull("${pageType.value!!.title}成功"))
                        getTopActivity().finish()
                    }
                }
            }
            .launchIn(viewModelScope)
    }

    fun onCancelClick() {
        getTopActivity().finish()
    }

    override fun onItemClick(position: Int, type: Int) {
        val adapter = rv!!.commonAdapter()!!
        val bean = adapter.getItem(position) as FileBean
        when (type) {
            R.id.rl -> {
                if (pageType.value != DetailsPageType.Details) {
                    bean.canDelete.set(!bean.canDelete.get())
                }
            }

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

            else -> {}
        }
    }

}