package com.rgt.superr.ui.batteryinfo

import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.StyleSpan
import android.view.ViewGroup
import com.rgt.superr.R
import com.rgt.superr.databinding.ItemBatteryElectricBinding
import com.rgt.superr.databinding.ItemBatteryHeadBinding
import com.rgt.superr.ui.adapter.CommonViewHolder
import com.rgt.superr.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter

class BatteryOtherBean(
    val map: HashMap<String, Any>,
)

class BatteryOtherAdapter(
    val layout: Int
) : BaseQuickAdapter<BatteryOtherBean, CommonViewHolder>() {

    override fun onBindViewHolder(
        holder: CommonViewHolder,
        position: Int,
        item: BatteryOtherBean?
    ) {
        item ?: return

        when (layout) {
            R.layout.item_battery_head -> {
                val binding = ItemBatteryHeadBinding.bind(holder.itemView)

                val hour = (item.map["hour"] as Int?) ?: 0
                val min = (item.map["min"] as Int?) ?: 0

                val h = if (hour < 10) "0${hour}" else hour.toString()
                val m = if (min < 10) "0${min}" else min.toString()
                val text1 = "$h h "
                val text2 = "$m m"
                binding.tvTime.text = buildSpannableString(text1, h)
                binding.tvTime.append(buildSpannableString(text2, m))
            }

            R.layout.item_battery_electric -> {
                val binding = ItemBatteryElectricBinding.bind(holder.itemView)

                val current1 = "%.1f".format((item.map["current1"] as Float?) ?: 0.0)
                val current2 = "%.1f".format((item.map["current2"] as Float?) ?: 0.0)

                val text1 = "$current1 mA"
                val text2 = "$current2 mA"

                binding.tvRealTimeCurrent.text = buildSpannableString(text1, current1)
                binding.tvAveCurrent.text = buildSpannableString(text2, current2)
            }
        }

    }

    override fun onCreateViewHolder(
        context: Context,
        parent: ViewGroup,
        viewType: Int
    ): CommonViewHolder {
        return CommonViewHolder(layout.inflate(parent))
    }

    fun buildSpannableString(fullString: String, tagString: String, size: Int = 32): SpannableString {
        val spannableString = SpannableString(fullString)
        val start = fullString.indexOf(tagString)
        val end = start + tagString.length

        spannableString.setSpan(
            StyleSpan(Typeface.BOLD),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            AbsoluteSizeSpan(size, true),
            start, end,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        return spannableString
    }
}