package com.jld.vod.view

import android.app.Activity
import android.app.Service
import android.content.*
import android.graphics.drawable.Drawable
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.jld.vod.R
import com.jld.vod.audio.MusicController
import com.jld.vod.base.BaseActivity
import com.jld.vod.config.AudioFlag
import com.jld.vod.config.AudioPlayerConstant
import com.jld.vod.config.AudioPlayerConstant.ACITION_AUDIO_PLAYER_PAUSE
import com.jld.vod.config.AudioPlayerConstant.ACITION_AUDIO_PLAYER_PLAY
import com.jld.vod.config.AudioPlayerConstant.ACITION_AUDIO_PLAYER_PLAY_COMPLETE
import com.jld.vod.config.AudioPlayerConstant.ACITION_AUDIO_PLAYER_PREPARE
import com.jld.vod.config.AudioPlayerConstant.ACITION_AUDIO_PLAYER_STOP
import com.jld.vod.config.AudioPlayerConstant.playerState
import com.jld.vod.config.Config
import com.jld.vod.model.bean.Audio
import com.jld.vod.model.bean.MusicByMidBean
import com.jld.vod.model.bean.MusicByMidBeans
import com.jld.vod.service.MusicPlayerService
import com.jld.vod.ui.animator.RatateImage
import com.jld.vod.ui.animator.RatateRobotArm
import com.jld.vod.utils.*
import com.jld.vod.utils.http.OkHttpUtils
import com.jld.vod.viewmodel.MusicPlayViewModel
import com.smp.soundtouchandroid.AudioSpeed
import com.smp.soundtouchandroid.MediaCallBack
import com.smp.soundtouchandroid.OnProgressChangedListener
import kotlinx.android.synthetic.main.activity_main.fl_bg
import kotlinx.android.synthetic.main.activity_main.iv_back_page
import kotlinx.android.synthetic.main.activity_main.iv_brightness
import kotlinx.android.synthetic.main.activity_main.iv_fl_power
import kotlinx.android.synthetic.main.activity_main.iv_home
import kotlinx.android.synthetic.main.activity_main.iv_power
import kotlinx.android.synthetic.main.activity_main.iv_volume
import kotlinx.android.synthetic.main.activity_main.tv_main_time
import kotlinx.android.synthetic.main.activity_main.tv_main_week
import kotlinx.android.synthetic.main.activity_musice_play.*
import okhttp3.Call
import okhttp3.Response
import java.io.IOException
import java.util.*

/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/7/7 11:37
 */
class MusicPlayActivity : BaseActivity(),View.OnClickListener {

    private val TAG:String = "MusicPlayActivity"
    //音频播放类
    private var audio: Audio? = null

    //上一首
    private var audio_preImg: ImageView? = null

    //播放
    private var audio_playImg: ImageView? = null

    //下一首
    private var audio_nextImg: ImageView? = null

    private var speed = AudioSpeed.SPEED_NORMAL
    private var context: Activity? = null

    //显示UI
    private val MSG_SHOW_UI = 1

    //准备播放
    private val MSG_AUDIO_PREPARE = MSG_SHOW_UI + 1

    //自动播放
    private val MSG_AUTO_PLAY = MSG_AUDIO_PREPARE + 1

    private var albumView: RelativeLayout? = null
    private var ratateImage: RatateImage? = null

    private var ratateRobotArm: RatateRobotArm? = null//机械臂

    //播放总时间
    private var audio_totalTimeTv: TextView? = null

    //进度条
    private var skbProgress: SeekBar? = null

    //当前播放的进度
    private var audio_curren_playTv: TextView? = null

    private var connect = false
    private var musicController: MusicController? = null

    private var musicId:Int = 0;

