package com.example.base.widget


import android.animation.ArgbEvaluator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.base.extensions.dp2px
import kotlin.math.abs

/**
 * @date 2021-08-12 13:57
 * @desc 加载中View
 */
class LoadingView  : View {

    constructor(context: Context?) : super(context)

    constructor(context: Context?, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context?, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var radius: Float = 0.toFloat()
    private var radiusOffset: Float = 0.toFloat()
    // 不是固定不变的，当width为30dp时，它为2dp，当宽度变大，这个也会相应的变大
    private var stokeWidth = 2f
    private val argbEvaluator = ArgbEvaluator()
    private val startColor = Color.parseColor("#CCCCCC")
    private val endColor = Color.parseColor("#333333")
    private var lineCount = 12 // 共12条线
    private var avgAngle = 360f / lineCount
    private var time = 0 // 重复次数
    private var centerX: Float = 0.toFloat()
    private var centerY: Float = 0.toFloat() // 中心x，y

    private val increaseTask = Runnable {
        time++
        invalidate()
    }

    init {
        stokeWidth = stokeWidth.dp2px()
        paint.strokeWidth = stokeWidth
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        radius = (measuredWidth / 2).toFloat()
        radiusOffset = radius / 2.5f

        centerX = (measuredWidth / 2).toFloat()
        centerY = (measuredHeight / 2).toFloat()

        stokeWidth *= measuredWidth * 1f / 30f.dp2px()
        paint.strokeWidth = stokeWidth

    }

    override fun onDraw(canvas: Canvas) {
        // 1 2 3 4 5
        // 2 3 4 5 1
        // 3 4 5 1 2
        // ...
        for (i in lineCount - 1 downTo 0) {
            val temp = abs(i + time) % lineCount
            val fraction = (temp + 1) * 1f / lineCount
            val color = argbEvaluator.evaluate(fraction, startColor, endColor) as Int
            paint.color = color

            val startX = centerX + radiusOffset
            val endX = startX + radius / 3f
            canvas.drawLine(startX, centerY, endX, centerY, paint)
            // 线的两端画个点，看着圆滑
            canvas.drawCircle(startX, centerY, stokeWidth / 2, paint)
            canvas.drawCircle(endX, centerY, stokeWidth / 2, paint)
            canvas.rotate(avgAngle, centerX, centerY)
        }
        postDelayed(increaseTask, 80)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        removeCallbacks(increaseTask)
    }
}
