package com.abbidot.tracker.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.animation.doOnEnd
import androidx.core.content.ContextCompat
import com.abbidot.baselibrary.util.AppUtils
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.R
import com.abbidot.tracker.util.ImageUtil
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import kotlin.math.abs


/**
 *Created  by .yzq on 2024/2/7/007.
 * @link
 * @description:
 */
class InviteFamilyAnimateView : View {

    private lateinit var mContext: Context
    private var mWidth = 0
    private var mHeight = 0

    private var mScreenWidth = 0

    //最大圆的半径
    private var mMaxCircleRadius = 0f

    //邮件矩形长度
    private val mMailRectLength = QMUIDisplayHelper.dpToPx(100)

    //最大图片大长度
    private val mMaxImageLength = QMUIDisplayHelper.dpToPx(50)

    //黄色十字长度
    private val mYellowCrossLength = QMUIDisplayHelper.dpToPx(18)

    //底部矩形露出的长度
    private val mOutPartRectLength = ((mMailRectLength / 2f) / 3f) * 2

    private lateinit var mCirclePaint: Paint
    private lateinit var mMailPaint: Paint
    private lateinit var mImagePaint: Paint

    private lateinit var mMailPath: Path
    private lateinit var mImagePath: Path

    private lateinit var mFirstRectF: RectF

    //    private lateinit var mSecondRectF: RectF
    private lateinit var mRectF: RectF

    private var mBitmap1: Bitmap? = null
    private var mBitmap2: Bitmap? = null
    private var mBitmap3: Bitmap? = null
    private var mBitmap4: Bitmap? = null

    private var mBitmap1Angle = -120f
    private var mBitmap2Angle = -35f
    private var mBitmap3Angle = -75f
    private var mBitmap4Angle = -135f

