package com.ym.game.view


import android.animation.Animator
import android.animation.ValueAnimator
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.res.AssetFileDescriptor
import android.graphics.Path
import android.graphics.PathMeasure
import android.media.MediaPlayer
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.ScaleAnimation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.google.gson.annotations.Until
import com.ym.admodule.config.AdManager
import com.ym.admodule.listener.ZXADVideoListener
import com.ym.ddhy.R
import com.ym.game.contract.PuzzleContract
import com.ym.game.listener.IDialogViewCloseCallback
import com.ym.game.presenter.PuzzlePresenter
import com.ym.game.utils.CenterDialog
import com.ym.library.listener.OnRecycleItemClickListener
import com.ym.library.module.PuzzleEntity
import com.ym.library.rxbus.RxBusUtil
import com.ym.library.utils.Utils
import com.ym.modulecommon.AppliContext
import com.ym.game.adapter.PuzzleBottomAdapter
import com.ym.library.Constant
import com.ym.library.listener.IAdVideoListener
import com.ym.library.module.StatusEntity
import com.ym.library.net.BaseObserver
import com.ym.library.net.GameApiClient
import com.ym.library.net.RxSchedulers
import com.ym.library.utils.ADConfig
import com.ym.library.utils.AdUtils
import com.ym.library.utils.EventUtils
import com.ym.piggybank.adapter.PuzzleTopAdapter

object PuzzleDialog : PuzzleContract.View, OnRecycleItemClickListener<PuzzleEntity.PuzzleData> {
    private var context: Context? = null
    private var mDialog: Dialog? = null
    private var mPresenter: PuzzlePresenter? = null
    private var topAdapter: PuzzleTopAdapter? = null
    private var bottomAdapter: PuzzleBottomAdapter? = null
    private var ta: TranslateAnimation? = null
    var rl: RelativeLayout? = null
    var rlredbg: RelativeLayout? = null
    var rltop: RecyclerView? = null
    var rlbottom: RecyclerView? = null
    var mPathMeasure: PathMeasure? = null
    val mCurrentPosition = FloatArray(2)
    var lottieView: LottieAnimationView? = null

    var anim_mask_layout: ViewGroup? = null

    //展示拼图窗口
    fun showPuzzleDialog(context: Activity?,mListener: IDialogViewCloseCallback) {
        if (context == null) {
            return
        }
        this.context = context
         EventUtils.onEvent("show_pintu_dialog", "拼图弹窗曝光")
        mPresenter = PuzzlePresenter(this)
        mPresenter?.getPuzzleData()
        RxBusUtil.getDefault().register(this)
        mDialog = Dialog(context, R.style.UpdateVersionCompatDialogTheme75)
        val mDialogView =
            CenterDialog.showBottomDialog(
                R.layout.dialog_layout_puzzle,
                context,
                mDialog!!,
                0,
                Gravity.CENTER
            )

        rl = mDialog?.findViewById<RelativeLayout>(R.id.id_rl_parent)
        rlredbg = mDialog?.findViewById<RelativeLayout>(R.id.id_rl_red_bg)
        lottieView = mDialogView.findViewById<LottieAnimationView>(R.id.lottie_view)
        rltop = mDialog?.findViewById<RecyclerView>(R.id.id_rl_top)
        rlbottom = mDialog?.findViewById<RecyclerView>(R.id.id_rl_bottom)
        rltop?.layoutManager = GridLayoutManager(context, 3)
        rlbottom?.layoutManager = GridLayoutManager(context, 5)

        topAdapter = PuzzleTopAdapter()
        bottomAdapter = PuzzleBottomAdapter(this)
        rltop?.adapter = topAdapter
        rlbottom?.adapter = bottomAdapter

        mDialogView?.findViewById<ImageView>(R.id.iv_dialog_close).setOnClickListener {
            mDialog?.dismiss()
            mListener.onCloseViewSuccess(true);
            //  RxBusUtil.getDefault().unregister(this)
        }
        mDialogView?.findViewById<ImageView>(R.id.id_img_one_click_puzzle).setOnClickListener {

            // mListener.onCloseViewSuccess(true);
            EventUtils.onEvent("click_pintu_yijian", "一键拼图按钮点击")
            mPresenter?.automatic()
            RxBusUtil.getDefault().unregister(this)
        }
        mDialogView?.findViewById<ImageView>(R.id.id_img_desc).setOnClickListener {
            MainDialog.showActivityDesc(context as Activity)
        }
        mDialog?.setOnCancelListener {
            RxBusUtil.getDefault().unregister(this)
        }

        mDialog?.setCanceledOnTouchOutside(false)
        mDialog?.setCancelable(false)
        if (context.isFinishing){
            return
        }
        mDialog?.show()
    }


//    override fun PuzzDataResult(mdata: PuzzleEntity) {
//        topAdapter?.clear()
//        topAdapter?.appendToList(mdata?.lockCardList)
//        topAdapter?.notifyDataSetChanged()
//        bottomAdapter?.clear()
//        bottomAdapter?.appendToList(mdata?.storeCardList)
//        bottomAdapter?.notifyDataSetChanged()
//        mPresenter?.openBox()
//    }

