package com.yidianling.ydlcommon.custom.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowManager
import android.widget.*
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayerView
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_image.transform.GlideRoundTransform
import com.yidianling.ydlcommon.R
import com.yidianling.ydlcommon.custom.player.YDLMusicHelper
import com.yidianling.ydlcommon.custom.player.YDLMusicPlayer
import com.yidianling.ydlcommon.custom.player.util.UtilH
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.util.*
import java.util.concurrent.CopyOnWriteArraySet


class PlayerFloatView(var mContext: Context) : FrameLayout(mContext) {
    //播放类型  1：视频  0：音频
    private var playType = 0
    private var mTouchStartX: Float = 0.toFloat()
    private var mTouchStartY: Float = 0.toFloat()
    private var mCurrX: Float = 0.toFloat()
    private var mCurrY: Float = 0.toFloat()

    private var playState: ImageView? = null
    private var mAudioLayout: LinearLayout? = null
    private var mVideoLayout: RelativeLayout? = null
    private var mInfoLayout: RelativeLayout? = null
    private var playClose: ImageView? = null
    private var playVideoClose: ImageView? = null
    private var playHead: ImageView? = null
    private var titleView: TextView? = null
    private var nameView: TextView? = null
    private var currentPlayingTimeView: TextView? = null
    private var durationView: TextView? = null
    private var mTouchSlop: Int = 0

    private var videoFullScreen: ImageView? = null
    private var videoBoxLayout: RelativeLayout? = null

    private var time: Int = 0
    private var allTime: Int = 0
    private var isMove: Boolean = false
    //视频播放器view
    private var videoView: PlayerView? = null

    private var wm: WindowManager? = null
    //此wmParams为获取的全局变量，用以保存悬浮窗口的属性
    var wmParams = WindowManager.LayoutParams()

    private var myHandler: Handler? = null

    private val UPDATE_VIEW_STATE = 1
    private val UPDATE_VIEW_COMPLETE = 2
    private val UPDATE_PLAY_TIME = 3//更新播放时间

    private var listeners: CopyOnWriteArraySet<FloatViewPlayListener> = CopyOnWriteArraySet()
    private var mStateChangeListener: YDLMusicPlayer.PlayStateChangeListener? = null
    private var timer: Timer? = null
    private var isCurrentVideoPlaying = true

    init {
        init(context)
    }

    fun resetWm(context: Context) {
        wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        wmParams = WindowManager.LayoutParams()
    }

    fun resetView() {
        playType = YDLMusicHelper.playType
        resetAudioAndVideoView()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun init(context: Context) {
        wm = getContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mTouchSlop = ViewConfiguration.get(getContext()).scaledTouchSlop + 8
        val view = View.inflate(context, R.layout.item_playing_float_btn, this)
        mAudioLayout = view.findViewById(R.id.ll_audio_layout)
        mVideoLayout = view.findViewById(R.id.rl_video_layout)
        mInfoLayout = view.findViewById(R.id.rl_info)
        videoBoxLayout = view.findViewById(R.id.app_video_box)
        playType = YDLMusicHelper.playType
        playHead = view.findViewById(R.id.play_head)
        playState = view.findViewById(R.id.play_state)
        playClose = view.findViewById(R.id.play_close)
        playVideoClose = view.findViewById(R.id.iv_video_close)
        videoFullScreen = view.findViewById(R.id.iv_video_full_screen)
        titleView = view.findViewById(R.id.tv_title)
        nameView = view.findViewById(R.id.tv_name)
        currentPlayingTimeView = view.findViewById(R.id.tv_now_playing_time)
        durationView = view.findViewById(R.id.tv_duration)

        resetAudioAndVideoView()

        if (!TextUtils.isEmpty(YDLMusicHelper.cover)) {
            GlideApp.with(context.applicationContext)
                    .load(YDLMusicHelper.cover)
                    .transform(GlideRoundTransform(context, 4))
                    .error(R.drawable.ico_play_float_pic)
                    .into(playHead!!)
        }

        myHandler = MyHandler()

        playHead!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            YDLMusicHelper.startPlayingActivity(context)
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        titleView!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            YDLMusicHelper.startPlayingActivity(context)
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        nameView!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            YDLMusicHelper.startPlayingActivity(context)
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        playClose!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            this@PlayerFloatView.visibility = View.GONE
                            YDLMusicHelper.clearTempData()
                            YDLMusicHelper.stop()
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        playVideoClose!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            this@PlayerFloatView.visibility = View.GONE
                            this.videoView?.stopPlay()
                            YDLMusicHelper.clearTempData()
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        videoFullScreen!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            YDLMusicHelper.startPlayingActivity(context, 1)
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        playState!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            if (YDLMusicHelper.isPlaying()) {
                                playState!!.setImageResource(R.drawable.ico_yyfc_play)
                                YDLMusicHelper.pause()
                                for (listener in listeners) {
                                    //数据重新设置回调
                                    listener.onPauseClick()
                                }
                            } else {
                                playState!!.setImageResource(R.drawable.ico_yyfc_pause)
                                YDLMusicHelper.start()
                                for (listener in listeners) {
                                    //数据重新设置回调
                                    listener.onStartClick()
                                }
                            }
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }

        if (mStateChangeListener == null) {
            mStateChangeListener = object : YDLMusicPlayer.PlayStateChangeListener {
                override fun reset() {

                }

                override fun update(time: Int, allTime: Int) {
                    this@PlayerFloatView.time = time
                    this@PlayerFloatView.allTime = allTime
                    myHandler?.sendEmptyMessage(UPDATE_PLAY_TIME)
                }

                fun pause() {

                }

                override fun completion() {
                    myHandler?.sendEmptyMessage(UPDATE_VIEW_COMPLETE)
                }

                override fun prepared() {
                    myHandler?.sendEmptyMessage(UPDATE_VIEW_STATE)
                }

                fun error() {
                }
            }
            YDLMusicPlayer.getInstance().addListener(mStateChangeListener!!)
        }
    }


