package com.base.appzxhy.ui.concatAdapter

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.updatePadding
import androidx.palette.graphics.Palette
import androidx.viewpager2.widget.ViewPager2
import com.base.appzxhy.R
import com.base.appzxhy.databinding.ItemBannerBinding
import com.base.appzxhy.databinding.ItemGalleryBannerBinding
import com.base.appzxhy.ui.adapter.CommonViewHolder
import com.base.appzxhy.utils.BarUtils
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.XmlEx.inflate
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.bytedance.sdk.shortplay.api.ShortPlay
import com.chad.library.adapter4.BaseQuickAdapter
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.BaseViewHolder
import com.zhpan.bannerview.constants.PageStyle
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle


class BannerAdapter : BaseQuickAdapter<List<ShortPlay>, CommonViewHolder>() {

    private val TAG = "BannerAdapter"
    var playAction: ((shortPlay: ShortPlay) -> Unit)? = null
    var binding: ItemBannerBinding? = null
    private var paletteMap = HashMap<String, Int>()
//    var paletteCallBack: ((color: Int) -> Unit)? = null

    override fun getItemCount(items: List<List<ShortPlay>>): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int, item: List<ShortPlay>?) {

        item ?: return
        binding = ItemBannerBinding.bind(holder.itemView)
        val context = holder.itemView.context
        LogEx.logDebug(TAG, "onBindViewHolder")

        val top = BarUtils.getStatusBarHeight() + context.resources.getDimensionPixelSize(R.dimen.dp_66)
        binding?.root?.updatePadding(top = top)

        if (binding?.banner?.adapter == null && item.isNotEmpty()) {
            LogEx.logDebug(TAG, "onBindViewHolder banner")
            val innerAdapter = GalleryAdapter()
            val banner: BannerViewPager<ShortPlay>? = binding?.root?.findViewById(R.id.banner)
            banner?.adapter = innerAdapter
            banner?.currentItem = item.size / 2
            banner?.setPageMargin(context.resources.getDimensionPixelOffset(R.dimen.dp_10))
            banner?.setScrollDuration(800)
            banner?.setRevealWidth(
                context.resources.getDimensionPixelOffset(R.dimen.dp_30),
                context.resources.getDimensionPixelOffset(R.dimen.dp_30)
            )
            banner?.setPageStyle(PageStyle.MULTI_PAGE_SCALE, 0.85f)

            banner?.setIndicatorVisibility(View.GONE)
            banner?.setIndicatorSlideMode(IndicatorSlideMode.SCALE)
            banner?.setIndicatorStyle(IndicatorStyle.ROUND_RECT)
            banner?.setIndicatorSliderGap(
                context.resources.getDimensionPixelSize(R.dimen.dp_6)
            )
            banner?.setIndicatorSliderWidth(
                context.resources.getDimensionPixelSize(R.dimen.dp_13),
                context.resources.getDimensionPixelSize(R.dimen.dp_20)
            )
            banner?.setIndicatorSliderColor(
                ContextCompat.getColor(context, R.color.color_4dffffff),
                ContextCompat.getColor(context, R.color.color_ffffff),
            )
            banner?.setIndicatorView(binding?.indicator)

            banner?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    LogEx.logDebug(TAG, "onPageSelected position=$position")
                    val bean = item[position]
                    val coverImage = bean.coverImage
                    val color = paletteMap[coverImage] ?: Color.BLACK
//                    paletteCallBack?.invoke(color)
                    binding?.root?.setBackgroundColor(color)
                }
            })
            banner?.create(item)
        } else {
            if (binding?.banner?.adapter?.itemCount == 0) {
                binding?.banner?.currentItem = item.size / 2
                binding?.banner?.addData(item)
            }
        }
    }

    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): CommonViewHolder {
        return CommonViewHolder(R.layout.item_banner.inflate(parent))
    }

    fun setBannerAutoLoop(isAutoLoop: Boolean) {
        binding?.banner?.setCanLoop(isAutoLoop)
    }

    inner class GalleryAdapter : BaseBannerAdapter<ShortPlay>() {

        private fun paletteImage(imageView: ImageView, coverImage: String) {
            Glide.with(context)
                .asBitmap()
                .load(coverImage)
                .into(object : CustomTarget<Bitmap?>() {
                    override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap?>?) {
                        imageView.setImageBitmap(bitmap)
                        Palette.from(bitmap).generate { palette ->
                            palette ?: return@generate
                            // 获取主题色
//                        val vibrantColor: Int = palette.getVibrantColor(Color.TRANSPARENT)
                            //柔和是
//                        val mutedColor: Int = palette.getMutedColor(Color.TRANSPARENT)
                            //主色调
                            val dominantColor = palette.getDominantColor(Color.TRANSPARENT)
//                        val alpha = 230 // 透明度值，范围为0-255，0为完全透明，255为完全不透明
//                        val newColor = vibrantColor and 0x00ffffff or (alpha shl 24)
                            // 使用这些颜色进行后续操作，例如设置背景色等
                            paletteMap[coverImage] = dominantColor
                        }
                    }

                    override fun onLoadCleared(placeholder: Drawable?) {
                        // 图片加载失败或清除时的处理
                    }
                })
            imageView.tag = coverImage
        }

        override fun bindData(holder: BaseViewHolder<ShortPlay>, data: ShortPlay?, position: Int, pageSize: Int) {
            data ?: return
            val binding = ItemGalleryBannerBinding.bind(holder.itemView)
            binding.llPlay.setOnClickListener {
                playAction?.invoke(data)
            }
            val tag = binding.iv.tag
            LogEx.logDebug(TAG, "position=$position  tag=$tag coverImage=${data.coverImage}")
            if (tag != data.coverImage) {
                paletteImage(binding.iv, data.coverImage)
            }
        }

        override fun getLayoutId(viewType: Int): Int {
            return R.layout.item_gallery_banner
        }
    }
}