package com.remax.visualnovel.widget.imageviewer.viewer

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.graphics.createBitmap
import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.transition.Transition
import com.remax.visualnovel.R
import com.remax.visualnovel.entity.imbean.raw.CustomAlbumData
import com.remax.visualnovel.entity.model.MyImgData
import com.remax.visualnovel.entity.response.Album
import com.remax.visualnovel.entity.response.AppearanceImage
import com.remax.visualnovel.entity.response.ChatBackground
import com.remax.visualnovel.extension.setOnClick
import com.remax.visualnovel.widget.dialoglib.ScreenUtils
import com.remax.visualnovel.widget.imageviewer.core.ImageLoader
import com.remax.visualnovel.widget.imageviewer.core.Photo
import com.remax.visualnovel.widget.imageviewer.widgets.PhotoView2
import timber.log.Timber

class MyImageLoader : ImageLoader {

    private val screenWidth by lazy {
        ScreenUtils.getScreenWidth()
    }

    override fun load(view: ImageView, data: Photo, viewHolder: RecyclerView.ViewHolder) {
        var isLock = false
        val loadUrl = when (data) {
            is Album -> {
                isLock = data.imgUrl == null
                data.imgUrl ?: data.img3 ?: return
            }

            is AppearanceImage -> {
                data.imageUrl
            }

            is ChatBackground -> {
                data.imgUrl
            }

            is CustomAlbumData -> {
                data.url
            }

            else -> {
                (data as? MyImgData?)?.url ?: return
            }
        }
        loadImg(viewHolder.itemView, loadUrl, isLock)
    }

    fun loadImg(
        itemView: View,
        url: String?,
        isLock: Boolean
    ) {
        itemView.run {
            val view = findViewById<PhotoView2>(R.id.photoView)
            val mask = findViewById<ImageView>(R.id.mask)
            val failIcon = findViewById<ImageView>(R.id.failIcon)
            val lockViewGroup = findViewById<View>(R.id.lockViewGroup)
            val failTv = findViewById<TextView>(R.id.failText)
            val loadingView = findViewById<LottieAnimationView>(R.id.loadingView)

            setOnClick(mask) {
                when (this) {
                    mask -> {
                        if (failIcon.isVisible) {
                            loadImg(itemView, url, isLock)
                        }
                    }
                }
            }

            Timber.d("大图加载 url: $url")
//            val width = view.measuredWidth
//            val height = view.measuredHeight
//            Timber.d("大图加载 图片控件的宽高 $width $height ")
//            val loadUrl = if (!isLock && width == screenWidth && height > 0) url.toS3Url(
//                view.measuredWidth,
//                view.measuredHeight,
//                false
//            ) else url
//            Timber.d("大图加载裁剪 loadUrl: $loadUrl")
            Glide.with(view).load(url)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .downsample(DownsampleStrategy.AT_LEAST)
                .into(object : ImageViewTarget<Drawable>(view) {
                    override fun setResource(resource: Drawable?) {

                    }

                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        super.onResourceReady(resource, transition)
                        mask?.isVisible = false
                        failIcon?.isVisible = false
                        failTv?.isVisible = false
                        lockViewGroup?.isVisible = isLock
                        view.isVisible = true
                        val viewWidth = view.measuredWidth
                        val viewHeight = view.measuredHeight
                        val result = if (viewWidth == screenWidth)
                            cropDrawableFromTopCenter(view.context, resource, viewWidth, viewHeight)
                        else resource
                        view.setImageDrawable(result)
                    }

                    override fun onLoadStarted(placeholder: Drawable?) {
                        super.onLoadStarted(placeholder)
                        mask?.isVisible = true
                        failIcon?.isVisible = false
                        failTv?.isVisible = false
                        view.isInvisible = true
                        lockViewGroup?.isVisible = false
                    }

                    override fun onLoadFailed(errorDrawable: Drawable?) {
                        super.onLoadFailed(errorDrawable)
                        mask?.isVisible = true
                        failIcon?.isVisible = true
                        failTv?.isVisible = true
                        view.isInvisible = true
                        lockViewGroup?.isVisible = false
                    }
                })
        }
    }


    private fun cropDrawableFromTopCenter(
        context: Context,
        drawable: Drawable,
        targetWidth: Int,
        targetHeight: Int
    ): Drawable {
        // 将 Drawable 转换为 Bitmap
        val bitmap = drawableToBitmap(drawable) ?: return drawable
        Timber.d("大图加载 bitmap的宽高 ${bitmap.width} ${bitmap.height}")
        Timber.d("大图加载 裁剪目标的宽高 $targetWidth  $targetHeight")

        // 按比例调整目标尺寸
        val (adjustedWidth, adjustedHeight) = adjustTargetSize(
            bitmap.width,
            bitmap.height,
            targetWidth,
            targetHeight
        )

        Timber.d("大图加载 按比例调整 $adjustedWidth $adjustedHeight")

        // 计算裁剪的起始点（顶部中间）
        val startX = (bitmap.width - adjustedWidth) / 2
        val startY = 0 // 从顶部开始

        // 确保裁剪区域有效
        if (startX < 0 || adjustedWidth > bitmap.width || adjustedHeight > bitmap.height) {
            return drawable // 或者抛出异常，视需求而定
        }

        // 裁剪 Bitmap
        val croppedBitmap = Bitmap.createBitmap(bitmap, startX, startY, adjustedWidth, adjustedHeight)

        // 将裁剪后的 Bitmap 转换回 Drawable
        return croppedBitmap.toDrawable(context.resources)
    }

    // 辅助函数：将 Drawable 转换为 Bitmap
    private fun drawableToBitmap(drawable: Drawable): Bitmap? {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }

        // 如果 Drawable 不是 BitmapDrawable，创建一个 Bitmap 并绘制
        val bitmap = createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bitmap
    }

    // 辅助函数：按比例调整目标尺寸
    private fun adjustTargetSize(
        bitmapWidth: Int,
        bitmapHeight: Int,
        targetWidth: Int,
        targetHeight: Int
    ): Pair<Int, Int> {
        // 如果目标尺寸小于等于 Bitmap 尺寸，直接返回
        if (targetWidth <= bitmapWidth && targetHeight <= bitmapHeight) {
            return Pair(targetWidth, targetHeight)
        }

        // 计算宽高比例
        val widthRatio = bitmapWidth.toFloat() / targetWidth
        val heightRatio = bitmapHeight.toFloat() / targetHeight

        // 取较小的比例以确保裁剪区域不超过 Bitmap 尺寸
        val scaleRatio = minOf(widthRatio, heightRatio)

        // 按比例调整目标宽高
        val adjustedWidth = (targetWidth * scaleRatio).toInt()
        val adjustedHeight = (targetHeight * scaleRatio).toInt()

        return Pair(adjustedWidth, adjustedHeight)

    }
}