    private fun resetAudioAndVideoView() {
        if (!TextUtils.isEmpty(YDLMusicHelper.cover)) {
            GlideApp.with(context.applicationContext)
                    .load(YDLMusicHelper.cover)
                    .transform(GlideRoundTransform(context, 4))
                    .error(R.drawable.ico_play_float_pic)
                    .into(playHead!!)
        }

        if (TextUtils.isEmpty(YDLMusicHelper.title)) {
            if (YDLMusicHelper.playingType == YDLMusicHelper.PLAY_TYPE_FM) {
                titleView!!.text = "心灵电台"
            }
            if (YDLMusicHelper.playingType == YDLMusicHelper.PLAY_TYPE_CONFIDE) {
                titleView!!.text = "壹点倾诉，心灵寄语"
            }
        } else {
            titleView!!.text = YDLMusicHelper.title
        }
        if (TextUtils.isEmpty(YDLMusicHelper.name)) {
            nameView!!.text = "壹点灵"
        } else {
            nameView!!.text = YDLMusicHelper.name
        }

        if (playType == 0) {
            mAudioLayout!!.visibility = View.VISIBLE
            mVideoLayout!!.visibility = View.GONE
        } else {
            mAudioLayout!!.visibility = View.GONE
            mVideoLayout!!.visibility = View.VISIBLE
            try {
                initVideoPlayer()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initVideoPlayer() {
        var url = YDLMusicHelper.courseVideoUlr?.replace("https", "http")

        var hisTime = UtilH.getProgress(mContext, url)

        videoView = PlayerView(mContext as Activity, videoBoxLayout!!)
                .setScaleType(PlayStateParams.fitparent)
                .hideAllUI()
                .setNetWorkTypeTie(false)
                .setAutoReConnect(true, 3)
                .forbidTouch(true)
                .setOnInfoListener(object : IMediaPlayer.OnInfoListener {
                    override fun onInfo(mp: IMediaPlayer, what: Int, extra: Int): Boolean {

                        if (what == PlayStateParams.STATE_COMPLETED) {
                            isCurrentVideoPlaying = false
                            UtilH.saveProgress(mContext, url, 0)
                        } else {
                            isCurrentVideoPlaying = true
                        }

                        return true
                    }
                })
                .setPlaySource(url)
                .startPlay()
                .seekTo(hisTime)

        videoBoxLayout!!.setOnTouchListener { v, event ->
            mCurrX = event.rawX
            mCurrY = event.rawY - 25
            Log.i("currP", "currX$mCurrX====currY$mCurrY")
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    //获取相对View的坐标，即以此View左上角为原点
                    mTouchStartX = event.x
                    mTouchStartY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    Log.i("TAG", "currX" + event.x + "====currY" + event.y)
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop || Math.abs(event.y - mTouchStartY) > mTouchSlop) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                        isMove = true
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if (Math.abs(event.x - mTouchStartX) > mTouchSlop ||
                            Math.abs(event.y - mTouchStartY) > mTouchSlop || isMove) {
                        Log.i("TAG", "is move")
                        updateViewPosition()
                    } else {
                        if (!isMove) {
                            YDLMusicHelper.startPlayingActivity(context, 0)
                        }
                        Log.i("TAG", "is click")
                    }
                    isMove = false
                    mTouchStartY = 0f
                    mTouchStartX = mTouchStartY
                }
            }
            true
        }


        startTimer(url!!)
    }

