package com.rdiot.yx485.util

import android.content.Context
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.R
import java.lang.reflect.Field
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method

/**
 *
 * @author mR2hao
 * @date 2022/12/14
 */
fun Context.loadOneTimeGif(
    url: Any,
    imageView: ImageView,
    gifListener: GifListener? = null
) {
    Glide.with(this).asGif().load(url).skipMemoryCache(true)
        .diskCacheStrategy(DiskCacheStrategy.NONE).listener(object : RequestListener<GifDrawable?> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<GifDrawable?>?,
                isFirstResource: Boolean
            ): Boolean {
                return false
            }

            override fun onResourceReady(
                resource: GifDrawable?,
                model: Any?,
                target: Target<GifDrawable?>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                try {
                    val gifStateField: Field = GifDrawable::class.java.getDeclaredField("state")
                    gifStateField.isAccessible = true
                    val gifStateClass =
                        Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable\$GifState")
                    val gifFrameLoaderField: Field = gifStateClass.getDeclaredField("frameLoader")
                    gifFrameLoaderField.isAccessible = true
                    val gifFrameLoaderClass =
                        Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader")
                    val gifDecoderField: Field = gifFrameLoaderClass.getDeclaredField("gifDecoder")
                    gifDecoderField.isAccessible = true
                    val gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder")
                    val gifDecoder =
                        gifDecoderField.get(gifFrameLoaderField.get(gifStateField.get(resource)))
                    val getDelayMethod: Method =
                        gifDecoderClass.getDeclaredMethod("getDelay", Int::class.javaPrimitiveType)
                    getDelayMethod.setAccessible(true)
                    //设置只播放一次
                    resource?.setLoopCount(1)
                    //获得总帧数
                    val count = resource?.frameCount ?: 0
                    var delay = 0
                    for (i in 0 until count) {
                        //计算每一帧所需要的时间进行累加
                        delay += getDelayMethod.invoke(gifDecoder, i) as Int
                    }
                    imageView.postDelayed(Runnable {
                        gifListener?.gifPlayComplete()
                    }, delay.toLong())
                } catch (e: NoSuchFieldException) {
                    e.printStackTrace()
                } catch (e: ClassNotFoundException) {
                    e.printStackTrace()
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                } catch (e: NoSuchMethodException) {
                    e.printStackTrace()
                } catch (e: InvocationTargetException) {
                    e.printStackTrace()
                }
                return false
            }


        }).into(imageView)

}

/**
 * Gif播放完毕回调
 */
interface GifListener {
    fun gifPlayComplete()
}

/**
 * 加载圆形图片
 * @receiver Context
 */
fun ImageView.circleImg(
    url: String,
    @DrawableRes errId: Int = R.mipmap.icon_default_user_big,
    @DrawableRes placeHolderId: Int = R.mipmap.icon_default_user_big
) {
    //渐变显示
    val factory = DrawableCrossFadeFactory.Builder()
        .setCrossFadeEnabled(true).build()

    val options: RequestOptions = RequestOptions()
        .error(errId)
        .placeholder(placeHolderId)
        .error(errId)
        .circleCrop()

    Glide.with(this)
        .load(url)
        .apply(options)
        .transition(DrawableTransitionOptions.withCrossFade(factory))
        .into(this)
}