package com.swago.room.giftdandao

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Service
import android.content.Context
import android.os.Vibrator
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.animation.BounceInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.swago.baseswago.model.live.gift.IMGiftModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.UserInfo
import com.swago.room.R
import com.swago.room.databinding.ViewItemGiftBinding
import java.io.File

/**
 *@date 2022/1/22 16:57
 *description:
 */
class GiftDanDaoView : FrameLayout {

    var isBusy = false
    private var binding: ViewItemGiftBinding? = null
    private var svgParser: SVGAParser? = null

    private var giftCount = 0

    var imCurrentGiftModel: IMGiftModel? = null

    private val imageViewData by lazy {
        ArrayList<ImageView>()
    }

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

    constructor(context: Context, mAttributeSet: AttributeSet?) : super(context, mAttributeSet) {
        initView(context)
    }
    //1 499..998   2 999..9998  3 9999
    private var svgaPlayWhichType = 0

    private var vibrator: Vibrator? = null

    private fun initView(context: Context) {
        vibrator = context.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
        binding = ViewItemGiftBinding.inflate(LayoutInflater.from(context), this, true)
        svgParser = SVGAParser(context)
        for (i in 0..5){
            val imageView = ImageView(context)
            imageViewData.add(imageView)
        }
    }

    fun addData(imGiftModel: IMGiftModel) {
        isBusy = true
        binding?.apply {
            Glide.with(ivAvatar.context)
                .load(imGiftModel.senderAvatar)
                .placeholder(R.mipmap.default_avatar)
                .error(R.mipmap.default_avatar)
                .into(ivAvatar)
            Glide.with(ivAvatar.context)
                .load(imGiftModel.giftIcon)
                .placeholder(R.mipmap.default_avatar)
                .error(R.mipmap.default_avatar)
                .into(ivGiftIcon)

            tvSenderName.text = imGiftModel.senderName
            if (!tvSenderName.isSelected) {
                tvSenderName.isSelected = true
            }

            tvSenderTo.text = AppContext.getContext().resources.getString(R.string.send_to)
                .format(imGiftModel.receiverName)
            if (!tvSenderTo.isSelected) {
                tvSenderTo.isSelected = true
            }
            LogUtil.d("礼物个数", "x${imGiftModel.giftNum}")
            clItemGift.visibility = View.VISIBLE
            imCurrentGiftModel = imGiftModel
            ivBg.visibility = View.INVISIBLE
            svgaImageView.visibility = View.INVISIBLE
            tvNum.visibility = View.INVISIBLE
            llNum.visibility = View.INVISIBLE
            llNum.removeAllViews()

            if (imCurrentGiftModel != null && imGiftModel.isCombo == 1) {
                giftCount += imGiftModel.giftOneceNum
            } else {
                //执行进场动画
                giftCount = imGiftModel.giftOneceNum
                giftEnterAnimator.start()
            }

            //设置背景
            if (giftCount in 1..198){
                ivBg.visibility = View.VISIBLE
                tvNum.visibility = View.VISIBLE
                tvNum.text = "x${giftCount}"
                ivBg.setImageResource(R.mipmap.bg_dan_dao_one)
            }
            if (giftCount in 199..498){
                ivBg.visibility = View.VISIBLE
                tvNum.visibility = View.VISIBLE
                tvNum.text = "x${giftCount}"
                ivBg.setImageResource(R.mipmap.bg_dan_dao_two)
            }
            if (giftCount in 499..998){
                svgaImageView.visibility = View.VISIBLE
                llNum.visibility = View.VISIBLE
                loadGiftNum(giftCount)
                if (svgaPlayWhichType!=1){
                    svgaPlayWhichType = 1
                    playSvg("dandao_one.svga")
                }else{
                    if (!svgaImageView.isAnimating){
                        playSvg("dandao_one.svga")
                    }
                }
            }
            if (giftCount in 999..9998){
                svgaImageView.visibility = View.VISIBLE
                llNum.visibility = View.VISIBLE
                loadGiftNum(giftCount)
                if (svgaPlayWhichType!=2){
                    svgaPlayWhichType = 2
                    playSvg("dandao_two.svga")
                }else{
                    if (!svgaImageView.isAnimating){
                        playSvg("dandao_two.svga")
                    }
                }
            }
            if (giftCount >9998){
                svgaImageView.visibility = View.VISIBLE
                llNum.visibility = View.VISIBLE
                loadGiftLargeNum(giftCount)
                if (svgaPlayWhichType!=3){
                    svgaPlayWhichType = 3
                    playSvg("dandao_three.svga")
                }else{
                    if (!svgaImageView.isAnimating){
                        playSvg("dandao_three.svga")
                    }
                }
            }


            clItemGift.removeCallbacks(showRunnable)
            clItemGift.postDelayed(showRunnable, 3000)

            if (imGiftModel.multiple != 0) {
                when (imGiftModel.multiple) {
                    in 1..100 -> {
                        iv.setImageResource(R.mipmap.win_100_prize)
                    }

                    in 100..499 -> {
                        iv.setImageResource(R.mipmap.win_499_prize)
                    }

                    in 500..10000 -> {
                        UserInfo.getUserInfo()?.let {  userInfoModel ->
                            if (userInfoModel.id == imGiftModel.senderId){
                                vibrator?.vibrate(2500)
                            }
                        }
                        iv.setImageResource(R.mipmap.win_500_prize)

                    }
                }
                clWinPrize.visibility = View.VISIBLE
                tvWinPrize.text =
                    AppContext.getContext().resources.getString(R.string.win_num_prize)
                        .format(imGiftModel.multiple)
                clWinPrize.removeCallbacks(winPrizeRunnable)
                clWinPrize.postDelayed(winPrizeRunnable, 1500)
            }
        }
    }

