package com.abbidot.tracker.ui.fragment.map.googlemap

import android.content.Context
import android.graphics.*
import android.text.TextUtils
import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.DrawableCompat
import com.abbidot.tracker.R
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.util.ImageUtil
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.qmuiteam.qmui.util.QMUIDisplayHelper

/**
 *Created  by .yzq on 2022/1/13/013.
 * @link
 * @description:谷歌地图BitmapHelper
 */
object GoogleBitmapHelper {

    /**
     * 自定义定位图标,宠物头像，自定义位图
     *
     * @param id 本地底部背景圆形图片
     * @param headUrl 网络宠物的头像url
     */
    suspend fun headToBitmap(
        context: Context, @DrawableRes id: Int, headUrl: String, petType: Int
    ): Bitmap? {
        var headUrlBitmap = if (TextUtils.isEmpty(headUrl)) {
            var headResId = R.drawable.icon_pet_default_head_svg
            if (petType == ConstantInt.CatPetType) headResId = R.drawable.icon_pet_default_head_svg
            ImageUtil.getBitmapFromDrawableAndSvg(context, headResId)
        } else {
            ImageUtil.getImageBitmapByUrl(context, headUrl)
        }
        if (null == headUrlBitmap) headUrlBitmap = BitmapFactory.decodeResource(
            context.resources, R.drawable.pic_avatar_df
        )
        return combineBitmap(ImageUtil.getBitmapFromDrawableAndSvg(context, id), headUrlBitmap!!)
//        return combineBitmap(BitmapFactory.decodeResource(context.resources, id), headUrlBitmap)
    }

    /**
     * 先等比压缩，然后合并两张bitmap为一张
     *
     * @param background
     * @param foreground
     * @return Bitmap
     */
    private fun combineBitmap(background: Bitmap?, foreground: Bitmap): Bitmap? {
        if (null == background) {
            return null
        }
        val bgWidth = background.width
        val bgHeight = background.height
        var foregroundBitmap = ImageUtil.zoomImg(foreground, bgWidth, bgWidth)
        foregroundBitmap = toRoundBitmap(foregroundBitmap, bgWidth, bgHeight)
//        val fgWidth = foregroundBitmap.width
//        val fgHeight = foregroundBitmap.height
//        val newmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888)
//        val canvas = Canvas(newmap)
//        canvas.drawBitmap(background, 0f, 0f, null)
//        canvas.drawBitmap(foregroundBitmap, (bgWidth - fgWidth) / 2f, (bgHeight - fgHeight) / 2f,
//                null)
//        canvas.save()
//        canvas.restore()
        return ImageUtil.combineBitmap(background, foregroundBitmap)
    }

    /**
     * 转换为圆形bitmap
     *
     * @param bitmap
     * @param bgWidth  底下圆形的宽
     * @param bgHeight 底下圆形的高
     * @return
     */
    private fun toRoundBitmap(bitmap: Bitmap, bgWidth: Int, bgHeight: Int): Bitmap {
        //算出底下圆形直径
//        val dia = (bgHeight - (bgHeight - bgWidth)).toFloat()
        val dia = bgWidth.toFloat()
        //底下圆形半径
        val radius = dia / 2f

        //前面同上，绘制图像分别需舆bitmap,canvas , paint对象
//        val bp = Bitmap.createScaledBitmap(bitmap, bgWidth, bgHeight, true)
        val bp = Bitmap.createScaledBitmap(bitmap, bgWidth, bgWidth, true)
        val bm = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bm)
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        //这里斋要先画出一个圈
        canvas.drawCircle(radius, radius, radius - (bgHeight - bgWidth) / 6f, paint)
        //圆画好之后将画笔重置一下
        paint.reset()
        //设置图像合成模式，该模式为只在源图像和目标图相交的地方绘制源图
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(bp, 0f, 0f, paint)
        return bm
    }


    /**
     * 在图片上写文字
     */
    fun imageUpNumberBitmap(
        context: Context,
        @DrawableRes id: Int,
        text: String = "",
        typeface: Typeface = Typeface.DEFAULT
    ): Bitmap {
        val bgBitmap = BitmapFactory.decodeResource(context.resources, id)
        val newBitmap =
            Bitmap.createBitmap(bgBitmap.width, bgBitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newBitmap)
        canvas.drawBitmap(bgBitmap, 0f, 0f, null)
        val paint = Paint()
        paint.color = ContextCompat.getColor(context, R.color.txt_black_color)
        paint.textSize = QMUIDisplayHelper.sp2px(context, 16).toFloat()
        if (!TextUtils.isEmpty(text)) paint.typeface = typeface
        //文字宽度
        val textWidth = paint.measureText(text)
        val fontMetrics = paint.fontMetrics
        //文字高度
        val textHeight = fontMetrics.bottom - fontMetrics.top

        val x = bgBitmap.width / 2f - textWidth / 2
        val y = bgBitmap.width.toFloat() - textHeight / 2 - (bgBitmap.height - bgBitmap.width) / 2
        canvas.drawText(text, x, y, paint)
        canvas.save()
        canvas.restore()
        return newBitmap
    }

    /**
     * 谷歌demo自定义MarkerOptions，自定义位图
     * https://developers.google.cn/codelabs/maps-platform/maps-platform-101-android#5
     *
     * Demonstrates converting a [Drawable] to a [BitmapDescriptor],
     * for use as a marker icon. Taken from ApiDemos on GitHub:
     * https://github.com/googlemaps/android-samples/blob/main/ApiDemos/kotlin/app/src/main/java/com/example/kotlindemos/MarkerDemoActivity.kt
     */
    fun vectorToBitmap(
        context: Context, @DrawableRes id: Int, @ColorInt color: Int
    ): BitmapDescriptor {
        val vectorDrawable = ResourcesCompat.getDrawable(context.resources, id, null)
        if (vectorDrawable == null) {
            Log.e("BitmapHelper", "Resource not found")
            return BitmapDescriptorFactory.defaultMarker()
        }
        val bitmap = Bitmap.createBitmap(
            vectorDrawable.intrinsicWidth, vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
        DrawableCompat.setTint(vectorDrawable, color)
        vectorDrawable.draw(canvas)
        return BitmapDescriptorFactory.fromBitmap(bitmap)
    }
}