    private var discMagneticStripe:ImageView? = null
    private var receiver: broadCastRecever = broadCastRecever()//更新时间广播
    private lateinit var musicPlayViewModel: MusicPlayViewModel
    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                MSG_SHOW_UI -> update()
                MSG_AUTO_PLAY -> autoPlay(needPlay)
            }
        }
    }

    /**
     * 播放回调
     */
    var mediaCallBack: MediaCallBack = object : MediaCallBack {
        override fun onError() {}
        override fun onChange(state: Int) {
            if (state == AudioPlayerConstant.ACITION_AUDIO_PLAYER_PLAY_PRE_AUDIO || state == AudioPlayerConstant.ACITION_AUDIO_PLAYER_PLAY_NEXT_AUDIO) {
                playerState = 0
                if (musicController != null) {
                    setAudio(musicController!!.audio)
                    setCurrentProgress(0)
                    tv_music_name.setText(audio!!.name)
                    tv_music_singer.setText(audio!!.author)
                  //  addAudioTitle()
                }
            } else {
                playerState = state
            }
            LogUtils.logD(TAG, "onChange=$state")
            changePlayUI()
        }

        override fun onPrepare() {
            LogUtils.logD(TAG, "onPrepare()")
            runOnUiThread { showLoading() }
        }

        override fun onPrepared(duration: Long) {
            LogUtils.logD(TAG, "onPrepared()")
            setInitDate(duration)
        }

        override fun onPlay() {
            LogUtils.logD(TAG, "onPlay()")
            runOnUiThread { finishLoading() }
        }

        override fun onStop() {
            LogUtils.logD(TAG, "onStop()")
        }

        override fun onPause() {
            LogUtils.logD(TAG, "onPause()")

        }

        override fun onComplete() {
            LogUtils.logD(TAG, "onComplete()")
        }
    }
    override fun getLayoutId(): Int {
        return R.layout.activity_musice_play
    }
    private fun setAudio(audio: Audio) {
        this.audio = audio
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
       LogUtils.logD(TAG, "onNewIntent")
        if (intent != null) {
            var audio: Audio? = intent.getSerializableExtra("audio") as Audio
            val play = intent.getBooleanExtra("play", false)
            val isHead = intent.getBooleanExtra("isHead", false)
            if (isHead && audio == null) {
                if (musicController != null) {
                    audio = musicController!!.audio
                }
            }

            if (audio != null) {
                if (!isSame(audio)) {
                    setAudio(audio)
                    changeToCurrent(play)
                } else {
                    judgeState()
                    changePlayUI()
                    if (playerState == ACITION_AUDIO_PLAYER_PAUSE) {
                        if (musicController != null && musicController!!.isPause) {
                            setCurrentProgress(musicController!!.playedDuration)
                        }
                    }
                }
            }
        }
    }

    /**
     * 是否相同
     */
    private fun isSame(audio: Audio?): Boolean {
        return if (audio == null) false else this.audio != null && audio.id === this.audio!!.id
    }

    /**
     * 变换到现在
     */
   private fun changeToCurrent( needPlay:Boolean) {
       if (needPlay) {
           play(audio);
       } else if (musicController != null) {
           judgeState();
           autoPlay(false);
           changePlayUI();
       }
   }
    /**
     * 进度
     */
    private fun setCurrentProgress(position: Long) {
        if (skbProgress != null) {
            skbProgress!!.progress = position.toInt()
        }
        if (audio_curren_playTv != null) {
            audio_curren_playTv!!.setText(getTimeStr(position.toInt()))
        }
    }

    /**
     * 初始化view
     */
    override fun initView() {
        super.initView()
        //上一首
        audio_preImg = findViewById(R.id.act_audio_player_button_prebuttonId)
        audio_preImg!!.setOnClickListener(this)
        //播放
        audio_playImg = findViewById(R.id.act_audio_player_button_playId)
        audio_playImg!!.setOnClickListener(this)

        //下一首
        audio_nextImg = findViewById(R.id.act_audio_player_button_nextId)
        audio_nextImg!!.setOnClickListener(this)

        //旋转图片
        albumView = findViewById(R.id.play_album_is)

        //机械臂
        discMagneticStripe = findViewById(R.id.iv_disc_magnetic_stripe)

        //总时间
        audio_totalTimeTv = findViewById(R.id.act_audio_player_total_timeId)
        //播放进度时间
        audio_curren_playTv = findViewById(R.id.act_audio_player_current_play_timeId)
        //进度条
        skbProgress = findViewById(R.id.act_audio_player_audio_progressId)
        //滑动监听
        skbProgress!!.setOnSeekBarChangeListener(SeekBarChangeEvent())

        iv_back_page.setOnClickListener {
            this.onBackPressed()
        }

        iv_home.setOnClickListener {
            go<HomeActivity>()
            finish()
        }

        //音量调节
        iv_volume.setOnClickListener {
            PopupUtils.popupUtilsVolume(this,iv_volume)
        }

        //待机
        iv_power.setOnClickListener {
            fl_bg.visibility = View.VISIBLE
        }
        iv_fl_power.setOnClickListener {
            fl_bg.visibility = View.INVISIBLE
        }

        //背光设置
        iv_brightness.setOnClickListener {
            PopupUtils.popupUtilsbrightness(this,iv_brightness)
        }

        //解决穿透问题
        fl_bg.setOnTouchListener(object :View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                return true
            }
        });
        //标题聚焦
        tv_music_name.setSelected(true)
    }

    /**
     * 初始化数据
     */
    override fun initData() {
        super.initData()
        val intent = intent
        context = this
        val bundle = intent.extras
        musicId = bundle!!.get("id") as Int
        val cid = bundle.get("cid")
        val mid = bundle.get("mid")
        val lid = bundle.get("lid")

        //初始化viewmodel
//        musicPlayViewModel = ViewModelProviders.of(this)
//            .get(MusicPlayViewModel::class.java)
//        musicPlayViewModel.findMusicMid()

        //获取一级列表数据
     //   val observer = Observer<List<MusicByMidBean>> { it->

           // setTest(it)
      //  }
     //   musicPlayViewModel.findMovieMidliveData.observe(this, observer)

        OkHttpUtils.getInstance().getDataAsyn(Config.ApiBaseUrl+ "/music/findMusicByCid?cid=$cid&mid=$mid&lid=$lid",object :OkHttpUtils.MyNetCall{
            override fun failed(call: Call?, e: IOException?) {
               LogUtils.logE("e="+e)
            }

            override fun success(call: Call?, response: Response?) {
                val json = response!!.body!!.string()
                val gson = Gson()
                val music = gson.fromJson(json, MusicByMidBeans::class.java)
                setTest(music.data)
                //LogUtils.logD("response"+music.code)
            }
        })

    }

    /**
     * 初始化事件
     */
    override fun initEvent() {
        super.initEvent()
        handler.sendEmptyMessage(MSG_SHOW_UI)
        ratateImage = RatateImage(this, albumView)
        ratateRobotArm = RatateRobotArm(this, discMagneticStripe!!)

        //动态背景图片
        val main_bg_img = SharedPrefUtils.getString(this,"main_bg_img")

        try {
            if (!main_bg_img.isEmpty())
            {
                val simpleTarget: SimpleTarget<Drawable?> = object : SimpleTarget<Drawable?>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) {
                        rl_music.setBackground(resource)
                    }
                }
                Glide.with(this).load(com.jld.vod.config.Config.ApiBaseUrl+"/synchronization/previewImg?imgUrl="
                        +main_bg_img).into(simpleTarget)
            }
        }catch (e: Exception)
        {
            e.printStackTrace()
        }
    }


    /**
     * 更新页面数据
     */
    private fun update() {
        //addAudioTitle()
        changePlayUI()
    }

    /**
     * 自动播放
     */
    private fun autoPlay(needPlay: Boolean) {
        LogUtils.logD( "autoPlay:playerState=$playerState")
        when (playerState) {
            AudioPlayerConstant.ACITION_AUDIO_PLAYER_PLAY -> if (musicController != null && musicController!!.isPlaying) {
                setInitDate(musicController!!.duration)
            }
            AudioPlayerConstant.ACITION_AUDIO_PLAYER_PAUSE -> if (musicController != null && musicController!!.isPause) {
                setInitDate(musicController!!.duration)
                setCurrentProgress(musicController!!.playedDuration)
            }
            else -> if (needPlay) {
                play()
            }
        }
    }

    /**
     * 初始时间
     */
    private fun setInitDate(duration: Long) {
        LogUtils.logD( "duration=$duration")
        if (musicController == null) return
        if (skbProgress != null) {
            skbProgress!!.setMax(duration.toInt())
        }
        if (audio_totalTimeTv != null) {
            audio_totalTimeTv!!.setText(getTimeStr(duration.toInt()))
        }
    }

    /**
     * 获取总时长
     */
    private fun getTimeStr(time: Int): String? {
        var time = time
        time = time / 1000000
        val min = time / 60 //分
        val second = time % 60
        var min1 = ""
        min1 = if (min < 10) {
            "0$min"
        } else {
            min.toString() + ""
        }
        var second1 = ""
        second1 = if (second < 10) {
            "0$second"
        } else {
            second.toString() + ""
        }
        return "$min1:$second1"
    }

    //音频列表
    private val audioList: MutableList<Audio> = ArrayList<Audio>()

    private fun setTest(music:List<MusicByMidBean>) {
        var musicName:String? = ""
        for ((index,e) in music.withIndex()) {
           // LogUtils.logD("清单:"+music[index])
             musicName = music[index].musicName

            val audio = Audio()
            //LogUtils.logD("MusicByMidBean"+e)
            audio.setFileUrl(Config.ApiBaseUrl+"/"+music[index].musicUrl)
            audio.setId((index.toLong() + 1))
            audio.setType(1)
            audio.setName(music[index].musicName)
            audio.author = music[index].musicSinger
            audioList.add(audio)
        }
//        this.runOnUiThread {
//            tv_music_name.setText(audioList[musicId].name)
//            tv_music_singer.setText(audioList[musicId].author)
//        }
//        LogUtils.logD("播放:$audioList----$musicId")

        for ((index,e) in audioList.withIndex()){
            LogUtils.logD("播放:$musicName-----"+audioList[index].name)
            if(audioList[index].name == musicName){
                this.runOnUiThread {
                    tv_music_name.setText(audioList[index].name)
                    tv_music_singer.setText(audioList[index].author)
                }
                this.audio = audioList[index]
                play(audio)
            }
        }
//        this.audio = audioList[musicId]
//        play(audio)


    }

    override fun onClick(v: View?) {
        when(v!!.id)
        {
            //进行播放/暂停
            R.id.act_audio_player_button_playId->{
                play(audio)
            }
            //上一首
            R.id.act_audio_player_button_prebuttonId->{
                if (musicController != null) {
                    musicController!!.pre()
                    tv_music_name.setText(audio!!.name)
                    tv_music_singer.setText(audio!!.author)
                }
            }
            //下一首
            R.id.act_audio_player_button_nextId->{
                if (musicController != null) {
                    musicController!!.next()
                    tv_music_name.setText(audio!!.name)
                    tv_music_singer.setText(audio!!.author)
                }
            }
        }
    }

    /**
     * 执行播放点击事件
     */
    private fun play(audio: Audio?) {
        if (audio == null) return
        this.audio = audio
        if (audio.fileUrl == null) return
        LogUtils.logD("点击的id = " + audio.id.toString() + " url=" + audio.fileUrl)
        judgeState()
        when (playerState) {
            ACITION_AUDIO_PLAYER_PLAY -> {
                LogUtils.logD("---执行暂停--")
                if (musicController != null) {
                    musicController!!.pause()
                }
            }
            ACITION_AUDIO_PLAYER_PREPARE -> { }
            ACITION_AUDIO_PLAYER_PLAY_COMPLETE->{ }
            ACITION_AUDIO_PLAYER_STOP->{ }
            ACITION_AUDIO_PLAYER_PAUSE -> {
                LogUtils.logD("---执行播放--")
                play()
            }
            AudioFlag.NOT_PLAY_ITEM -> {
                LogUtils.logD("---播放特定的某一首--")
                play()
            }
        }
    }

    /**
     * 播放
     */
    private fun play() {
        if (!connect) {
            initMusicService(true)
            return
        }
        if (musicController != null) {
            musicController!!.play(audio)
        }
    }

    /**
     * 初始化音乐服务
     */
    var needPlay = false
    private fun initMusicService(needPlay: Boolean) {
        this.needPlay = needPlay
        val intent = Intent(this, MusicPlayerService::class.java)
        if (!AppUtil.isServiceRunning(this, MusicPlayerService::class.java.name)) {
            LogUtils.logD( "服务未开启")
            //开启服务
            startService(intent)
        }
        //绑定服务
        bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE)
    }


    /**
     * 判断状态
     */
    private fun judgeState() {
        if (audio == null) return
        playerState = if (musicController != null && musicController!!.currentId === audio!!.id) {
            musicController!!.state
        } else { //不是用以个音频
            AudioFlag.NOT_PLAY_ITEM
        }
        LogUtils.logD( "judgeState：playerState = $playerState")
    }

    /**
     * service绑定交互
     */

    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            connect = true
            if (service == null) return
            musicController = (service as MusicPlayerService.MyBinder).getMusicController()
            LogUtils.logD("musicController=$musicController")
            if (musicController!!.getPlayList() != null)
            {
                musicController!!.getPlayList().clear()
            }
            if (musicController!!.getPlayList() == null || musicController!!.getPlayList().isEmpty()) {
                if (audioList != null) {
                   // LogUtils.logD("MusicByMidBeans"+audioList)
                    musicController!!.setPlayList(audioList)
                }
            }
            musicController!!.setOnProgressChangedListener(progressChangedListener)
            musicController!!.setMediaCallBack(mediaCallBack)
            onPrepare()
           LogUtils.logD("onServiceConnected")
        }

        override fun onServiceDisconnected(name: ComponentName) {
            connect = false
            LogUtils.logD("onServiceDisconnected")
        }
    }

    /**
     * 进度监听
     */
    private val progressChangedListener: OnProgressChangedListener =
        object : OnProgressChangedListener {
            override fun onProgressChanged(track: Int, currentPercentage: Double, position: Long) {
                setCurrentProgress(position)
            }
            override fun onTrackEnd(track: Int) {}
            override fun onExceptionThrown(string: String) {}
        }

    private fun onPrepare() {
        if (musicController != null) {
            speed = musicController!!.temp
        }
        judgeState()
        changePlayUI()
        handler.sendEmptyMessage(MSG_AUTO_PLAY)
    }

    /**
     * 改变按钮状态
     */
    private fun changePlayUI() {
        LogUtils.logD("changePlayUI:playerState=$playerState")
        val isMainThread =
            Thread.currentThread() === Looper.getMainLooper().thread
        if (!isMainThread) {
            runOnUiThread { changePlayUIInternal() }
        } else {
            changePlayUIInternal()
        }
    }

    /**
     * 切换播放按钮和旋转碟盘
     */
    private fun changePlayUIInternal() {
        LogUtils.logD("changePlayUIInternal")
        when (playerState) {
            ACITION_AUDIO_PLAYER_PLAY -> {
                setImg(audio_playImg, R.mipmap.music_state_play)
                if (ratateImage != null) {
                    ratateImage!!.startSpin()
                }
                if (ratateRobotArm != null)
                {
                    ratateRobotArm!!.stopSpin()
                    LogUtils.logD("stopSpin")
                }

            }
            ACITION_AUDIO_PLAYER_PAUSE -> {
                setImg(audio_playImg, R.mipmap.music_state_pause)
                if (ratateImage != null) {
                    ratateImage!!.stopSpin()
                }
                if (ratateRobotArm != null)
                {
                    ratateRobotArm!!.startSpin()
                }
            }
            ACITION_AUDIO_PLAYER_PLAY_COMPLETE -> {
                setImg(audio_playImg, R.mipmap.music_state_pause)
                if (ratateImage != null) {
                    ratateImage!!.stopSpin()
                }
                if (ratateRobotArm != null)
                {
                    ratateRobotArm!!.startSpin()
                }
                //更新进度
                if (skbProgress != null && skbProgress!!.getProgress() != skbProgress!!.getMax()) {
                    skbProgress!!.setProgress(skbProgress!!.getMax())
                }
            }
            else -> {
                if (ratateImage != null) {
                    ratateImage!!.stopSpin()
                }
                if (ratateRobotArm != null)
                {
                    ratateRobotArm!!.startSpin()
                }
                setImg(audio_playImg, R.mipmap.music_state_pause)
                //更新进度
                if (skbProgress != null) {
                    skbProgress!!.setProgress(0)
                }
            }
        }
    }

    /**
     * 切换播放按钮
     */
    private fun setImg(imageView: ImageView?, imgRes: Int) {
        if (imageView == null) return
        imageView.setImageResource(imgRes)
    }

    /**
     * 滑动条监听
     */
    inner class SeekBarChangeEvent : SeekBar.OnSeekBarChangeListener {
        //单位:rank_mark
        var progress: Long = 0
        var total_time: Long = 0
        var fromUser = false

        override fun onProgressChanged(
            seekBar: SeekBar,
            progress: Int,
            fromUser: Boolean) {
            if (musicController != null) {

                total_time = musicController!!.getDuration()
                if (seekBar.max != 0) {
                    this.progress = progress * total_time / seekBar.max
                }
            }
            this.fromUser = fromUser
        }

        override fun onStartTrackingTouch(seekBar: SeekBar) {}
        override fun onStopTrackingTouch(seekBar: SeekBar) {
            if (fromUser) {
               LogUtils.logD("debug", "  fromUser:$fromUser  progress=$progress")
                //rank_mark—>ms
                if (musicController != null) {
                    musicController!!.seekTo(progress)
                }
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        LogUtils.logD( "onDestroy")
        //如果音频正在播放，停止获取播放进度
        if (connect && serviceConnection != null) {
            if (musicController != null) {
                musicController!!.removeCallBack()
            }
            unbindService(serviceConnection)
        }

        unregisterReceiver(receiver)
    }

    override fun onStart() {
        super.onStart()
        //初始化当前时间
        var date: Date = Date(System.currentTimeMillis())
        var time = DateUtils.getTime(date)
        var dates = DateUtils.getDate(date)
        var week = DateUtils.getWeekOfDate(date)
        tv_main_time.text = time
        tv_main_week.text = dates +" "+ week
        //动态注册广播
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(receiver, filter)
    }

    /**
     * 时间广播更新
     */
    inner class broadCastRecever : BroadcastReceiver() {
        //广播接收器
        override fun onReceive(context: Context?, intent: Intent?) {//接收广播后执行的操作
            var action: String? = intent!!.getAction()
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //获取当前时间
                var date: Date = Date(System.currentTimeMillis())
                var time = DateUtils.getTime(date)
                var dates = DateUtils.getDate(date)
                var week = DateUtils.getWeekOfDate(date)
                tv_main_time.text = time
                tv_main_week.text = dates + " " +week
            }
        }
    }
}