    private fun loadGiftLargeNum(giftCount: Int) {
        binding?.apply {
            val giftContStr = giftCount.toString()
            if (giftContStr.length>imageViewData.size){
                imageViewData.clear()
                for (i in 0..giftContStr.length){
                    val imageView = ImageView(context)
                    imageViewData.add(imageView)
                }
            }
            imageViewData[0].setImageResource(R.mipmap.ic_dan_dao_x)
            llNum.addView(imageViewData[0])
            giftCount.toString().toCharArray().forEachIndexed {  index,char ->
                when(char){
                    '0' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_zero)
                    }
                    '1' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_one)
                    }
                    '2' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_two)
                    }
                    '3' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_three)
                    }
                    '4' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_four)
                    }
                    '5' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_five)
                    }
                    '6' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_six)
                    }
                    '7' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_seven)
                    }
                    '8' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_eight)
                    }
                    '9' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_big_nine)
                    }
                }
                llNum.addView(imageViewData[index+1])
            }
        }
    }

    private fun loadGiftNum(giftCount: Int) {
        binding?.apply {
            val giftContStr = giftCount.toString()
            if (giftContStr.length>imageViewData.size){
                imageViewData.clear()
                for (i in 0..giftContStr.length){
                    val imageView = ImageView(context)
                    imageViewData.add(imageView)
                }
            }
            imageViewData[0].setImageResource(R.mipmap.ic_dan_dao_x)
            llNum.addView(imageViewData[0])
            giftCount.toString().toCharArray().forEachIndexed {  index,char ->
                when(char){
                    '0' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_zero)
                    }
                    '1' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_one)
                    }
                    '2' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_two)
                    }
                    '3' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_three)
                    }
                    '4' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_four)
                    }
                    '5' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_five)
                    }
                    '6' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_six)
                    }
                    '7' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_seven)
                    }
                    '8' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_eight)
                    }
                    '9' -> {
                        imageViewData[index+1].setImageResource(R.mipmap.ic_dan_dao_nine)
                    }
                }
                llNum.addView(imageViewData[index+1])
            }
        }
    }


    private val giftEnterAnimator by lazy {
        val tx = ObjectAnimator.ofFloat(
            binding!!.clItemGift,
            "translationX",
            -binding!!.clItemGift.width.toFloat(),
            0f
        )
        val ap = ObjectAnimator.ofFloat(binding!!.clItemGift, "alpha", 0.5f, 1f)
        tx.interpolator = DecelerateInterpolator()
        tx.duration = 400
        tx.repeatCount = 0
        ap.duration = 200
        ap.repeatCount = 0
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(tx, ap)
        animatorSet
    }

    private val showRunnable by lazy {
        Runnable {
            clear()
            binding?.apply {
                clItemGift.translationX = -(clItemGift.width).toFloat()
            }
        }
    }

    private val winPrizeRunnable by lazy {
        Runnable {
            vibrator?.cancel()
            binding!!.clWinPrize.visibility = View.INVISIBLE
            binding!!.tvWinPrize.text = ""
        }
    }

    private fun playSvg(path:String){
        svgParser?.let {
            it.decodeFromAssets(path,object:SVGAParser.ParseCompletion{
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    binding?.apply {
                        val drawable = SVGADrawable(videoItem)
                        svgaImageView.setImageDrawable(drawable)
                        svgaImageView.loops = 99999
                        svgaImageView.startAnimation()
                    }
                }

                override fun onError() {
                    Toast.makeText(AppContext.getContext(), "播放异常", Toast.LENGTH_SHORT).show()
                }
            },object:SVGAParser.PlayCallback{
                override fun onPlay(file: List<File>) {
                }

            })

        }
    }


    fun clear() {
        vibrator?.cancel()
        isBusy = false
        imCurrentGiftModel = null
        svgaPlayWhichType = 0
        binding?.apply {
            if (svgaImageView.isAnimating){
                svgaImageView.stopAnimation()
            }
            clWinPrize.visibility = View.INVISIBLE
            clItemGift.visibility = View.INVISIBLE
            clWinPrize.removeCallbacks(winPrizeRunnable)
            clItemGift.removeCallbacks(showRunnable)
        }
    }

    fun cancelVibrator() {
        vibrator?.cancel()
    }

}