package com.easy.clean.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 android.widget.TextView
import com.easy.clean.R
import com.easy.clean.databinding.ItemBatteryHeadBinding
import com.easy.clean.ui.adapter.CommonViewHolder
import com.easy.clean.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter

class BatteryHead(
    val min: Int,
    val p: Float = 0.50f,
    val temper: String = "36℃",
    val v: String = "3.6V",
    val power: String = "4753mAh",
)

class BatteryHeadAdapter : BaseQuickAdapter<BatteryHead, CommonViewHolder>() {

    override fun onBindViewHolder(
        holder: CommonViewHolder,
        position: Int,
        item: BatteryHead?,
    ) {
        item ?: return
        val binding = ItemBatteryHeadBinding.bind(holder.itemView)
        binding.tvCapacity.text = "${(item.p * 100).toInt()}%"

        binding.iv.setImageLevel((item.p * 100).toInt())

        setText(binding.tvTime, item.min)
        setText(binding.tvVideo, (item.min * 0.5).toInt())
        setText(binding.tvMusic, (item.min * 0.8).toInt())
        binding.tvWendu.text = item.temper
        binding.tvV.text = item.v
        binding.tvAh.text = item.power
    }

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

    fun setText(item: TextView, time: Int) {
        var h = time / 60
        var m = time % 60
        val strH = if (h < 10) "0$h" else h.toString()
        val strM = if (m < 10) "0$m" else m.toString()
        val text1 = "$strH h "
        val text2 = "$strM m"
        item.text = buildSpannableString(text1, strH)
        item.append(buildSpannableString(text2, strM))
    }

    fun buildSpannableString(fullString: String, tagString: String): 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(18, true),
            start, end,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        return spannableString
    }
}