package com.lukouguoji.module_base.impl

import android.view.View
import android.view.ViewTreeObserver
import com.lukouguoji.module_base.adapter.loadImage
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.bean.FileBean
import com.lukouguoji.module_base.databinding.ItemImageSelectNewBinding
import com.lukouguoji.module_base.ktx.commonAdapter
import com.lukouguoji.module_base.ktx.logd
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ui.page.preview.PreviewActivity
import com.lukouguoji.module_base.util.MediaUtil

class ImageSelectNewViewHolder(view: View) : BaseViewHolder<FileBean, ItemImageSelectNewBinding>(view) {

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

        // 让高度等于宽度，实现正方形
        binding.rl.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                binding.rl.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val width = binding.rl.width
                if (width > 0 && binding.rl.height != width) {
                    val lp = binding.rl.layoutParams
                    lp.height = width
                    binding.rl.layoutParams = lp
                }
            }
        })

        binding.rl.setOnClickListener {
            if (bean.path.isEmpty()) {
                MediaUtil.pickImage(itemView.context, maxNum = 10) { results ->
                    val adapter = getRecyclerView()?.commonAdapter() ?: return@pickImage
                    results.forEach { result ->
                        logd("添加了图片 : ${result.realPath}")
                        // 在加号按钮（最后一项）之前插入图片
                        val insertPos = adapter.items.size - 1
                        adapter.items.add(insertPos, FileBean(path = result.realPath))
                        adapter.notifyItemInserted(insertPos)
                    }
                }
            } else {
                PreviewActivity.start(itemView.context, listOf(bean))
            }
        }

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

        notifyItemClick(position, binding.ivDelete)

        if (bean.isOnlineResource()) {
            loge("开始下载 : ${bean.path}")
            bean.download {
                loadImage(binding.iv, it)
            }
        }
    }
}
