package com.yidianling.muse.activity

import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.SeekBar
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.webview.H5Params
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.event.MeditationEvent
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper.Companion.show
import com.yidianling.common.tools.ToastUtil
import com.yidianling.home.http.MuseHttp
import com.yidianling.muse.R
import com.yidianling.muse.bean.MeditationPlayModuleBean
import com.yidianling.muse.constants.MuseBIConstants
import com.yidianling.muse.event.MeditationFloatEvent
import com.yidianling.muse.helper.MediaPlayerManager
import com.yidianling.muse.utils.MediaPlayerTimeUtil
import com.yidianling.muse.utils.MeditationFloatPermissionUtil
import com.yidianling.muse.widget.QuitMeditationDialog
import com.yidianling.muse.widget.ShareMeditationDialog
import com.yidianling.user.api.service.IUserService
import de.greenrobot.event.EventBus
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_play_meditation.*
import kotlinx.android.synthetic.main.activity_play_meditation.iv_close
import kotlinx.android.synthetic.main.activity_play_meditation.tv_title
import kotlinx.android.synthetic.main.player_control_view.*
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt


@Route(path = "/muse/play")
class PlayMeditationActivity : BaseActivity() {

    private var mMeditationId: Long? = null
    private var mMeditationType: Int? = null
    private var mMediaId: Long? = null
    private var mMediaUrl = ""
    private var mMediaCoverUrl = ""

    private var mMinProgramId: String? = null
    private var mCateId: Int? = null
    private var mTagId: String? = null
    private var mMark: Int? = null

    private var mTitle = ""
    private var mDesc = ""
    private var mStatus = 0

    private var mBusinessType = 0

    private var mediaListLink = ""

    private var meditations = mutableListOf<MeditationPlayModuleBean.MeditationDetail>()
    private var currentMeditation: MeditationPlayModuleBean.MeditationDetail? = null

    private var currentMeditationIndex = 0

    private var collected = false
    private var isPlaying = false

    private var shareDialog: ShareMeditationDialog? = null
    private var quitDialog: QuitMeditationDialog? = null

    private var mTimer = Timer()
    private var mMediaPlayer: MediaPlayer? = null

    private var duration = 0

    private var isSeekbarChanging = false

    private var mDisposable: Disposable? = null
    private lateinit var mObservable: Observable<Long>
    private var mObserver: Observer<Long>? = null

    private var mBuried: String? = null

    private var mVideoId: String? = null
    private var mIndexForMini = 0

    private var mMinProgramPath: String? = null

    /**
     * 传递过来的mediaId  用于判断正在播放的是否是同一条音频
     */
    private var mMediaIdFromLocal: Long? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        PlayerFloatHelper.removeResetView()

        mMediaPlayer = MediaPlayerManager.getInstance(this)?.getMediaPlayer()

        EventBus.getDefault().register(this)

        mMediaIdFromLocal = intent?.getLongExtra("MEDIA_ID", 0L)
        mMeditationId = intent?.getLongExtra("MEDITATION_ID", 0L)
        mMeditationType = intent?.getIntExtra("MEDITATION_TYPE", 0)
        mMediaUrl = intent?.getStringExtra("MEDIA_URL") ?: ""
        mMediaCoverUrl = intent?.getStringExtra("MEDIA_COVER_URL") ?: ""

