package com.quyunshuo.module.home.weight

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.annotation.IntDef
import androidx.annotation.Nullable
import com.quyunshuo.module.home.R
import java.lang.ref.WeakReference
import java.util.Random
import kotlin.math.acos
import kotlin.math.sin

internal class ProgressView : View {
    //进度条颜色
    private val FIRST_COLOR =  /*0xfffff000;*/-0x3624 /*0xff00574B;*/

    //背景颜色
    private val SECOND_COLOR = -0xd9a68

    private var mSecondWidth = 0
    private var mFirstWidth = 0

    private var mHeight = 0
    private var mSecondRadius = 0
    private var mFirstRadius = 0
    private val progressPadding = 15 //背景与内部进度条的间距

    private var currentValue = 0f
    var maxProgress: Float = 120f //进度条

    //画笔
    private var paint: Paint? = null
    private var rectF: RectF? = null
    private lateinit var leafBitmap: Bitmap
    private var mLeafWidth = 0
    private var mLeafHeight = 0
    private var mLeafInfos: MutableList<Leaf>? = null

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


    //1. 初始化
    @JvmOverloads
    constructor(context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int = 0) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        //2. 初始化画笔
        paint = Paint()
        paint!!.style = Paint.Style.FILL
        paint!!.color = FIRST_COLOR
        paint!!.isAntiAlias = true

        //3. 初始化矩形区域
        rectF = RectF()

