package com.sd.cavphmi.ui.view

import android.animation.Animator
import android.animation.Animator.AnimatorListener
import android.animation.AnimatorInflater
import android.animation.AnimatorSet
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.isNotEmpty
import com.sd.cavphmi.R
import com.sd.cavphmi.bean.WarningBean
import com.sd.cavphmi.databinding.EarlyTipBaseBinding


/**预警气泡**/
class RoadWarn : LinearLayout {

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

    //重心
    private var mGravity = 0

    private var setAni: AnimatorSet? = null

    private fun init() {
        setAni = AnimatorInflater.loadAnimator(context, R.animator.early_tip_ani) as AnimatorSet

        setAni?.addListener(object : AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
            }

            override fun onAnimationEnd(animation: Animator) {
//                println("--------------动画结束")
                removeAllViews()
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }

        })
    }

    fun setMyOrientation(orientation: Int) {
        this.orientation = orientation
        if (orientation == HORIZONTAL) {
            mGravity = Gravity.CENTER_VERTICAL
        } else {
            mGravity = Gravity.CENTER_HORIZONTAL
        }
    }

    fun setWarnBean(warningBean: WarningBean) {
//        println("-----${setAni?.isRunning}")
        //加载动画的时候什么也不干,或者里面有子View
        if (setAni?.isRunning == true || isNotEmpty()) {
            return
        }
        removeAllViews()
        val params = (layoutParams as LayoutParams).apply {
            gravity = mGravity
        }
        loadChildView(warningBean, params)
        setAni!!.apply {
            setTarget(this@RoadWarn)
            start()
        }
    }


    //    private fun loadChildView(type: Int, parentParam: LinearLayout.LayoutParams) {
    private fun loadChildView(
        bean: WarningBean,
        parentParam: LayoutParams
    ) {
        lateinit var baseView: View
        var binding = EarlyTipBaseBinding.inflate(LayoutInflater.from(context))
        baseView = binding.root
        addView(baseView, parentParam)
//        DisplayUtil.forceMeasure(baseView)
        binding.bean = bean
    }


}