package com.lukouguoji.module_base.impl

import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.bean.FileBean
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.databinding.ItemImageSelectBinding
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.logd
import com.lukouguoji.module_base.ui.page.preview.PreviewActivity
import com.lukouguoji.module_base.util.MediaUtil
import java.io.File

class ImageSelectViewHolder(view: View) : BaseViewHolder<FileBean, ItemImageSelectBinding>(view) {

    override fun onBind(item: Any?, position: Int) {
        val bean = getItemBean(item)!!
        binding.bean = bean

        // 加载缩略图
        if (bean.path.isNotEmpty()) {
            if (bean.isOnlineResource()) {
                val glideUrl = GlideUrl(
                    bean.path,
                    LazyHeaders.Builder()
                        .addHeader("Authorization", SharedPreferenceUtil.getString(Constant.Share.token))
                        .build()
                )
                Glide.with(itemView.context).load(glideUrl).into(binding.iv)
            } else {
                Glide.with(itemView.context).load(File(bean.path)).into(binding.iv)
            }
        }

        binding.rl.setOnClickListener {
            if (bean.path.isEmpty()) {
                MediaUtil.pickImage(itemView.context, maxNum = 10) {
                    it.forEach {
                        logd("添加了图片 : ${it.realPath}")
                        getRecyclerView()?.commonAdapter()?.addItem(FileBean(path = it.realPath))
                    }
                }
            } else {
                val items = getRecyclerView()?.commonAdapter()?.items
                    ?.filterIsInstance<FileBean>()
                    ?.filter { it.path.isNotEmpty() }
                    ?: listOf(bean)
                val previewList = items.map { fb ->
                    FileBean(path = if (fb.originalPic.isNotEmpty()) fb.originalPic else fb.path)
                }
                val previewPosition = items.indexOfFirst { it === bean }.coerceAtLeast(0)
                PreviewActivity.start(itemView.context, previewList, previewPosition)
            }
        }

        // 长按事件
        binding.rl.setOnLongClickListener {
            clickListener?.onItemClick(bindingAdapterPosition, binding.rl.id)
            true
        }

        notifyItemClick(position, binding.ivDelete)
    }

}