    private var mBitmap1RotationAnimator: ValueAnimator? = null
    private var mBitmap2RotationAnimator: ValueAnimator? = null
    private var mBitmap3RotationAnimator: ValueAnimator? = null
    private var mBitmap4RotationAnimator: ValueAnimator? = null
    private var isStartAnim = false

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    ) {
        init(context)
    }

    private fun init(context: Context) {
        mContext = context
        //禁用硬件加速,防止返回到界面多次执行onDraw
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        mScreenWidth = QMUIDisplayHelper.getScreenWidth(context)

        mCirclePaint = Paint()
        mMailPaint = Paint()
        mImagePaint = Paint()

        mMailPath = Path()
        mImagePath = Path()

        mFirstRectF = RectF()
        mRectF = RectF()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        mBitmap1 =
            ImageUtil.getBitmapFromDrawableAndSvg(mContext, R.drawable.invite_family_animate_image1)
        mBitmap2 =
            ImageUtil.getBitmapFromDrawableAndSvg(mContext, R.drawable.invite_family_animate_image2)
        mBitmap3 =
            ImageUtil.getBitmapFromDrawableAndSvg(mContext, R.drawable.invite_family_animate_image3)
        mBitmap4 =
            ImageUtil.getBitmapFromDrawableAndSvg(mContext, R.drawable.invite_family_animate_image4)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        mWidth = maxOf(measuredWidth, mScreenWidth)
        mMaxCircleRadius = mWidth / 2f
        //最大半圆半径+露出最大图片/2+底部矩形露出部分长度
        mHeight = (mMaxCircleRadius + mMaxImageLength / 2 + mOutPartRectLength).toInt()
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        LogUtil.e("InviteFamilyAnimateView----------------onSizeChanged")
        super.onSizeChanged(w, h, oldw, oldh)
    }


    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        LogUtil.e("InviteFamilyAnimateView----------------onLayout")
        super.onLayout(changed, left, top, right, bottom)
        if (!isStartAnim) planetRotationAnimation()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.apply {
            drawCircle(this)
            drawMail(this)
            drawImage(this)
        }
    }

    private fun drawCircle(canvas: Canvas) {
        canvas.apply {
            mFirstRectF.apply {
                left = 0f
                top = mMaxImageLength / 2f
                right = mWidth.toFloat()
                bottom = mMaxCircleRadius * 2 + mMaxImageLength / 2f
            }
            mCirclePaint.color = ContextCompat.getColor(mContext, R.color.block_color)
            drawArc(mFirstRectF, -180f, 180f, true, mCirclePaint)

            val secondCircleSpace = mMaxCircleRadius / 4
            mRectF.apply {
                left = mFirstRectF.left + secondCircleSpace
                top = mFirstRectF.top + secondCircleSpace
                right = mFirstRectF.right - secondCircleSpace
                bottom = mFirstRectF.bottom - secondCircleSpace
            }
            mCirclePaint.color = ContextCompat.getColor(mContext, R.color.white_gray_color)
            drawArc(mRectF, -180f, 180f, true, mCirclePaint)

            val thirdCircleSpace = secondCircleSpace * 2
            mRectF.apply {
                left = mFirstRectF.left + thirdCircleSpace
                top = mFirstRectF.top + thirdCircleSpace
                right = mFirstRectF.right - thirdCircleSpace
                bottom = mFirstRectF.bottom - thirdCircleSpace
            }
            mCirclePaint.color = ContextCompat.getColor(mContext, R.color.block_color3)
            drawArc(mRectF, -180f, 180f, true, mCirclePaint)
        }
    }

    private fun drawMail(canvas: Canvas) {
        val halfWith = mWidth / 2f
        val halfMailRectLength = mMailRectLength / 2f
        mMailPath.apply {
            //画下面填充白色矩形，填充合成图形的空白
            mRectF.apply {
                left = halfWith - halfMailRectLength
                top = mHeight - halfMailRectLength
                right = halfWith + halfMailRectLength
                bottom = mHeight - mMailRectLength / 3f
            }
            mMailPaint.strokeWidth = 0f
            mMailPaint.color = ContextCompat.getColor(mContext, R.color.white)
            canvas.drawRect(mRectF, mMailPaint)

            //画最上面的三角形
            moveTo(halfWith, (mHeight - mMailRectLength).toFloat())
            lineTo(mRectF.left, mRectF.top)
            lineTo(mRectF.right, mRectF.top)
            close()
            canvas.drawPath(mMailPath, mMailPaint)
            reset()

            //画矩形
            mRectF.apply {
                left = halfWith - (halfMailRectLength / 5f) * 4
                top =
                    mHeight - halfMailRectLength - (halfMailRectLength - (halfMailRectLength / 2.5f))
                right = halfWith + (halfMailRectLength / 5f) * 4
                bottom = mHeight - (halfMailRectLength / 6f) * 2
            }
            mMailPaint.color = ContextCompat.getColor(mContext, R.color.select_color)
            canvas.drawRect(mRectF, mMailPaint)

            //画右边的三角形
            moveTo(halfWith + halfMailRectLength, mHeight - halfMailRectLength)
            lineTo(halfWith + halfMailRectLength, mHeight.toFloat())
            lineTo(halfWith - halfMailRectLength, mHeight.toFloat())
            close()
            mMailPaint.color = ContextCompat.getColor(mContext, R.color.white_color10)
            canvas.drawPath(mMailPath, mMailPaint)
            reset()

            //画左边的三角形
            moveTo(halfWith - halfMailRectLength, mHeight - halfMailRectLength)
            lineTo(halfWith - halfMailRectLength, mHeight.toFloat())
            lineTo(halfWith + halfMailRectLength, mHeight.toFloat())
            close()
            mMailPaint.color = ContextCompat.getColor(mContext, R.color.white)
            canvas.drawPath(mMailPath, mMailPaint)
            reset()

            //画绿色的十字
            mMailPaint.strokeWidth = AppUtils.dpToPx(2.5f)
            mMailPaint.color = ContextCompat.getColor(mContext, R.color.select_color2)
            val linStartX1 = halfWith - mYellowCrossLength / 2f
            val linStartY1 = mHeight - halfMailRectLength - halfMailRectLength / 6f
            //画横线
            canvas.drawLine(
                linStartX1, linStartY1, linStartX1 + mYellowCrossLength, linStartY1, mMailPaint
            )
            val linStartY2 = linStartY1 - mYellowCrossLength / 2
            //画竖线
            canvas.drawLine(
                halfWith, linStartY2, halfWith, linStartY2 + mYellowCrossLength, mMailPaint
            )
        }
    }

    private fun drawImage(canvas: Canvas) {
        val halfWith = mWidth / 2f
//        mImagePath.apply {
//            moveTo(0f, mMaxCircleRadius + mMaxImageLength / 2f)
//            quadTo(
//                halfWith,
//                -mMaxCircleRadius*2,
//                mWidth.toFloat(),
//                mMaxCircleRadius + mMaxImageLength / 2f
//            )
//            canvas.drawPath(this, mMailPaint)
//            reset()
//        }

        canvas.apply {
            val circleY = mMaxCircleRadius + mMaxImageLength / 2f

            mBitmap1?.let {
                val point = Utils.getPointOnCircleArc(
                    halfWith, circleY, mMaxCircleRadius, mBitmap1Angle.toDouble()
                )
                //矫正x轴
                val checkX = abs(1f / 180f * mBitmap1Angle) + 1
                drawBitmap(it, point[0] - it.width * checkX, point[1] - it.height, null)
            }
            mBitmap2?.let {
                val point = Utils.getPointOnCircleArc(
                    halfWith, circleY, mMaxCircleRadius, mBitmap2Angle.toDouble()
                )
                //矫正x轴
                val checkX = abs(1f / 180f * mBitmap2Angle) + 1
                drawBitmap(it, point[0] - it.width * checkX, point[1] - it.height, null)
            }

            val secondCircleSpace = mMaxCircleRadius / 4
            mBitmap3?.let {
                val point = Utils.getPointOnCircleArc(
                    halfWith,
                    circleY,
                    mMaxCircleRadius - secondCircleSpace,
                    mBitmap3Angle.toDouble()
                )
                //矫正x轴
                val checkX = abs(1f / 180f * mBitmap3Angle) + 1
                drawBitmap(it, point[0] - it.width * checkX, point[1] - it.height, null)
            }

            mBitmap4?.let {
                val point = Utils.getPointOnCircleArc(
                    halfWith,
                    circleY,
                    mMaxCircleRadius - secondCircleSpace * 2,
                    mBitmap4Angle.toDouble()
                )
                //矫正x轴
                val checkX = abs(1f / 180f * mBitmap4Angle) + 1
                drawBitmap(it, point[0] - it.width * checkX, point[1] - it.height, null)
            }
        }
    }

    /**
     * 星球旋转动画
     */
    private fun planetRotationAnimation() {
        isStartAnim = true
        mBitmap1RotationAnimator = setRotationAnimator(mBitmap1Angle, 0f).apply {
            duration = 10 * 1000
            addUpdateListener {
                mBitmap1Angle = it.animatedValue as Float
                postInvalidate()
            }
        }
        mBitmap1RotationAnimator?.apply {
            if (!isRunning) {
                LogUtil.e("木有开始")
                start()
            }
        }

        mBitmap2RotationAnimator = setRotationAnimator(mBitmap2Angle, -180f).apply {
            duration = 25 * 1000
            addUpdateListener {
                mBitmap2Angle = it.animatedValue as Float
//                postInvalidate()
            }
        }
        mBitmap2RotationAnimator?.apply {
            if (!isRunning) {
                start()
            }
        }

        mBitmap3RotationAnimator = setRotationAnimator(mBitmap3Angle, -180f).apply {
            duration = 20 * 1000
            addUpdateListener {
                mBitmap3Angle = it.animatedValue as Float
//                postInvalidate()
            }
        }
        mBitmap3RotationAnimator?.apply {
            if (!isRunning) {
                start()
            }
        }

        mBitmap4RotationAnimator = setRotationAnimator(mBitmap4Angle, 0f).apply {
            duration = 15 * 1000
            addUpdateListener {
                mBitmap4Angle = it.animatedValue as Float
//                postInvalidate()
            }
        }
        mBitmap4RotationAnimator?.apply {
            if (!isRunning) {
                start()
            }
        }
    }

    private fun setRotationAnimator(startValue: Float, endValue: Float): ValueAnimator {
        return ValueAnimator.ofFloat(startValue, endValue).apply {
            repeatMode = ValueAnimator.REVERSE
            //匀速变化
            interpolator = LinearInterpolator()
            doOnEnd {
                repeatCount = ValueAnimator.INFINITE
                if (startValue == 0f || endValue == -180f) {
                    setFloatValues(-180f, 0f)
                } else {
                    setFloatValues(0f, -180f)
                }
                start()
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mBitmap1RotationAnimator?.cancel()
        mBitmap2RotationAnimator?.cancel()
        mBitmap3RotationAnimator?.cancel()
        mBitmap4RotationAnimator?.cancel()
        if (null != mBitmap1) {
//            mBitmap1?.recycle()
            mBitmap1 = null
        }
        if (null != mBitmap2) {
//            mBitmap2?.recycle()
            mBitmap2 = null
        }
        if (null != mBitmap3) {
//            mBitmap3?.recycle()
            mBitmap3 = null
        }
        if (null != mBitmap4) {
//            mBitmap4?.recycle()
            mBitmap4 = null
        }
    }
}