        //4. 加载叶子图标
        leafBitmap = BitmapFactory.decodeResource(context.resources, R.drawable.icon_leaf)
        mLeafWidth = leafBitmap.getWidth() //设置叶子的宽
        mLeafHeight = 30 //设置叶子的高
        Log.e("zhen", " mLeafWidth: $mLeafWidth mLeafHeight: $mLeafHeight")
    }

    fun setFirstWidth(width: Int) {
        mFirstWidth = width
    }

    fun setFirstRadius(radius: Int) {
        mFirstRadius = radius
    }

    //视图尺寸变化回调
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // 设置视图高度
        mHeight = 105//设置y轴坐标
        val scaleFactor=0.8f

        //外围 设置背景宽度和圆角半径
     //   mSecondWidth = 1000 //设置x轴坐标
        mSecondWidth = (1150*scaleFactor).toInt() //设置x轴坐标
        mSecondRadius = ((mSecondWidth * 1f / 5) / 5).toInt() //设置整体比例

        //内部进度条 设置进度条宽度和圆角半径
        mFirstWidth = mSecondWidth - progressPadding - mSecondRadius
        mFirstRadius = mSecondRadius - progressPadding

        // 生成叶子对象
        mLeafInfos = LeafFactory(mFirstRadius - mLeafWidth, 6).generateLeafs() //叶子数量

        // 设置叶子对象的初始坐标
        for (i in mLeafInfos!!.indices) {
            val leaf = mLeafInfos!![i]
            leaf.x = (mFirstWidth - mFirstRadius - (i * 50)).toFloat() // 根据具体需求设置 x 坐标
            leaf.y = 0f // 设置 y 坐标
        }

        Log.e(
            "zhen", " mSecondWidth: " + mSecondWidth + " mHeight: " + mHeight +
                    " mSecondRadius: " + mSecondRadius + " mFirstWidth: " + mFirstWidth + " mFirstRadius: " + mFirstRadius
        )

    }

    //设置当前进度
    fun setCurrentProgress(currentProgress: Float) {
        Log.e("zhen", "currentProgress: $currentProgress:$maxProgress:$mFirstWidth")
        if (currentProgress > maxProgress) return

        // 计算当前进度值对应的宽度
        currentValue = currentProgress / maxProgress * mFirstWidth

        // 触发重绘
        invalidate()
    }

    //绘制视图
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        //画布移动
        canvas.translate(mSecondRadius.toFloat(), (mHeight / 2).toFloat())

        //画背景左半圆
        paint!!.style = Paint.Style.FILL
        paint!!.color = SECOND_COLOR
        rectF!!.left = -mSecondRadius.toFloat()
        rectF!!.top = -mSecondRadius.toFloat()
        rectF!!.right = mSecondRadius.toFloat()
        rectF!!.bottom = mSecondRadius.toFloat()
        canvas.drawArc(rectF!!, 90f, 180f, false, paint!!)

        //画背景右半圆
        rectF!!.left = (mSecondWidth - 3 * mSecondRadius).toFloat()
        rectF!!.top = -mSecondRadius.toFloat()
        rectF!!.right = (mSecondWidth - mSecondRadius).toFloat()
        rectF!!.bottom = mSecondRadius.toFloat()
        canvas.drawArc(rectF!!, -90f, 180f, false, paint!!)

        //画背景中间方形
        rectF!!.left = 0f
        rectF!!.top = -mSecondRadius.toFloat()
        rectF!!.right = (mSecondWidth - 2 * mSecondRadius).toFloat()
        rectF!!.bottom = mSecondRadius.toFloat()
        canvas.drawRect(rectF!!, paint!!)

        //绘制进度条半圆
        paint!!.color = FIRST_COLOR
        val leftValue = if ((mFirstRadius - currentValue) > 0) (mFirstRadius - currentValue) else 0f
        val angel = Math.toDegrees(acos((leftValue / mFirstRadius).toDouble())).toFloat()
        rectF!!.left = -mFirstRadius.toFloat()
        rectF!!.top = -mFirstRadius.toFloat()
        rectF!!.right = mFirstRadius.toFloat()
        rectF!!.bottom = mFirstRadius.toFloat()
        canvas.drawArc(rectF!!, 180 - angel, 2 * angel, false, paint!!)

        //绘制进度条方形
        if (currentValue >= mFirstRadius) {
            currentValue = if (currentValue > mFirstWidth) mFirstWidth.toFloat() else currentValue
            rectF!!.left = 0f
            rectF!!.top = -mFirstRadius.toFloat()
            rectF!!.right = currentValue - mFirstRadius
            rectF!!.bottom = mFirstRadius.toFloat()
            canvas.drawRect(rectF!!, paint!!)
            Log.d(TAG, rectF!!.right.toString() + ":mFirstWidth onDraw: " + currentValue)
        }


        //落叶纷飞
        if (currentValue > 0 && currentValue < mFirstWidth) {
            val currentTime = System.currentTimeMillis()
            for (i in mLeafInfos!!.indices) {
                val leaf = mLeafInfos!![i]
                val delay = ((currentTime - leaf.startTime) % Leaf.CIRCLE_TIME).toInt()
                leaf.x =
                    mFirstWidth - mFirstRadius - delay * (mFirstWidth * 1f / Leaf.CIRCLE_TIME)
                if (leaf.x + mFirstRadius + mLeafWidth < currentValue) continue
                leaf.y =
                    (leaf.amplitude * sin(2 * Math.PI / Leaf.CIRCLE_TIME * delay + leaf.phaseOffeset)).toFloat()
                // 通过Matrix控制叶子旋转
                val matrix = Matrix()
                matrix.postTranslate(leaf.x, leaf.y)
                // 根据叶子旋转方向确定叶子旋转角度
                val rotate = if (leaf.rotateOrientation) leaf.x % 360f else -leaf.x % 360
                matrix.postRotate(rotate, leaf.x + mLeafWidth / 2, leaf.y)
                canvas.drawBitmap(leafBitmap!!, matrix, paint)
            }
        }


        //绘制旋转风车               右边圆的属性
        paint!!.color = Color.WHITE
        paint!!.style = Paint.Style.STROKE
        paint!!.strokeWidth = 10f
        val x = (mSecondWidth - 2 * mSecondRadius).toFloat()
        val y = 0f
        canvas.drawCircle(x, y, mSecondRadius.toFloat(), paint!!) //飘落的逻辑
        paint!!.style = Paint.Style.FILL
        paint!!.color = -0x3624
        canvas.drawCircle(x, y, (mSecondRadius - 5).toFloat(), paint!!)
    }

    private fun drawLeaf(canvas: Canvas) {
        // 绘制叶子的代码
        for (i in mLeafInfos!!.indices) {
            val leaf = mLeafInfos!![i]
            // 绘制叶子的逻辑
            canvas.drawBitmap(leafBitmap!!, leaf.x, leaf.y, paint)
        }
    }

    @IntDef(*[Amplitude.SMALL, Amplitude.MIDDLE, Amplitude.LARGE])
    annotation class Amplitude {
        companion object {
            const val SMALL: Int = 0
            const val MIDDLE: Int = 1
            const val LARGE: Int = 2
        }
    }

    //叶子对象与工厂类
    class Leaf {
        //振幅大小
        var amplitude: Int = 0

        //初始相位偏移
        var phaseOffeset: Int = 0

        //旋转方向
        var rotateOrientation: Boolean = false

        //延时时间
        var startTime: Long = 0

        //x位置取决于初始位置偏移
        var x: Float = 0f

        //y位置取决于振幅，初始相位
        var y: Float = 0f

        override fun toString(): String {
            return "Leaf{" +
                    "amplitude=" + amplitude +
                    ", phaseOffeset=" + phaseOffeset +
                    ", rotateOrientation=" + rotateOrientation +
                    ", startTime=" + startTime +
                    ", x=" + x +
                    ", y=" + y +
                    '}'
        }

        companion object {
            var CIRCLE_TIME: Long = 3000 //一个周期所需要的时间
        }
    }
    class LeafFactory(private val mHeight: Int, private val mLeafSize: Int) {
        private val random = Random()
        var randomValue: Int = 0

        fun generateLeafs(): MutableList<Leaf> {
            val mLeafsInfo: MutableList<Leaf> = ArrayList()
            for (i in 0 until mLeafSize) {
                mLeafsInfo.add(generateLeaf())
            }
            return mLeafsInfo
        }

        private fun generateLeaf(): Leaf {
            val leaf = Leaf()
            randomValue = random.nextInt(3)
            when (randomValue) {
                Amplitude.SMALL -> leaf.amplitude = (mHeight * 1f / 3).toInt()
                Amplitude.MIDDLE -> leaf.amplitude = (mHeight * 2f / 3).toInt()
                Amplitude.LARGE -> leaf.amplitude = (mHeight * 3f / 3).toInt()
            }
            leaf.startTime = random.nextInt(Leaf.CIRCLE_TIME.toInt()).toLong()
            leaf.phaseOffeset = random.nextInt(8)
            leaf.rotateOrientation = random.nextBoolean()
            Log.e("zhen", "生成一个叶子：$leaf")
            return leaf
        }
    }

    //动画与叶子添加
    @SuppressLint("ObjectAnimatorBinding")
    fun addLeaf(leaf: Leaf) {
        if (mLeafInfos == null) {
            mLeafInfos = ArrayList()
        }
        mLeafInfos!!.add(leaf)

        // 启动动画
        val animator = ValueAnimator.ofFloat(0f, (mFirstWidth - mFirstRadius).toFloat())
        animator.setDuration(1000)
        animator.repeatCount = ValueAnimator.INFINITE
        animator.repeatMode = ValueAnimator.REVERSE

        // 使用WeakReference来持有外部类的引用
        val weakRef = WeakReference(this)
        animator.addUpdateListener { animation: ValueAnimator? ->
            val instance = weakRef.get()
            instance?.invalidate()
        }
        animator.start()
    }

    companion object {
        private const val TAG = "ProgressView"
    }
}