package com.ydl.media.view

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.PixelFormat
import android.graphics.Point
import android.os.Bundle
import androidx.core.view.ViewCompat
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ydl.media.audio.AudioPlayer
import com.yidianling.common.tools.RxImageTool

/**
 * 音频播放悬浮窗 帮助类
 *
 * 需要在Activity onDestroy中调用removeView()方法移除
 * 避免内存泄露
 */
class PlayerFloatHelper {

    companion object {
        @SuppressLint("StaticFieldLeak")
        private var mPlayerFloatView: PlayerFloatView? = null
        //已添加悬浮窗页面全路径名
        private var showingPageName: String? = null
        private var wm: WindowManager? = null
        var isCanClick = true

        var playingType = PlayTypeEnum.PLAY_TYPE_NONE
        var playTempData = hashMapOf<String,String>()
        /**
         * FM:
         * fmId
         * fmTitle
         * fmAuthor
         * fmImageUrl
         */

        /**
         * 如果有音频正在播放则显示
         */
        fun showIfPlaying(context: Context) {
            if (AudioPlayer.get().isPlaying) {
                show(context)
                mPlayerFloatView?.updatePlayState()
            } else {
                hide()
            }
        }

        /**
         * 显示悬浮控件
         */
        fun show(context: Context, playTypeEnum: PlayTypeEnum = PlayTypeEnum.PLAY_TYPE_NONE, playData:HashMap<String,String> = hashMapOf<String,String>()) {

            playingType = playTypeEnum
            if (playData.size>0){
                this.playTempData.putAll(playData)
            }

            if (mPlayerFloatView == null) {
                mPlayerFloatView = PlayerFloatView(context)
                mPlayerFloatView?.addFloatClickListener(object :PlayerFloatView.FloatViewPlayListener{
                    override fun onPauseClick() {

                    }

                    override fun onStartClick() {

                    }

                    override fun onPlayFinish() {

                    }

                })
            }

            if (showingPageName != context::class.qualifiedName) {
                mPlayerFloatView?.resetWm(context)
                addFloatToWm(context)
            }

            mPlayerFloatView?.resetView()

            mPlayerFloatView?.visibility = View.VISIBLE
            mPlayerFloatView?.setPlayingState()
        }

        fun hide() {
            mPlayerFloatView?.visibility = View.GONE
        }

        fun addClickListener(listener: PlayerFloatView.FloatViewPlayListener) {
            mPlayerFloatView?.addFloatClickListener(listener)
        }

        fun removeClickListener(listener: PlayerFloatView.FloatViewPlayListener) {
            mPlayerFloatView?.removeFloatClickListener(listener)
        }

        fun isShow(context: Context): Boolean {
            return !TextUtils.isEmpty(showingPageName) && showingPageName == context::class.qualifiedName && mPlayerFloatView?.visibility == View.VISIBLE
        }

        fun removeView(context: Context) {
            if (TextUtils.isEmpty(showingPageName) || showingPageName != context::class.qualifiedName) {
                return
            }
            mPlayerFloatView?.visibility = View.GONE
            wm?.removeViewImmediate(mPlayerFloatView)
            showingPageName = ""
            wm = null
        }

        fun onDestroy() {
            if (mPlayerFloatView != null) {
                if (!TextUtils.isEmpty(showingPageName)) {
                    wm?.removeViewImmediate(mPlayerFloatView)
                    showingPageName = ""
                }

                mPlayerFloatView?.onDestroy()
                mPlayerFloatView?.removeAllViews()

            }
        }

        fun setPlayingState(context: Context) {
            show(context)
            mPlayerFloatView?.setPlayingState()
        }

        fun updatePlayState() {
            mPlayerFloatView?.updatePlayState()
        }

        private fun addFloatToWm(context: Context) {
            if (wm != null && !TextUtils.isEmpty(showingPageName)) {
                if (ViewCompat.isAttachedToWindow(mPlayerFloatView!!)){
//                    if (context is Activity && !(context.isFinishing)){
//                      wm?.removeViewImmediate(mPlayerFloatView)
//                    }
                    wm?.removeViewImmediate(mPlayerFloatView)
                }
                wm = null
            }
            //获取WindowManager
            wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            //设置LayoutParams(全局变量）相关参数
            val wmParams = mPlayerFloatView?.wmParams
            wmParams?.type = WindowManager.LayoutParams.TYPE_APPLICATION   //设置window type
            wmParams?.format = PixelFormat.RGBA_8888   //设置图片格式，效果为背景透明
            //设置Window flag
            wmParams?.flags =
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            wmParams?.gravity = Gravity.LEFT or Gravity.TOP   //调整悬浮窗口至左上角
            //以屏幕左上角为原点，设置x、y初始值
            val size = Point()
            wm?.defaultDisplay?.getSize(size)
            wmParams?.x = 0
            wmParams?.y = size.y * 5 / 6
            //设置悬浮窗口长宽数据
            wmParams?.width = WindowManager.LayoutParams.MATCH_PARENT
            wmParams?.height = RxImageTool.dp2px(56f)
            //显示myFloatView图像
            wm?.addView(mPlayerFloatView, wmParams)
            showingPageName = context::class.qualifiedName!!
        }

        /**
         * 打开播放中的页面详情
         */
        fun startPlayingActivity(context: Context?, fullScreen: Int = 0) {
            if (playingType == PlayTypeEnum.PLAY_TYPE_FM) {
                //FM播放页
                startFMPlayActivity(context)
            } else if (playingType == PlayTypeEnum.PLAY_TYPE_COURSE) {
                var url = AudioPlayer.get().playMusic?.path
                //课程播放页
                startCoursePlayActivity(context, 1, fullScreen, url, true)
            }
        }

        fun startCoursePlayActivity(context: Context?, from: Int, fullScreen: Int = 0, coursePlayUrl: String? = "", isFromFloatView: Boolean = false) {
            ARouter.getInstance()
                .build("/course/play")
                .withInt("course_id", playTempData["course_id"]?.toInt()?:0)
                .withInt("course_type", 0)
                .withString("coursePlayUrl", coursePlayUrl)
                .withInt("from", from)
                .withBoolean("isFromFloatView", isFromFloatView)
                .withInt("fullScreen", fullScreen)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation()
        }

        fun startFMPlayActivity(context: Context?) {
            val bundle = Bundle()
            bundle.putInt("id", playTempData["fmId"]?.toInt()?:0)
            ARouter.getInstance().build("/fm/detail")
                .withBundle("bundle", bundle)
                .navigation()
        }

        /**
         * 获取FM播放Id
         */
        fun getFmId(): Int {
            return playTempData["fmId"]?.toInt()?:0
        }




    }

}
