package com.swago.room.pk

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGADrawable
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.swago.baseswago.baseroom.IRoomActiveListener
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoomTimer
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.model.live.pk.ProcessPKModel
import com.swago.baseswago.model.live.pk.PunishPKModel
import com.swago.baseswago.model.live.pk.StartPKModel
import com.swago.baseswago.model.live.pk.StopPKModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.DpPxUtil
import com.swago.baseswago.util.TimeUtil
import com.swago.loadUrl
import com.swago.room.R
import com.swago.room.databinding.LayoutPkViewBinding
import java.io.File

class PKLayoutView : ConstraintLayout, IRoomActiveListener, IPKListener,
    RoomTimer.TimeTickListener {

    private var binding:LayoutPkViewBinding? = null
    private var svgParser:SVGAParser? = null
    private var svgParserProgress:SVGAParser? = null
    private var mProgress = 50
    private val selfAdapter by lazy {
        PKAudienceAdapter()
    }
    private val peerAdapter by lazy {
        PKAudienceAdapter()
    }

    var pkTime = 0

    var pkResult = 3

    private var pkEndTime = 0

    //主播获取PK信息
    var doGetPKInfoFun:(()->Unit)? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView(context)
    }

    private fun initView(context: Context) {
        binding = LayoutPkViewBinding.inflate(LayoutInflater.from(context), this, true)
        SwagoRoomManager.addListener(this)
        PKStateManager.addPKListener(this)
        RoomTimer.timeTickList.add(this)
        svgParser = SVGAParser(context)
        svgParserProgress = SVGAParser(context)
        playProgress("laugh.svga")
        binding?.let {
            it.rvSelf.layoutManager = LinearLayoutManager(context)
            it.rvSelf.adapter = selfAdapter
            it.rvPeer.layoutManager = LinearLayoutManager(context)
            it.rvPeer.adapter = peerAdapter

            selfAdapter.setOnItemClickListener { _, _, position ->

            }
            peerAdapter.setOnItemClickListener { _, _, position ->

            }
        }
    }

    private fun initProgressPosition(){
        binding?.apply {
            val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
            svgProcessLayoutParams.startToStart = R.id.view
            svgProcessLayoutParams.topToBottom = R.id.view
            svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
            svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/2
            svgProgress.layoutParams = svgProcessLayoutParams
        }

    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        visibility = View.GONE
        resetSvg()
        resetData()
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun closeRoomed() {
        resetSvg()
        RoomTimer.timeTickList.remove(this)
        SwagoRoomManager.removeListener(this)
        PKStateManager.removePKListener(this)
    }

    private var startPKModel:StartPKModel? = null

    override fun startPK(startPKModel: StartPKModel,isGetDataFromIM:Boolean) {
        binding?.apply {
            this@PKLayoutView.startPKModel = startPKModel
            pkEndTime = startPKModel.pkEndTime-startPKModel.pkResultTime
            if (isGetDataFromIM){
                initProgressPosition()
            }
            tvSelf.text = "0"
            tvPeer.text = "0"
            visibility = View.VISIBLE
            pkTime = startPKModel.pkResultTime
            tvPkTime.text = TimeUtil.convertMinSecond(pkTime.toLong())
            playProgress("progress.svga")
            clPKTime.visibility = View.VISIBLE
            clPunishTime.visibility = View.GONE
            tvPeerName.text = startPKModel.oppositeName
            tvPeerId.text = AppContext.getContext().resources.getString(R.string.id_x).format(startPKModel.oppositeUserId)
            try {
                ivPeerAvatar.loadUrl(context,startPKModel.oppositeAvatar)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    override fun stopPK(stopPKModel: StopPKModel) {
        resetData()
        visibility = View.GONE
    }

    override fun punishPK(punishPKModel: PunishPKModel,isGetDataFromIM:Boolean) {
        binding?.apply {
            if (!isGetDataFromIM){
                ivPeerAvatar.loadUrl(context,punishPKModel.oppositeAvatar)
                tvPeerName.text = punishPKModel.oppositeName
                tvPeerId.text = AppContext.getContext().resources.getString(R.string.id_x).format(punishPKModel.oppositeUserId)
                pkEndTime = punishPKModel.pkEndTime
            }else{
                startPKModel?.let {
                    pkTime = it.pkEndTime - it.pkResultTime
                }
            }
            visibility = View.VISIBLE
            clPKTime.visibility = View.GONE
            clPunishTime.visibility = View.VISIBLE
            if (svgProgress.isAnimating){
                svgProgress.stopAnimation()
            }
            // 3赢 4输  5平局
            pkResult =punishPKModel.roomResult
            when(punishPKModel.roomResult){
                3 -> {
                    playPKResultSvg("pk_win.svga")
                    playProgress("laugh.svga")
                }
                4 -> {
                    playPKResultSvg("pk_fail.svga")
                    playProgress("cry.svga")
                }
                5 -> {
                    playPKResultSvg("pk_balance.svga")
                }
            }

        }
    }

    override fun processChangePK(processPKModel: ProcessPKModel,isGetDataFromIM: Boolean) {
        binding?.apply {
            if (processPKModel.roomAudienceList.isNotEmpty()){
                selfAdapter.setNewData(processPKModel.roomAudienceList)
            }
            if (processPKModel.oppositeRoomAudienceList.isNotEmpty()){
                peerAdapter.setNewData(processPKModel.oppositeRoomAudienceList)
            }
            if (!isGetDataFromIM){
                tvSelf.text = processPKModel.progressValue.toString()
                tvPeer.text = processPKModel.oppositeProgressValue.toString()
            }else{
                if (tvSelf.text.toString().toInt() < processPKModel.progressValue || tvPeer.text.toString().toInt() < processPKModel.oppositeProgressValue) {
                    tvSelf.text = processPKModel.progressValue.toString()
                    tvPeer.text = processPKModel.oppositeProgressValue.toString()
                } else {
                    return
                }
            }
            val selfProgressValue = if (processPKModel.progressValue == 0) {
                 0.01
            } else {
                processPKModel.progressValue
            }

            val peerProgressValue = if (processPKModel.oppositeProgressValue == 0) {
                0.01
            } else {
                processPKModel.oppositeProgressValue
            }

            val progress =  (selfProgressValue.toDouble() / (peerProgressValue.toDouble() + selfProgressValue.toDouble()) * 80).toInt()
            mProgress = when (progress) {
                0 -> {
                    10
                }
                else -> {
                    10 + progress
                }
            }
            progressBar.progress = mProgress


            if (isGetDataFromIM){
                if (processPKModel.progressValue == 0&&processPKModel.oppositeProgressValue != 0){
                    val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                    svgProcessLayoutParams.startToStart = R.id.view
                    svgProcessLayoutParams.topToBottom = R.id.view
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/10 - DpPxUtil.dip2px(10f)
                    svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                    svgProgress.layoutParams = svgProcessLayoutParams
                    return
                }

                if (processPKModel.oppositeProgressValue == 0&&processPKModel.progressValue != 0){
                    val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                    svgProcessLayoutParams.startToStart = R.id.view
                    svgProcessLayoutParams.topToBottom = R.id.view
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/10*9 - DpPxUtil.dip2px(10f)
                    svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                    svgProgress.layoutParams = svgProcessLayoutParams
                    return
                }

                val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                svgProcessLayoutParams.startToStart = R.id.view
                svgProcessLayoutParams.topToBottom = R.id.view
                if (mProgress>50){
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress + DpPxUtil.dip2px(10f)
                }else if(mProgress<50){
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress - DpPxUtil.dip2px(10f)
                }else{
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress
                }

                svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                svgProgress.layoutParams = svgProcessLayoutParams
            }else{
                if (processPKModel.progressValue == 0&&processPKModel.oppositeProgressValue != 0){
                    val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                    svgProcessLayoutParams.startToStart = R.id.view
                    svgProcessLayoutParams.topToBottom = R.id.view
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/10 - DpPxUtil.dip2px(10f)
                    svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                    svgProgress.layoutParams = svgProcessLayoutParams
                    return
                }

                if (processPKModel.oppositeProgressValue == 0&&processPKModel.progressValue != 0){
                    val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                    svgProcessLayoutParams.startToStart = R.id.view
                    svgProcessLayoutParams.topToBottom = R.id.view
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/10*9 - DpPxUtil.dip2px(10f)
                    svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                    svgProgress.layoutParams = svgProcessLayoutParams
                    return
                }

                val svgProcessLayoutParams = ConstraintLayout.LayoutParams(DpPxUtil.dip2px(20f),DpPxUtil.dip2px(20f))
                svgProcessLayoutParams.startToStart = R.id.view
                svgProcessLayoutParams.topToBottom = R.id.view
                if (mProgress>50){
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress + DpPxUtil.dip2px(10f)
                }else if(mProgress<50){
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress - DpPxUtil.dip2px(10f)
                }else{
                    svgProcessLayoutParams.marginStart = DpPxUtil.getScreenWidth()/100*mProgress
                }
                svgProcessLayoutParams.topMargin = DpPxUtil.dip2px(-3f)
                svgProgress.layoutParams = svgProcessLayoutParams
            }

        }
    }

    override fun onTimeCount(time: Int) {
        binding?.apply {
            pkTime--
            if (PKStateManager.roomState==PKStateManager.PK){
                if (pkTime>=0){
                    tvPkTime.text = TimeUtil.convertMinSecond(pkTime.toLong())
                }
                if (pkTime==-5 ){
                    doGetPKInfoFun?.invoke()
                }
            }else if(PKStateManager.roomState==PKStateManager.PUNISH){
                if (pkTime>=0){
                    tvPunishTime.text = TimeUtil.convertMinSecond(pkTime.toLong())
                }
                if (pkTime==-5 ){
                    doGetPKInfoFun?.invoke()
                }
            }
        }
    }


    private fun resetData(){
        binding?.apply {
            mProgress = 50
            progressBar.progress = 50
            tvSelf.text = "0"
            tvPeer.text = "0"
            ivSelfPKResult.visibility = View.GONE
            ivPeerPKResult.visibility = View.GONE
            tvPeerName.text = ""
            tvPeerId.text = ""
            tvPunishTime.text = "00:00"
            tvPkTime.text = "00:00"
            selfAdapter.data.clear()
            selfAdapter.notifyDataSetChanged()
            peerAdapter.data.clear()
            peerAdapter.notifyDataSetChanged()
        }
    }

    private fun resetSvg(){
        binding?.apply {
            if (svgProgress.isAnimating){
                svgProgress.stopAnimation()
            }
            if (svgPKResult.isAnimating){
                svgPKResult.stopAnimation()
            }
        }
    }


    /**
     * type 1 播放PK结果动画  2 播放正在PK进度条动画
     */
    private fun playProgress(path:String){
        svgParserProgress?.let {
            it.decodeFromAssets(path,object:SVGAParser.ParseCompletion{
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    binding?.apply {
                        val drawable = SVGADrawable(videoItem)
                        svgProgress.setImageDrawable(drawable)
                        svgProgress.loops = 99999
                        svgProgress.startAnimation()
                    }
                }

                override fun onError() {
                    binding?.apply {
                    }
                }
            },object:SVGAParser.PlayCallback{
                override fun onPlay(file: List<File>) {
                }

            })

        }
    }


    private fun playPKResultSvg(path:String){
        svgParser?.let {
            it.decodeFromAssets(path,object:SVGAParser.ParseCompletion{
                override fun onComplete(videoItem: SVGAVideoEntity) {
                    binding?.apply {
                        val drawable = SVGADrawable(videoItem)
                        svgPKResult.setImageDrawable(drawable)
                        svgPKResult.callback = playResultCallback
                        svgPKResult.visibility = View.VISIBLE
                        svgPKResult.loops = 1
                        svgPKResult.startAnimation()
                    }
                }

                override fun onError() {
                    binding?.apply {
                        svgPKResult.visibility = View.GONE
                    }
                }
            },object:SVGAParser.PlayCallback{
                override fun onPlay(file: List<File>) {
                }

            })

        }
    }


    private var playResultCallback = object: SVGACallback {

        override fun onFinished() {
            binding?.apply {
               if (PKStateManager.roomState == PKStateManager.PUNISH){
                   ivSelfPKResult.visibility = View.VISIBLE
                   ivPeerPKResult.visibility = View.VISIBLE
               }
                svgPKResult.visibility = View.GONE
                when(pkResult){
                    3 -> {
                        ivSelfPKResult.setImageResource(R.mipmap.icon_pk_win)
                        ivPeerPKResult.setImageResource(R.mipmap.icon_pk_fail)
                    }
                    4 -> {
                        ivSelfPKResult.setImageResource(R.mipmap.icon_pk_fail)
                        ivPeerPKResult.setImageResource(R.mipmap.icon_pk_win)
                    }
                    5 -> {
                        ivSelfPKResult.setImageResource(R.mipmap.icon_pk_draw)
                        ivPeerPKResult.setImageResource(R.mipmap.icon_pk_draw)
                    }
                }
            }
        }

        override fun onPause() {}

        override fun onRepeat() {}

        override fun onStep(frame: Int, percentage: Double) {}
    }

}