package com.lukouguoji.module_base.adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Build
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.GranularRoundedCorners
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lukouguoji.module_base.base.BaseViewHolder
import com.lukouguoji.module_base.base.CommonAdapter
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.db.perference.SharedPreferenceUtil
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.util.SizeUtils

/**
 * @author：孟凡华
 * @date：2022/11/11
 * @desc：dataBinding适配器
 */
/**
 * 加载图片
 */
@SuppressLint("CheckResult")
@BindingAdapter(
    // 图片地址
    "loadImage",
    // 错误图片
    "loadError",
    // 占位图
    "loadPlaceholder",
    // 宽度
    "loadWidth",
    // 高度
    "loadHeight",
    // 是否缓存
    "loadCache",
    // 加载圆形图片
    "loadCircle",
    // 圆角
    "loadRadius",
    /**
     * 下述圆角参数优先级高于 loadRadius 和 loadCircle,
     * 并且设置了单个圆角参数后,就会生效,未设置的参数默认为0
     */
    //左上角圆角
    "loadRadiusTopLeft",
    // 右上角圆角
    "loadRadiusTopRight",
    // 左下角圆角
    "loadRadiusBottomLeft",
    // 右下角圆角
    "loadRadiusBottomRight",
    requireAll = false
)
fun loadImage(
    imageView: ImageView,
    source: Any? = null,
    error: Any? = null,
    placeholder: Any? = null,
    width: Int? = 0,
    height: Int? = 0,
    cacheEnable: Boolean? = true,
    circle: Boolean? = false,
    radius: Any? = null,
    radiusTopLeft: Any? = null,
    radiusTopRight: Any? = null,
    radiusBottomLeft: Any? = null,
    radiusBottomRight: Any? = null
) {
    // 获取当前的Activity
    val activity: Activity? = when (imageView.context) {
        is Activity -> {
            imageView.context as Activity
        }

        is Fragment -> {
            (imageView.context as Fragment).requireActivity()
        }

        else -> {
            null
        }
    }
    // 如果当前的Activity已经销毁，就不加载图片
    if (activity?.isDestroyed != false) {
        return
    }
    // 根据定义的 cacheEnable 参数来决定是否缓存
    val diskCacheStrategy =
        if (cacheEnable == true)
            DiskCacheStrategy.AUTOMATIC else DiskCacheStrategy.NONE
    // 设置编码格式，在Android 11(R)上面使用高清无损压缩格式 WEBP_LOSSLESS ，
    // Android 11 以下使用PNG格式，PNG格式时会忽略设置的 quality 参数。
    val encodeFormat =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
            Bitmap.CompressFormat.WEBP_LOSSLESS else Bitmap.CompressFormat.PNG

    // 加载原图
    val requestOptions = RequestOptions()
        .override(
            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL,
            com.bumptech.glide.request.target.Target.SIZE_ORIGINAL
        )

    // 对 http(s) 字符串 URL，自动包装为带 Authorization header 的 GlideUrl，避免 /file/getImg/ 接口 403
    val actualSource: Any? = if (source is String && (source.startsWith("http://") || source.startsWith("https://"))) {
        GlideUrl(
            source,
            LazyHeaders.Builder()
                .addHeader("Authorization", SharedPreferenceUtil.getString(Constant.Share.token))
                .build()
        )
    } else {
        source
    }

    // 设置图片加载
    val load = Glide.with(imageView)
        .setDefaultRequestOptions(requestOptions)
        .load(actualSource)
        .diskCacheStrategy(diskCacheStrategy)
        .encodeFormat(encodeFormat)

    // 设置错误图片
    error?.let {
        load.error(error)
    }

    // 设置占位图
    placeholder?.let {
        if (it is Drawable) {
            load.placeholder(it)
        }
        if (it is Int) {
            load.placeholder(it)
        }
    }

    // 设置宽高
    if ((width ?: 0) > 0 && (height ?: 0) > 0)
        load.override(width!!, height!!)

    // 判定是否设置了四个圆角
    if (radiusTopLeft != null || radiusTopRight != null || radiusBottomLeft != null || radiusBottomRight != null) {
        load.transform(
            CenterCrop(),
            GranularRoundedCorners(
                getSize(radiusTopLeft).toFloat(),
                getSize(radiusTopRight).toFloat(),
                getSize(radiusBottomRight).toFloat(),
                getSize(radiusBottomLeft).toFloat(),
            )
        )
    } else if (radius != null) {
        load.transform(CenterCrop(), RoundedCorners(getSize(radius)))
    } else if (circle == true) {
        // 设置圆形图片
        load.circleCrop()
    }

    // 设置图片到控件
    load.into(imageView)
}

/**
 * 设置通用adapter
 */
@BindingAdapter("viewHolder", "itemLayoutId")
fun setCommonAdapter(
    rv: RecyclerView,
    holderClass: Class<out BaseViewHolder<*, out ViewDataBinding>>,
    itemLayoutId: Int
) {
    val customAdapter = CommonAdapter(rv.context, itemLayoutId, holderClass)
    rv.adapter = customAdapter
}


/**
 * 获取尺寸
 * 这里只支持dp
 * [SizeUtils] 是尺寸工具类,可以在代码库中获取
 */
private fun getSize(size: Any?): Int {
    return try {
        SizeUtils.dp2px(size.toString().toFloat())
    } catch (e: Exception) {
        0
    }
}