        initView()
        getData()
    }


    override fun initDataAndEvent() {
    }

    private fun getData() {
        updateUIByMeditationType()
        if (mMeditationId == null || (mMediaIdFromLocal == null && mMeditationType != 0)) {
            return
        }
//        声音详情
        if (mMeditationType == 0) {
            MuseHttp.getInstance().getPureMusicPlayDetail(
                meditionType = mMeditationType!!,
                meditationId = mMeditationId!!
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    if (it.code.equals("200") && it.data != null) {
                        val module = it.data
                        mMediaId = module.mediaId

                        mMinProgramId = module.minProgramId
                        mCateId = module.cateId
                        mTagId = module.tagId
                        mMark = module.mark

                        meditations.clear()

                        module.mediaList?.forEach { meditationPlayBean ->

                            meditations.add(meditationPlayBean)

                            if (meditationPlayBean.mediaId == mMediaId) {

                                currentMeditation =
                                    meditationPlayBean.copy(
                                        meditationType = mMeditationType,
                                        meditationId = mMeditationId!!
                                    )

                                mMediaId = module?.mediaId ?: 0L
                                mTitle = meditationPlayBean.title
                                mDesc = meditationPlayBean.desc ?: ""

                                mMediaCoverUrl = meditationPlayBean.coverImageUrl

                                mMediaUrl = meditationPlayBean.mediaUrl

                                val currentPosition = meditationPlayBean.broadcastTime

                                mBusinessType = meditationPlayBean.businessType

                                mStatus = meditationPlayBean.status

                                mBuried = meditationPlayBean.buried

                                collected = mStatus == 1

                                mVideoId = meditationPlayBean.videoId

                                mIndexForMini = 0

                                updateUI()

                                formatMiniPath()

                                initMediaPlayer(
                                    mMediaUrl,
                                    currentPosition,
                                    mMediaIdFromLocal == mMediaId
                                )
                            }
                        }
                    }
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        show(msg)
                    }
                })
        } else {
            MuseHttp.getInstance().getMeditationPlayDetail(
                meditionType = 1,
                mediaId = mMediaIdFromLocal!!,
                meditationId = mMeditationId!!
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {

                    if (it.code.equals("200") && it.data != null) {

                        val module = it.data
                        mMediaId = module.mediaId
                        mMinProgramId = module.minProgramId
                        mCateId = module.cateId
                        mTagId = module.tagId
                        mMark = module.mark

                        meditations.clear()

                        module.mediaList?.forEachIndexed { index, meditationPlayBean ->

                            meditations.add(meditationPlayBean)

                            if (meditationPlayBean.mediaId == mMediaId) {

                                mIndexForMini = index

                                currentMeditation =
                                    meditationPlayBean.copy(
                                        meditationType = mMeditationType,
                                        meditationId = mMeditationId!!
                                    )

                                mMediaId = module?.mediaId ?: 0L
                                mTitle = meditationPlayBean.title
                                mDesc = meditationPlayBean.desc ?: ""

                                mMediaCoverUrl = meditationPlayBean.coverImageUrl

                                mMediaUrl = meditationPlayBean.mediaUrl

                                val currentPosition = meditationPlayBean.broadcastTime

                                mBusinessType = meditationPlayBean.businessType

                                mStatus = meditationPlayBean.status

                                mBuried = meditationPlayBean.buried

                                collected = mStatus == 1

                                mVideoId = meditationPlayBean.videoId

                                formatMiniPath()

                                updateUI()

                                initMediaPlayer(
                                    mMediaUrl,
                                    currentPosition,
                                    mMediaIdFromLocal == mMediaId
                                )
                            }
                        }
                    }
                }, object : ThrowableConsumer() {
                    override fun accept(msg: String) {
                        show(msg)
                    }
                })
        }
    }

    private fun updateUIByMeditationType() {
        val event = MeditationFloatEvent(false)
        EventBus.getDefault().post(event)

//        声音类型
        if (mMeditationType == 0) {
            exo_rew.visibility = View.GONE
            exo_ffwd.visibility = View.GONE
            exo_prev.visibility = View.GONE
            exo_next.visibility = View.GONE
            iv_time_off.visibility = View.GONE
            tv_time_off.visibility = View.GONE

            ll_pure_music_time_off.visibility = View.VISIBLE
            iv_pure_music_list.visibility = View.VISIBLE

        } else {
            exo_rew.visibility = View.VISIBLE
            exo_ffwd.visibility = View.VISIBLE
            exo_prev.visibility = View.VISIBLE
            exo_next.visibility = View.VISIBLE
            iv_time_off.visibility = View.VISIBLE
            tv_time_off.visibility = View.VISIBLE

            ll_pure_music_time_off.visibility = View.GONE
            iv_pure_music_list.visibility = View.GONE
        }

        initClickListener()

    }

    private fun initClickListener() {
        iv_pure_music_list.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            //列表点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_LIST_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            if (!mediaListLink.isNullOrBlank()) {
                ChooseMusicActivity.launch(this, H5Params(mediaListLink, ""))
            }
        }

        iv_collect.setOnClickListener {
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnClickListener
            }
            //快进点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_COLLECT_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )

            if (!ModularServiceManager.provide(IUserService::class.java)
                    .loginByOneKeyLogin(this, true)
            ) {
                return@setOnClickListener
            }
            if (mMeditationId == null || mMediaId == null) return@setOnClickListener
            MuseHttp.getInstance().collectMeditation(
                meditationId = mMeditationId!!,
                mediaId = mMediaId!!,
                status = if (collected) 0 else 1, businessType = mBusinessType
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ result ->
                    if (result != null && result.code == "200") {
                        collected = !collected
                        if (collected) {
                            show("收藏成功！")
                            iv_collect.setImageResource(R.drawable.icon_meditation_collected)
                        } else {
                            show("取消收藏！")
                            iv_collect.setImageResource(R.drawable.icon_play_meditation_collect)
                        }
                    } else {

                    }
                }, {
                    object : ThrowableConsumer() {
                        override fun accept(msg: String) {

                        }
                    }
                })
        }
    }

    override fun layoutResId(): Int {
        return R.layout.activity_play_meditation
    }

    private fun initView() {

        iv_close.setOnClickListener {
            //关闭点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_CLOSE_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )

            if (mMeditationType == 0) {
                if (mMeditationId != null && mMediaId != null) {
                    MediaPlayerTimeUtil.uploadPlayRecord(
                        meditationId = mMeditationId!!.toInt(),
                        isQuit = 1, mediaId = mMediaId!!,
                        playTime = (seekbar_play_progress.progress / 1000.00).roundToInt(),
                        isComplete = 0
                    )
                    stopPlay()
                    finish()
                } else {
                    stopPlay()
                    finish()
                }

            } else {
                if (quitDialog == null) {
                    quitDialog = QuitMeditationDialog.newInstance()
                }
                if (quitDialog != null && quitDialog?.isAdded == false) {
                    quitDialog?.setListener(object : QuitMeditationDialog.ClickListener {
                        override fun quit() {
                            if (mMeditationId != null && mMediaId != null) {
                                MediaPlayerTimeUtil.uploadPlayRecord(
                                    meditationId = mMeditationId!!.toInt(),
                                    isQuit = 1, mediaId = mMediaId!!,
                                    playTime = (seekbar_play_progress.progress / 1000.00).roundToInt(),
                                    isComplete = 0
                                )
                            }
                            stopPlay()
                            finish()
                        }
                    })
                    quitDialog?.show(supportFragmentManager, QuitMeditationDialog.TAG)
                }
            }

        }

        iv_back.setOnClickListener {
            //收起点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_PACK_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            val event = MeditationFloatEvent(
                true,
                meditation = currentMeditation?.copy(
                    meditationType = mMeditationType, meditationId =
                    mMeditationId ?: 0
                ),meditations = meditations
            )
            EventBus.getDefault().post(event)

            Handler().postDelayed({
                finish()
            }, 300)
        }

        iv_share.setOnClickListener {
            //分享点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_SHARE_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            if (shareDialog == null) {
                shareDialog = ShareMeditationDialog
                    .newInstance(
                        shareTitle = mTitle,
                        shareContent = mDesc,
                        shareUrl = mMediaUrl,
                        shareImageUrl = mMediaCoverUrl,
                        miniId = mMinProgramId!!,
                        miniPath = mMinProgramPath!!
                    )
            }
            if (shareDialog != null && shareDialog?.isAdded == false) {
                shareDialog?.show(supportFragmentManager, ShareMeditationDialog.TAG)
            }
        }

        iv_time_off.setOnClickListener {
            //定时 ioc点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_IOC_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            val intent = Intent(this, MeditationTimeOffActivity::class.java)
            intent.putExtra("BG_IMAGE_URL", mMediaCoverUrl)
            startActivityForResult(intent, request_code)
        }

        ll_pure_music_time_off.setOnClickListener {
            //定时 ioc点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_IOC_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            val intent = Intent(this, MeditationTimeOffActivity::class.java)
            intent.putExtra("BG_IMAGE_URL", mMediaCoverUrl)
            startActivityForResult(intent, request_code)
        }

        exo_play.setOnClickListener {

            if (Utils.isFastClick()) return@setOnClickListener

            if (isPlaying) {
                mMediaPlayer?.pause()
                if (mMeditationId == null || mMediaId == null) return@setOnClickListener

                val playTime = (seekbar_play_progress.progress / 1000.00).roundToInt()
                MediaPlayerTimeUtil.uploadPlayRecord(
                    meditationId = mMeditationId?.toInt(),
                    mediaId = mMediaId,
                    isQuit = 0,
                    playTime = playTime,
                    isComplete = 0
                )

                //暂停埋点
                ActionCountUtils.baiDuCountSign3(
                    MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                    MuseBIConstants.YDL_MUSE_PLAY_PAUSE_CLICK,
                    currentMeditation?.title ?: "",
                    mBuried ?: "",
                    ""
                )

            } else {
                val duration = mMediaPlayer?.duration

                MediaPlayerManager.getInstance(this@PlayMeditationActivity)?.play()

                if (duration != null) {
                    seekbar_play_progress.max = duration
                }
                mTimer.cancel()
                mTimer = Timer()
                mTimer.schedule(object : TimerTask() {
                    override fun run() {
                        if (!isSeekbarChanging) {
                            seekbar_play_progress.progress = MediaPlayerManager
                                .getInstance(this@PlayMeditationActivity)
                                ?.getMediaPlayer()?.currentPosition ?: 0
                        }
                    }
                }, 0, 50)
                //播放埋点
                ActionCountUtils.baiDuCountSign3(
                    MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                    MuseBIConstants.YDL_MUSE_PLAY_PLAY_CLICK,
                    currentMeditation?.title ?: "",
                    mBuried ?: "",
                    ""
                )
            }
            isPlaying = !isPlaying
            if (isPlaying) {
                exo_play.setImageResource(R.drawable.icon_pause_play)
            } else {
                exo_play.setImageResource(R.drawable.icon_pause_meditation)
            }

        }

        exo_prev.setOnClickListener {

            if (Utils.isFastClick()) return@setOnClickListener

            //上一曲埋点
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_LAST_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            var currentPosition = 0
            meditations?.forEachIndexed { index, meditationDetail ->
                if (meditationDetail.mediaId == mMediaId) {
                    currentPosition = index
                }
            }
            if (currentPosition > 0) {
                if (mMeditationId == null || mMediaId == null) return@setOnClickListener

                val playTime = (seekbar_play_progress.progress / 1000.00).roundToInt()
                MediaPlayerTimeUtil.uploadPlayRecord(
                    meditationId = mMeditationId?.toInt(),
                    mediaId = mMediaId,
                    isQuit = 0,
                    playTime = playTime,
                    isComplete = 0
                )

                val meditation = meditations[currentPosition - 1]

                currentMeditation = meditation.copy(meditationId = mMeditationId!!)

                mMediaId = meditation.mediaId
                mMediaCoverUrl = meditation.coverImageUrl
                mMediaUrl = meditation.mediaUrl
                mStatus = meditation.status

                mTitle = meditation.title
                mDesc = meditation.title

                mVideoId = meditation.videoId
                mIndexForMini = currentPosition - 1

                formatMiniPath()

                updateUI(needRefresh = false)

                initMediaPlayer(mMediaUrl, 0, mMediaIdFromLocal == mMediaId)
            } else {
                ToastUtil.toastShort("暂无内容")
            }
        }

        exo_next.setOnClickListener {
            if (Utils.isFastClick()) return@setOnClickListener

            //下一个点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_NEXT_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            var currentPosition = 0
            meditations?.forEachIndexed { index, meditationDetail ->
                if (meditationDetail.mediaId == mMediaId) {
                    currentPosition = index
                }
            }
            if (currentPosition < meditations.size - 1) {
                if (mMeditationId == null || mMediaId == null) return@setOnClickListener

                val playTime = (seekbar_play_progress.progress / 1000.00).roundToInt()
                MediaPlayerTimeUtil.uploadPlayRecord(
                    meditationId = mMeditationId?.toInt(),
                    mediaId = mMediaId,
                    isQuit = 0,
                    playTime = playTime,
                    isComplete = 0
                )

                val meditation = meditations[currentPosition + 1]

                currentMeditation = meditation.copy(meditationId = mMeditationId!!)

                mMediaId = meditation.mediaId
                mMediaCoverUrl = meditation.coverImageUrl
                mMediaUrl = meditation.mediaUrl
                mStatus = meditation.status

                mTitle = meditation.title
                mDesc = meditation.title
                mVideoId = meditation.videoId

                mIndexForMini = currentPosition + 1

                formatMiniPath()

                updateUI(needRefresh = false)

                initMediaPlayer(mMediaUrl, 0, mMediaIdFromLocal == mMediaId)
            } else {
                ToastUtil.toastShort("暂无内容")
            }
        }

        exo_rew.setOnClickListener {
            if (Utils.isFastClick()) return@setOnClickListener

            //快退点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_REW_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            val currentPosition = MediaPlayerManager
                .getInstance(this@PlayMeditationActivity)?.getMediaPlayer()?.currentPosition
            val seekPosition = 0.coerceAtLeast(currentPosition?.minus(15000) ?: 0)
            MediaPlayerManager.getInstance(this@PlayMeditationActivity)?.getMediaPlayer()
                ?.seekTo(seekPosition)

        }

        exo_ffwd.setOnClickListener {
            if (Utils.isFastClick()) return@setOnClickListener

            //快进点击事件
            ActionCountUtils.baiDuCountSign3(
                MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                MuseBIConstants.YDL_MUSE_PLAY_SPEED_CLICK,
                currentMeditation?.title ?: "",
                mBuried ?: "",
                ""
            )
            val currentPosition = MediaPlayerManager
                .getInstance(this@PlayMeditationActivity)?.getMediaPlayer()?.currentPosition
            val seekPosition = duration.coerceAtMost(currentPosition?.plus(15000) ?: 0)
            MediaPlayerManager
                .getInstance(this@PlayMeditationActivity)?.getMediaPlayer()?.seekTo(seekPosition)

        }

        seekbar_play_progress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

                if (mMediaPlayer != null) {
                    val totalDuration = mMediaPlayer!!.duration / 1000
                    val position = mMediaPlayer!!.currentPosition
                    exo_position.text = MediaPlayerTimeUtil.calculateTime(position / 1000)
                    exo_duration.text = MediaPlayerTimeUtil.calculateTime(totalDuration)
                }

            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                //进度条点击事件
                ActionCountUtils.baiDuCountSign3(
                    MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
                    MuseBIConstants.YDL_MUSE_PLAY_PROGRESS_CLICK,
                    currentMeditation?.title ?: "",
                    mBuried ?: "",
                    ""
                )
                isSeekbarChanging = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekbarChanging = false
                seekBar?.progress?.let {
                    MediaPlayerManager.getInstance(this@PlayMeditationActivity)?.seekTo(
                        it
                    )
                    if (mMediaPlayer != null) {
                        exo_position.text = MediaPlayerTimeUtil.calculateTime(
                            mMediaPlayer!!.currentPosition / 1000
                        )
                    }

                }
            }

        })

        val isLoop =
            MediaPlayerManager.getInstance(this@PlayMeditationActivity)?.getTimeOffStatus() == true
        initPlayCompletionListener(isLoop = isLoop)

        MeditationFloatPermissionUtil.checkSuspendedWindowPermission(this) {

        }

    }

    private fun initPlayCompletionListener(isLoop: Boolean = false, isSingle: Boolean = false) {

        mMediaPlayer?.setOnCompletionListener {

            val duration = currentMeditation?.duration?.toInt() ?: 0
            val currentDuration = (mMediaPlayer?.currentPosition ?: 0) / 1000
            if (currentDuration == duration) {
                val playTime = (seekbar_play_progress.progress / 1000.00).roundToInt()

                MediaPlayerTimeUtil.uploadPlayRecord(
                    meditationId = mMeditationId?.toInt(),
                    mediaId = mMediaId,
                    isQuit = 0,
                    playTime = playTime,
                    isComplete = 1
                )
            }

            if (isLoop) {
                if (isSingle || meditations.size == 1) {
                    switchSound()
                } else {
                    switchSound()
                }
            }

            isPlaying = if (it.isPlaying) {
                exo_play.setImageResource(R.drawable.icon_pause_play)
                true
            } else {
                exo_play.setImageResource(R.drawable.icon_pause_meditation)
                false
            }
            if (mMediaPlayer?.isPlaying == true) {
                mMediaPlayer?.pause()
            }
        }

        mMediaPlayer?.setOnErrorListener { mp, what, extra -> true }

    }


    private fun switchSound() {
        var meditation: MeditationPlayModuleBean.MeditationDetail? = null
        meditations?.forEachIndexed { index, meditationDetail ->
            if (meditationDetail.mediaId == mMediaId) {
                currentMeditationIndex = index
            }
        }
        if (mMeditationId == null || mMediaId == null) return
        if (currentMeditationIndex < meditations.size - 1) {
            meditation = meditations[currentMeditationIndex + 1]
            mIndexForMini = currentMeditationIndex + 1
        } else {
            meditation = meditations[0]
            mIndexForMini = 0
        }
        currentMeditation = meditation.copy(meditationId = mMeditationId!!)

        mMediaId = meditation.mediaId
        mMediaCoverUrl = meditation.coverImageUrl
        mMediaUrl = meditation.mediaUrl
        mStatus = meditation.status

        mTitle = meditation.title
        mDesc = meditation.title

        mVideoId = meditation.videoId

        formatMiniPath()

        updateUI(needRefresh = false)

        initMediaPlayer(mMediaUrl, 0, mMediaIdFromLocal == mMediaId)
    }

    private fun initMediaPlayer(path: String, current: Int, isSameOne: Boolean = false) {

        if (MediaPlayerManager.getInstance(this)?.getAudioPath() != null &&
            MediaPlayerManager.getInstance(this)?.getMediaId() == mMediaId
        ) {
            if (mMediaPlayer?.isPlaying == true) {
                exo_play.setImageResource(R.drawable.icon_pause_play)
            } else {
                exo_play.setImageResource(R.drawable.icon_pause_meditation)
            }

            val currentPosition = mMediaPlayer?.currentPosition
            duration = mMediaPlayer?.duration ?: 0
            if (current >= 0) {
                seekbar_play_progress.max = duration
                seekbar_play_progress.progress = current
                exo_position.text = MediaPlayerTimeUtil.calculateTime(current)
            } else if (currentPosition != null) {
                seekbar_play_progress.max = duration
                seekbar_play_progress.progress = current
                exo_position.text = MediaPlayerTimeUtil.calculateTime(currentPosition / 1000)
            }
            exo_duration.text = MediaPlayerTimeUtil.calculateTime(duration / 1000)

            seekbar_play_progress.max = duration
            mTimer.cancel()
            mTimer = Timer()
            mTimer.schedule(object : TimerTask() {
                override fun run() {
                    if (!isSeekbarChanging) {
                        seekbar_play_progress.progress = mMediaPlayer?.currentPosition ?: 0
                    }
                }
            }, 0, 50)

        } else {
            MediaPlayerManager.getInstance(this)?.setAudioPath(path)
            MediaPlayerManager.getInstance(this)
                ?.setOnPreparedListener(object : MediaPlayerManager.OnMediaPlayerManagerListener {
                    override fun onPrepared(mediaPlayer: MediaPlayer) {
                        MediaPlayerManager.getInstance(this@PlayMeditationActivity)?.play()

                        if (mMediaPlayer?.isPlaying == true) {
                            exo_play.setImageResource(R.drawable.icon_pause_play)
                        } else {
                            exo_play.setImageResource(R.drawable.icon_pause_meditation)
                        }

                        val currentPosition = mMediaPlayer?.currentPosition
                        duration = mMediaPlayer?.duration ?: 0
                        if (current > 0) {
                            mMediaPlayer?.seekTo(current * 1000)
                            seekbar_play_progress.max = duration
                            seekbar_play_progress.progress = current
                            exo_position.text = MediaPlayerTimeUtil.calculateTime(current)
                        } else if (currentPosition != null) {
                            seekbar_play_progress.max = duration
                            seekbar_play_progress.progress = current
                            exo_position.text =
                                MediaPlayerTimeUtil.calculateTime(currentPosition / 1000)
                        }
                        exo_duration.text = MediaPlayerTimeUtil.calculateTime(duration / 1000)
                        mTimer.schedule(object : TimerTask() {
                            override fun run() {
                                if (!isSeekbarChanging) {
                                    seekbar_play_progress.progress =
                                        mMediaPlayer?.currentPosition ?: 0
                                }
                            }
                        }, 0, 50)

                    }
                })
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && request_code == requestCode) {
            val minute = data?.extras?.getInt("TIME_OFF_MINUTE", 0)
            if (minute != null && minute > 0) {
                if (mMeditationType == 0) {
                    initPlayCompletionListener(isLoop = true, isSingle = true)
                    tv_time_off_pure_music.visibility = View.VISIBLE
                    tv_time_off.visibility = View.GONE
                    mDisposable?.dispose()
                    mDisposable = null
                    MediaPlayerManager.getInstance(this)?.setTimeOffStatus(true)
                    initRxTimeOff((minute * 60 * 1000).toLong(), 0)
                } else {
                    initPlayCompletionListener(isLoop = true, isSingle = false)
                    tv_time_off_pure_music.visibility = View.GONE
                    tv_time_off.visibility = View.VISIBLE
                    mDisposable?.dispose()
                    mDisposable = null
                    MediaPlayerManager.getInstance(this)?.setTimeOffStatus(true)
                    initRxTimeOff((minute * 60 * 1000).toLong(), 1)
                }
                val event = MeditationFloatEvent(false, time = (minute * 60 * 1000).toLong())
                EventBus.getDefault().post(event)
            } else {
                initPlayCompletionListener()
                MediaPlayerManager.getInstance(this)?.setTimeOffStatus(false)
                mDisposable?.dispose()
                mDisposable = null
                tv_time_off.visibility = View.GONE
                tv_time_off_pure_music.visibility = View.GONE
                mMediaPlayer?.isLooping = false
                val event = MeditationFloatEvent(false, time = 0)
                EventBus.getDefault().post(event)
            }
        }
    }

    private fun updateUI(needRefresh: Boolean = true) {
        tv_title.text = mTitle
        tv_content.text = mDesc
        Glide.with(this)
            .load(mMediaCoverUrl)
            .transition(DrawableTransitionOptions.withCrossFade())
            .into(iv_bg)
        iv_collect.setImageResource(
            if (mStatus == 0) {
                R.drawable.icon_play_meditation_collect
            } else {
                R.drawable.icon_meditation_collected
            }
        )

        if (needRefresh) {
            if (MediaPlayerManager.getInstance(this)?.getTimeOffStatus() == true) {
                val timeOff = MediaPlayerManager.getInstance(this)?.getTimeOff()
                if (timeOff != null && timeOff > 0 && mMeditationType != null) {
                    initRxTimeOff(timeOff, mMeditationType!!)
                }
            }
        }

        ActionCountUtils.baiDuCountSign3(
            MuseBIConstants.YDL_MUSE_MEDITATION_MUSIC_PLAY_PAGE,
            MuseBIConstants.YDL_MUSE_PLAY_PAGE_VISIT,
            mTitle,
            mBuried ?: "",
            ""
        )

    }

    private fun initRxTimeOff(time: Long, meditationType: Int) {

        MediaPlayerManager.getInstance(this)?.initRxTimeOff(time)

        mObservable = Observable.interval(0, 1, TimeUnit.SECONDS)
            .take(time / 1000 + 1)
            .map { t -> time - t * 1000 }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

        mObserver = object : Observer<Long> {
            override fun onSubscribe(d: Disposable) {
                mDisposable = d
            }

            override fun onNext(t: Long) {
                if (meditationType == 0) {
                    tv_time_off_pure_music.text = MediaPlayerTimeUtil.formatTimeOff(t)
                } else {
                    tv_time_off.text = MediaPlayerTimeUtil.formatTimeOff(t)
                }
            }

            override fun onError(e: Throwable) {
                mDisposable?.dispose()
            }

            override fun onComplete() {
                if (mMediaPlayer?.isPlaying == true) {
                    mMediaPlayer?.stop()
                    exo_play.setImageResource(R.drawable.icon_pause_meditation)
                }
                if (meditationType == 0) {
                    tv_time_off_pure_music.text = ""
                } else {
                    tv_time_off.text = ""
                }
                finish()
            }
        }

        if (mObserver != null && mObserver is Observer<Long>) {
            mObservable.subscribe(mObserver as Observer<Long>)
        }

        if (mDisposable?.isDisposed == true && mObserver != null && mObserver is Observer<Long>) {
            mObservable?.subscribe(mObserver as Observer<Long>)
        }

    }

    fun onEventMainThread(event: MeditationEvent) {
        if (event != null) {

            mTitle = event.title
            mDesc = event.desc
            mMediaUrl = event.mediaUrl
            mMediaCoverUrl = event.mediaCoverUrl

            mStatus = event.status

            updateUI(needRefresh = false)

            if (event.mediaUrl == MediaPlayerManager.getInstance(this)?.getAudioPath()) {
                return
            }
            initMediaPlayer(event.mediaUrl, 0, mMediaIdFromLocal == mMediaId)
        }
    }

    override fun onBackPressed() {
        val event = MeditationFloatEvent(true, meditation = currentMeditation,meditations = meditations)
        EventBus.getDefault().post(event)
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        mDisposable?.dispose()
        mTimer.cancel()
    }

    private fun stopPlay() {
        MediaPlayerManager.getInstance(this)?.stop()
    }

    companion object {
        const val request_code = 0x0001
    }

    private fun formatMiniPath() {
        mMinProgramPath = "/pages/player/index?share=1&meditationId=${mMeditationId}" +
                "&meditionType=${mMeditationType}&mediaId=${mMediaId}&collectStatus=${mStatus}&index=${mIndexForMini}&videoId=${mVideoId}&cateId=${mCateId}&mark=${mMark}&tagId=${mTagId}"
        LogUtil.d("Lancet======", mMinProgramPath)
    }

}