package com.xty.common.services

import android.app.*
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.widget.RemoteViews
import com.alibaba.android.arouter.facade.annotation.Route
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.R
import com.xty.common.arouter.ARouterUrl
import com.xty.common.broadCast.MusicBroadCast
import com.xty.common.event.MusicPlayStatus
import com.xty.network.model.MusicBean
import org.greenrobot.eventbus.EventBus


/**
 * 音乐播放服务
 */
@Route(path = ARouterUrl.MUSIC_SERVICE)
class MusicService : NotificationListenerService(), OrderProiver {

    var noficationManager:NotificationManager?=null
    var medic: MediaPlayer? = null
    var notification: Notification? = null
    var builder : Notification.Builder?=null
    var musicBean:MusicBean?=null
    var remoteViews:RemoteViews?=null
    var channelId="音乐播放"
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        intent?.let {
            when {
                it.hasExtra("close") -> {
                    stopMusic()
                }
                it.hasExtra("music") -> {
                 var  newBean= it.getSerializableExtra("music") as MusicBean

                    initMedicMusicPlayer(newBean)
                }
                it.hasExtra("play") -> {
                    changeStatus()
                }
                it.hasExtra("manager") -> {
                    if(noficationManager==null){
                    }
                }
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }




    private fun changeStatus() {
        if(musicBean==null){
            return
        }
        medic?.let {
            if(it.isPlaying){
                it.pause()
                musicBean!!.isPlayer = false
                EventBus.getDefault().post(MusicPlayStatus(musicBean!!))
                createNofication(false)
            }else{
                it.start()
                musicBean!!.isPlayer = true
                EventBus.getDefault().post(MusicPlayStatus(musicBean!!))
                createNofication(true)
            }
            Const.nowMusicBean=musicBean
        }
    }

    /**
     * 初始化
     */
    private fun initMedicMusicPlayer(bean: MusicBean) {
        if (medic == null) {
            medic = MediaPlayer()
            LogUtils.d("初始化播放器")
        }
        medic?.let {
            if (it.isPlaying) {
                //如果不一样 则播放新资源
                    if(musicBean!!.fileId!=bean.fileId){
                        musicBean=bean
                        it.stop()
                         setPlayer(musicBean!!.fileUrl)
                    }
                return
            } else {
                musicBean=bean
                setPlayer(musicBean!!.fileUrl)

            }
        }
    }


    private fun setPlayer(path:String) {
        medic?.let {
            try{
                it.reset()
                listenerPlayer()
                it.setDataSource(this, Uri.parse(path))
                //需使用异步缓冲
                it.prepareAsync()
            }catch (e:Exception){
                medic!!.reset()
                medic==null
                medic = MediaPlayer()
                listenerPlayer()
                medic!!.setDataSource(this, Uri.parse(path))
                //需使用异步缓冲
                medic!!.prepareAsync()
                //直接创建
                createNofication(false)
            }
        }
    }

    /**
     * 消息创建
     */
    private fun createNofication(isPlay: Boolean) {
        EventBus.getDefault().post(MusicPlayStatus(musicBean!!))
        remoteViews = RemoteViews(packageName, R.layout.layout_music)
        remoteViews!!.setTextViewText(R.id.mTvShow,musicBean!!.fileName)
        if(isPlay){
            remoteViews!!.setImageViewResource(R.id.mPlay,R.mipmap.ic_stop)
        }else{
            remoteViews!!.setImageViewResource(R.id.mPlay,R.mipmap.ic_player)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder=Notification.Builder(this,channelId)
            noficationManager = getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
            //Android8.0开始必须给每个通知分配对应的渠道
            var notificationChannel=NotificationChannel(channelId,channelId,NotificationManager.IMPORTANCE_LOW)
            notificationChannel.enableLights(false)
            notificationChannel.setShowBadge(false)
            noficationManager?.createNotificationChannel(notificationChannel)
        }else{
            builder=Notification.Builder(this)
        }


        //播放按钮的控制
        var intentPlay=Intent(this, MusicBroadCast::class.java)
        intentPlay.action="music_broad_play"
        intentPlay.putExtra("play","play")
        var pendingPlay=PendingIntent.getBroadcast(this,0,intentPlay,0)
        remoteViews!!.setOnClickPendingIntent(R.id.mPlay,pendingPlay)

        notification = builder!!
            .setSmallIcon(R.mipmap.ic_logo)
            .setContent(remoteViews)
            .setAutoCancel(false)
            .build();
            notification!!.flags = Notification.FLAG_ONGOING_EVENT //常驻通知栏



        startForeground(1, notification)
    }
    /**
     * 创建监听事件 并添加前台时间
     */
    private fun listenerPlayer() {
        //播放完毕
        medic!!.setOnCompletionListener {
            stopMusic()
        }
        //监听媒体流是否装载完成
        medic!!.setOnPreparedListener {
            it.start()
            Const.nowMusicBean=musicBean
            musicBean!!.isPlayer=true
            createNofication(true)
        }
        //监听流媒体加载出错的问题
        medic!!.setOnErrorListener { mp, what, extra ->
            LogUtils.e("加载文件错误 :$what")
            stopMusic()
            true
        }
    }

    private fun stopMusic() {
        if (medic != null) {
            medic!!.stop()
            medic!!.release()
            medic=null
            musicBean?.let {
                musicBean!!.isPlayer = false
                EventBus.getDefault().post(MusicPlayStatus(musicBean!!))
                Const.nowMusicBean=null
                Const.musicLoading=false
            }

        }
        stopForeground(true)
        stopSelf()
    }

    override fun init(context: Context?) {
    }

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        LogUtils.d("新消息创建 ")
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification? ) {
        super.onNotificationRemoved(sbn)
        LogUtils.d("消息被移除 ")
    }
    override fun onDestroy() {
        LogUtils.d("服务终止music ")
        stopMusic()
        super.onDestroy()

    }

}