    override fun PutPuzzDataResult(mdata: PuzzleEntity) {
        topAdapter?.clear()
        topAdapter?.appendToList(mdata?.lockCardList)
        topAdapter?.notifyDataSetChanged()
        bottomAdapter?.clear()
        bottomAdapter?.appendToList(mdata?.storeCardList)
        bottomAdapter?.notifyDataSetChanged()
        if (mdata.isWin == 1) {
            mPresenter?.openBox()
            rlredbg?.setBackgroundResource(R.color.black)
            //先执行动画，再弹这个窗
            lottieView?.visibility = View.VISIBLE
            lottieView?.imageAssetsFolder = "puzzle/images/"
            lottieView?.setAnimation("puzzle/data.json")
            lottieView?.setRepeatCount(1)
            lottieView?.playAnimation()
            playSound("collect.mp3")
            lottieView?.addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener { valueAnimator -> // 判断动画加载结束
                if (valueAnimator.animatedFraction == 1f) {
                    lottieView?.visibility = View.GONE
                    rlredbg?.setBackgroundResource(R.color.transparent)
                    lottieView?.removeAllUpdateListeners()
                    MainDialog.showgetWaterDrop(context as Activity
                        , 4, "puzzle", mdata.winCoin, null)

                }

            })


        }
    }

    //卡片向上飞
    override fun cardsFlyUp(result: PuzzleEntity, index: Int) {
        val iv = ImageView(context)
        //获取图片资源
        when (index) {
            1 -> {
                iv.setImageResource(R.drawable.icon_bottom_one_gray)
            }
            2 -> {
                iv.setImageResource(R.drawable.icon_bottom_two_gray)
            }
            3 -> {
                iv.setImageResource(R.drawable.icon_bottom_three_gray)
            }
            4 -> {
                iv.setImageResource(R.drawable.icon_bottom_four_gray)
            }
            5 -> {
                iv.setImageResource(R.drawable.icon_bottom_five_gray)
            }
            6 -> {
                iv.setImageResource(R.drawable.icon_bottom_six_gray)
            }
            7 -> {
                iv.setImageResource(R.drawable.icon_bottom_seven_gray)
            }
            8 -> {
                iv.setImageResource(R.drawable.icon_bottom_eight_gray)
            }
            9 -> {
                iv.setImageResource(R.drawable.icon_bottom_nine_gray)
            }
        }


        val params =
            RelativeLayout.LayoutParams(100, 100)
        rl!!.addView(iv, params)
        val parentLocation = IntArray(2)
        rl!!.getLocationOnScreen(parentLocation)
        val startLocation = IntArray(2)
        rlbottom?.findViewHolderForAdapterPosition(index - 1)?.itemView?.getLocationOnScreen(
            startLocation
        )
        //得到最后落的位置的坐标(用于计算动画结束后的坐标)
        val endLoc = IntArray(2)
        rltop?.findViewHolderForAdapterPosition(index - 1)?.itemView?.getLocationOnScreen(endLoc)
        Log.e("终点坐标", "" + endLoc[0] + "x" + endLoc[1] + "y")
        Log.e("终点坐标", "" + startLocation[0] + "x" + startLocation[1] + "y")
        Log.e("终点坐标", "" + parentLocation[0] + "x" + parentLocation[1] + "y")
//        正式开始计算动画开始/结束的坐标
        //起始点：起始点-父布局起始点+该图片的宽
        // var x=rlbottom?.findViewHolderForAdapterPosition(index-1)?.itemView?.x
        val startX = startLocation[0] - parentLocation[0] + iv!!.width.toFloat()
        val startY = startLocation[1] - parentLocation[1] + iv!!.height.toFloat()
        //params.setMargins(100,100,100,100)
        //终点坐标：起始点-父布局起始点
        val toX = (endLoc[0] - parentLocation[0]).toFloat()
        val toY = (endLoc[1] - parentLocation[1]).toFloat()
        Log.e("坐标", "" + startX + "x" + startY + "y")
        Log.e("坐标", "" + toX + "x" + toY + "y")
        //        计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        val path = Path()
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY)
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        // path.quadTo((startX + toX) / 2, startY, toX, toY)
        path.quadTo(startX, startY, toX, toY)
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = PathMeasure(path, false)

        //属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        val valueAnimator =
            ValueAnimator.ofFloat(0f, mPathMeasure!!.length)
        valueAnimator.duration = 300
        // 匀速线性插值器
        valueAnimator.interpolator = LinearInterpolator()
        valueAnimator.addUpdateListener { animation -> // 当插值计算进行时，获取中间的每个值，
            // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
            val value = animation.animatedValue as Float
            // 获取当前点坐标封装到mCurrentPosition
            // boolean getPosTan(float distance, float[] pos, float[] tan) ：
            // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
            // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
            mPathMeasure!!.getPosTan(
                value,
                mCurrentPosition,
                null
            ) //mCurrentPosition此时就是中间距离点的坐标值
            // 移动的图片（动画图片）的坐标设置为该中间点的坐标
            iv.translationX = mCurrentPosition[0]
            iv.translationY = mCurrentPosition[1]
        }

        //       开始执行动画
        //  iv.startAnimation(scaleAnimation)
        valueAnimator.start()
        //      动画结束后的处理
        valueAnimator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}

            //当动画结束后：
            override fun onAnimationEnd(animation: Animator) {
                rl!!.removeView(iv)
                PutPuzzDataResult(result)
            }

            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })
    }

    override fun getPuzzlelookAd(diffCardsNum: Int) {
        if (diffCardsNum != 0) {
            MainDialog.showDialoggetPuzzle(
                context as Activity,
                diffCardsNum,
                View.OnClickListener {
                    AdUtils.playRewardAd(
                        context as Activity,
                        "get_puzzle_dialog",
                        object : IAdVideoListener {
                            override fun onAdClose() {
                                mPresenter?.onecleanPuzzle()
                            }
                            override fun onError(errorMsg: String?) {
                               // mPresenter?.onecleanPuzzle()
                                Log.e("MXL","ERROR")
                                Utils.showToast(context,"加载失败请重试")
                            }
                        })
                })
        }

    }

    private val scaleAnimation by lazy {
        ScaleAnimation(
            1f,
            2f,
            1f,
            2f,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        ).apply {
            duration = 300
            fillAfter = true
        }
    }

    override fun onItemClick(view: View, position: Int, data: PuzzleEntity.PuzzleData) {
        // Utils.showToast(AppliContext.get(), "点击" + position)
        if (data.number == 0) {
           // Utils.showToast(AppliContext.get(), "看广告")
            EventUtils.onEvent("click_pintu_suipian_video","碎片视频按钮点击")
            AdUtils.playRewardAd(
                context as Activity,
                "get_puzzle_click_dialog",
                object : IAdVideoListener {
                    override fun onAdClose() {
                        mPresenter?.noputPuzzleData(data.index)

                    }

                    override fun onError(errorMsg: String?) {
                       // mPresenter?.noputPuzzleData(data.index)
                    }
                })

        } else {
            mPresenter?.putPuzzleData(data.index)
        }

    }
    /**
     * 播放音效
     */
    private fun playSound(fileName: String) {
        val fd: AssetFileDescriptor? = context?.assets?.openFd(fileName)
        val mMediaPlayer = MediaPlayer()
        mMediaPlayer?.setDataSource(fd?.fileDescriptor, fd?.startOffset!!, fd.length)
        mMediaPlayer?.prepareAsync()
        mMediaPlayer?.setOnPreparedListener {
            mMediaPlayer?.start()
        }
        mMediaPlayer?.setOnCompletionListener {
            try {
                mMediaPlayer?.stop()
                mMediaPlayer?.release()
            } catch (e: java.lang.Exception) {}
        }
    }


}