package com.sixin.module_p.ui.gnj.accidentVisa.add

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.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.PdaImageSelectViewHolder
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.model.ScanModel
import com.lukouguoji.module_base.util.MediaUtil
import com.lukouguoji.module_base.util.UploadUtil
import com.sixin.module_p.R
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 PdaAccidentVisaAddViewModel : BaseViewModel(), IOnItemClickListener {

    var id = ""


    val itemLayoutId = R.layout.pda_item_image_select
    val itemViewHolder = PdaImageSelectViewHolder::class.java
    var rv: RecyclerView? = null

    val dataBean = MutableLiveData(AccidentVisaBean())

    val pageType = MutableLiveData(DetailsPageType.Add)

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


    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()

                // 渲染图片
                val list = dataBean.value!!.pic.split(",")
                    .filter { url -> url.isNotEmpty() }
                    .map { url ->
                        FileBean(MediaUtil.fillUrl(url), url)
                    }
                val zipList = dataBean.value!!.originalPic.split(",")
                    .filter { url -> url.isNotEmpty() }
                    .map { url ->
                        FileBean(MediaUtil.fillUrl(url))
                    }
                for ((index, fileBean) in list.withIndex()) {
                    val originalPic = zipList.get(index).path
                    fileBean.originalPic= originalPic
                }

                rv?.commonAdapter()
                    ?.loadMore(list)
            }
        }
    }

    fun reSet(){
        dataBean.value = AccidentVisaBean()
    }

    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
                it.url = data?.newName ?: ""
                it.originalPic = data?.zipFileName ?: ""
            }
            .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.originalPic = list.joinToString(separator = ",") { MediaUtil.removeUrl(it.url) }
                    bean.pic = 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)
    }



    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 -> {}
        }
    }
    fun scanClick() {
        ScanModel.startScan(getTopActivity(), Constant.RequestCode.CAR)
    }
}