    private fun startTimer(url: String) {
        if (timer == null) {
            timer = Timer()
        }
        timer?.schedule(object : TimerTask() {
            override fun run() {
                if (isCurrentVideoPlaying) {
                    var time = videoView?.currentPosition ?: 0
                    if (time < 3000) return
                    UtilH.saveProgress(context, url, time)
                }
            }
        }, 1000, 1000)
    }


    fun stopVideo() {
        if (videoView != null) {
            videoView!!.stopPlay()
            videoView = null
        }
        YDLMusicHelper.isVideoPlaying = false
        YDLMusicHelper.playType = 0
        if (timer != null) {
            timer!!.cancel()
        }
        timer = null
    }


    private fun getStringTime(time: Int): String {
        if (time <= 0) return "00:00"
        var min = time / 60000
        var ss = (time - min * 60000) / 1000

        var mm = "" + min
        var SS = "" + ss
        if (min < 10) {
            mm = "0$mm"
        }
        if (ss < 10) {
            SS = "0$ss"
        }
        return "$mm:$SS"
    }

    private fun updatePlayTime() {
        currentPlayingTimeView?.text = getStringTime(time)
        durationView?.text = getStringTime(allTime)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //获取相对屏幕的坐标，即以屏幕左上角为原点
        mCurrX = event.rawX
        mCurrY = event.rawY - 25
        Log.i("currP", "currX$mCurrX====currY$mCurrY")
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                //获取相对View的坐标，即以此View左上角为原点
                mTouchStartX = event.x
                mTouchStartY = event.y
            }
            MotionEvent.ACTION_MOVE -> updateViewPosition()
            MotionEvent.ACTION_UP -> {
                updateViewPosition()
                mTouchStartY = 0f
                mTouchStartX = mTouchStartY
            }
        }
        return true
    }

    private fun updateViewPosition() {
        //更新浮动窗口位置参数
        wmParams.x = (mCurrX - mTouchStartX).toInt()
        wmParams.y = (mCurrY - mTouchStartY).toInt()
        wm!!.updateViewLayout(this, wmParams)
    }

    fun updatePlayState() {
        if (YDLMusicHelper.isPlaying()) {
            playState!!.setImageResource(R.drawable.ico_yyfc_pause)
        } else {
            playState!!.setImageResource(R.drawable.ico_yyfc_play)
            for (listener in listeners) {
                listener.onPlayFinish()
            }
        }
    }


    fun setPlayingState() {
        playState!!.setImageResource(R.drawable.ico_yyfc_pause)
        resetAudioAndVideoView()
    }

    fun onDestroy() {
        listeners.clear()
        mStateChangeListener?.let { YDLMusicPlayer.getInstance().removeListener(it) }
    }

    fun addFloatClickListener(floatClickListener: FloatViewPlayListener) {
        listeners.add(floatClickListener)
    }

    fun removeFloatClickListener(floatClickListener: FloatViewPlayListener) {
        listeners.remove(floatClickListener)
    }

    interface FloatViewPlayListener {

        fun onPauseClick()

        fun onStartClick()

        fun onPlayFinish()
    }

    internal inner class MyHandler : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                UPDATE_VIEW_STATE -> updatePlayState()
                UPDATE_VIEW_COMPLETE -> {
                    updatePlayState()
                    for (listener in listeners) {
                        //数据重新设置回调
                        listener.onPlayFinish()
                    }
                }
                UPDATE_PLAY_TIME -> {
                    updatePlayTime()
                }
            }
        }
    }
}