package com.swago.room.adapter

import android.graphics.Bitmap
import android.graphics.Color
import android.text.Html
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ImageSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.swago.baseswago.cusview.SwagoLevelView
import com.swago.baseswago.im.IRoomChat
import com.swago.baseswago.im.RoomMsgType
import com.swago.room.R
import com.swago.room.adapter.bitmap.CenterAlignImageSpan
import com.swago.room.adapter.bitmap.CustomImageSpan
import com.swago.room.adapter.bitmap.HtmlImageGetter
import java.util.HashMap

/**
 *@date 2021/10/23 19:17
 *description:
 */
class RoomChatAdapter :
    BaseQuickAdapter<IRoomChat, BaseViewHolder>(R.layout.item_chat, arrayListOf()) {

    /**
     * 图标bitmap缓存
     */
    private val iconBitmapCachePool: HashMap<String, Bitmap> = HashMap()
    private val localImageKey = ArrayList<String>()

    companion object {
        const val LEVEL_KEY = "level"
    }

    init {
        localImageKey.add(LEVEL_KEY)
    }

    var showUserInfoDialog: ((iChatMsg: IRoomChat) -> Unit)? = null


    override fun convert(helper: BaseViewHolder, item: IRoomChat) {
        var count = 0
        helper.apply {
            val tvContent = itemView.findViewById<TextView>(R.id.tvContent)
            var span: SpannableString? = null
            when (item.getMsgType()) {
                RoomMsgType.ROOM_CHAT_TEXT -> {
                    val sb = StringBuffer()
                    sb.append(item.getSenderName())
                        .append("<img src='" + "file:///xx/")
                        .append(LEVEL_KEY).append(".png")
                        .append("'>")

                    if (item.getIsBenefit() == 1) {
                        count++
                        sb.append("<img src='" + "file:///android_asset/icon_chat_benefit.png")
                            .append("'>")
                    }
                    sb.append("：")


                    sb.append(item.getMsgContent())

                    val glideImageGetter = HtmlImageGetter(mContext, tvContent, 14, localImageKey)
                    val fromHtml = Html.fromHtml(sb.toString(), glideImageGetter, null)
                    span = SpannableString(fromHtml)
                    setHtml(span, helper, item)


                    if (span.length < item.getSenderName().length + count) {
                        span.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(widget: View) {
                                    showUserInfoDialog?.invoke(item)
                                }

                                override fun updateDrawState(ds: TextPaint) {}

                            },
                            0,
                            span.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    } else {
                        span.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(widget: View) {
                                    showUserInfoDialog?.invoke(item)
                                }

                                override fun updateDrawState(ds: TextPaint) {}

                            },
                            0,
                            item.getSenderName().length + count,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    }



                    if (item.getIsBenefit() == 1) {
                        setBackgroundRes(R.id.tvContent, R.drawable.shape_e87230_ddb558_all_20)
                    } else {
                        setBackgroundRes(R.id.tvContent, R.drawable.shape_white_20)
                    }
                }

                RoomMsgType.SYSTEM_MESSAGE -> {
                    span = SpannableString(item.getMsgContent())
                    setBackgroundRes(R.id.tvContent, R.drawable.shape_4bce98_20)
                }
                RoomMsgType.USER_ENTER_ROOM -> {
                    val sb = StringBuffer()
                    sb.append(item.getSenderName())
                        .append("<img src='" + "file:///xx/")
                        .append(LEVEL_KEY).append(".png")
                        .append("'>")

                    if (item.getIsBenefit() == 1) {
                        count++
                        sb.append("<img src='" + "file:///android_asset/icon_chat_benefit.png")
                            .append("'>")
                    }
                    sb.append("：")


                    sb.append(item.getMsgContent())

                    val glideImageGetter = HtmlImageGetter(mContext, tvContent, 14, localImageKey)
                    val fromHtml = Html.fromHtml(sb.toString(), glideImageGetter, null)
                    span = SpannableString(fromHtml)
                    setHtml(span, helper, item)

                    if (span.length < item.getSenderName().length + count) {
                        span.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(widget: View) {
                                    showUserInfoDialog?.invoke(item)
                                }

                                override fun updateDrawState(ds: TextPaint) {}

                            },
                            0,
                            span.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    } else {
                        span.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(widget: View) {
                                    showUserInfoDialog?.invoke(item)
                                }

                                override fun updateDrawState(ds: TextPaint) {}

                            },
                            0,
                            item.getSenderName().length + count,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    }

                    if (item.getIsBenefit() == 1) {
                        setBackgroundRes(R.id.tvContent, R.drawable.shape_4bce98_20)
                    } else {
                        when (item.getUserLevel()) {
                            in 0..37 -> {
                                setBackgroundRes(R.id.tvContent, R.drawable.shape_4bce98_20)
                            }
                            in 38..54 -> {
                                setBackgroundRes(R.id.tvContent, R.drawable.shape_6c55ff_20)
                            }
                            in 55..75 -> {
                                setBackgroundRes(R.id.tvContent, R.drawable.shape_6720d1_180c72_20)
                            }
                            in 76..97 -> {
                                setBackgroundRes(R.id.tvContent, R.drawable.shape_f8614b_8c2922_20)
                            }
                            in 98..1000 -> {
                                setBackgroundRes(R.id.tvContent, R.drawable.shape_434343_000000_20)
                            }
                        }
                    }

                }
            }
            tvContent.movementMethod = LinkMovementMethod.getInstance()
            tvContent.highlightColor = Color.TRANSPARENT
            tvContent.text = span
        }
    }


    private fun setHtml(span: SpannableString, helper: BaseViewHolder, item: IRoomChat) {
        try {
            val imageSpans = span.getSpans(0, span.length, ImageSpan::class.java)
            var i = 0
            val size = imageSpans.size
            while (i < size) {
                val imageSpan = imageSpans[i]
                val d = imageSpan.drawable
                val newImageSpan =
                    CenterAlignImageSpan(d, ImageSpan.ALIGN_BASELINE)
                val start = span.getSpanStart(imageSpan)
                val end = span.getSpanEnd(imageSpan)
                val clickableSpans = span.getSpans(start, end, ClickableSpan::class.java)
                if (clickableSpans != null && clickableSpans.isNotEmpty()) {
                    for (cs in clickableSpans) {
                        span.removeSpan(cs)
                    }
                }
                if (imageSpan.source != null && imageSpan!!.source!!.contains(LEVEL_KEY)) {
                    span.setSpan(
                        setLevel(item.getUserLevel(), helper.itemView as ViewGroup),
                        start,
                        end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                } else {
                    span.setSpan(newImageSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                }
                span.removeSpan(imageSpan)
                i++
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun setLevel(iSenderLevel: Int, viewGroup: ViewGroup): CustomImageSpan? {
        var level = iSenderLevel.toString()
        if (level.isNullOrEmpty()) {
            level = "1"
        }
        var bm = iconBitmapCachePool[level + "level"]
        if (bm == null) {
            val view = LayoutInflater.from(mContext)
                .inflate(R.layout.item_chat_level, viewGroup, false) as SwagoLevelView
            view.measure(
                View.MeasureSpec.makeMeasureSpec(
                    (1 shl 30) - 1,
                    View.MeasureSpec.AT_MOST
                ),
                View.MeasureSpec.makeMeasureSpec(
                    (1 shl 30) - 1,
                    View.MeasureSpec.AT_MOST
                )
            )
            view.setUserLevel(level.toInt())
            bm = convertViewToBitmap(view)
            if (bm != null) {
                iconBitmapCachePool[level + "level"] = bm
            }
        }

        return CustomImageSpan(mContext, bm, CustomImageSpan.ALIGN_FONTCENTER)
    }


    private fun convertViewToBitmap(view: View): Bitmap? {
        view.measure(
            View.MeasureSpec.makeMeasureSpec(
                (1 shl 30) - 1,
                View.MeasureSpec.AT_MOST
            ),
            View.MeasureSpec.makeMeasureSpec(
                (1 shl 30) - 1,
                View.MeasureSpec.AT_MOST
            )
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        view.buildDrawingCache()
        return view.drawingCache
    }
}