package com.yidianling.course.coursePlay.presenter

import android.content.Intent
import android.text.TextUtils
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.ydlcommon.data.http.BaseResponse
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.mvp.base.BasePresenter
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.router.YdlCommonRouterManager
import com.ydl.ydlcommon.utils.extend.ifNotNull
import com.ydl.ydlnet.client.observer.CommonObserver
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.bean.COURSE_AUDIO
import com.yidianling.course.bean.CourseConsultant
import com.yidianling.course.bean.CourseMediaBean
import com.yidianling.course.bean.CourseMediaDetailBean
import com.yidianling.course.coursePlay.model.AudioPlayModelImpl
import com.yidianling.user.api.service.IUserService
import org.json.JSONException
import org.json.JSONObject
import java.util.*

class AudioPlayPresenter : BasePresenter<IAudioPlayContract.View, IAudioPlayContract.Model>(),
    IAudioPlayContract.Presenter {

    private val ROUTER_PARAMS = "routerParam"

    private var mFrom: Int = 0
    private var mPlayUrl: String? = null // 外部选中要播放的音频文件地址
    private var mCourPlayBean: CourseMediaDetailBean? = null
    private val mPlayList: ArrayList<CourseMediaBean> = ArrayList() // 播放列表
    private var mCurrentPosition = 0
    private var mCourseId = 0 // 课程id

    override fun createModel(): IAudioPlayContract.Model = AudioPlayModelImpl()

    override fun getParams(intent: Intent) {
        if (intent.hasExtra(ROUTER_PARAMS)) {
            //路由传递的入参
            val json = intent.getStringExtra(ROUTER_PARAMS)
            try {
                val jsonObject = JSONObject(json)
                //课程ID
                mCourseId = jsonObject.getInt(IYDLRouterConstant.EXTRA_ID)
            } catch (e: JSONException) {
                e.printStackTrace()
            }
            return
        }
        //正常跳转所传参数
        mCourseId = intent.getIntExtra("course_id", 0)
        mPlayUrl = intent.getStringExtra("coursePlayUrl")
        val isFromFloatView = intent.getBooleanExtra("isFromFloatView", false)
        mView.setNonWifiTips(!isFromFloatView)
        mFrom = intent.getIntExtra("from", 0)
        if (mCourseId == 0) {
            ToastUtil.toastShort("参数错误")
            mView.close()
        }
    }

    override fun getNewIntent(intent: Intent) {
        val courseId = intent.getIntExtra("course_id", 0)
        if (0 == courseId) {
            ToastUtil.toastShort("参数错误")
            mView.close()
        } else if (courseId != mCourseId) {
            mCourseId = courseId
            getCoursePlayData()
        }
    }

    override fun getCoursePlayData() {
        mView.showProgressDialog()
        mModel.getCoursePlayData(mCourseId)
            .compose(RxUtils.applySchedulers(mView))
            .subscribe(object : CommonObserver<BaseResponse<CourseMediaDetailBean>>() {
                override fun onError(s: String?) {
                    mView.dismissProgressDialog()
                }

                override fun onSuccess(resp: BaseResponse<CourseMediaDetailBean>?) {
                    mView.dismissProgressDialog()
                    resp?.let { response ->
                        if (response.code == 200) {
                            response.data?.let { bean ->
                                mCourPlayBean = bean
                                setPlayList(bean)
                                if (!mPlayUrl.isNullOrEmpty()) {
                                    val position = mPlayList.indexOfFirst {
                                        mPlayUrl == it.url
                                    }
                                    mCurrentPosition = if (-1 == position) 0 else position
                                }
                                mView.updateView(bean.courseExtra, mFrom)
                            } ?: let {
                                ToastUtil.toastShort("解析出错")
                            }
                        } else {
                            ToastUtil.toastShort(response.msg)
                        }
                    }
                }

            })
    }

    override fun getConsultantInfo() {
        mModel.getConsultantInfo(mCourseId)
            .compose(RxUtils.applySchedulers(mView))
            .subscribe(object : CommonObserver<BaseResponse<CourseConsultant>>() {
                override fun onError(s: String?) {}

                override fun onSuccess(resp: BaseResponse<CourseConsultant>?) {
                    resp?.let { response ->
                        if (response.code == 200) {
                            response.data?.let { info ->
                                if (1 == info.isOnline) {
                                    mView.goToConsultantInfo(info.doctorHead)
                                } else {
                                    ToastUtil.toastShort("该咨询师未上线")
                                }
                            } ?: let {
                                ToastUtil.toastShort("解析出错")
                            }
                        } else {
                            ToastUtil.toastShort(response.msg)
                        }
                    }
                }

            })
    }

    //设置播放列表数据
    private fun setPlayList(bean: CourseMediaDetailBean) {
        mPlayList.clear()
        if (bean.voiceSample.courseMedia.isNotEmpty()) {
            for (voiceSampleData in bean.voiceSample.courseMedia) {
                voiceSampleData.isDemo = true
                mPlayList.add(voiceSampleData)
            }
        }
        if (bean.voiceWhole.courseMedia.isNotEmpty()) {
            for (voiceCourseData in bean.voiceWhole.courseMedia) {
                mPlayList.add(voiceCourseData)
            }
        }
    }

    override fun convertToMusics(): ArrayList<Music> {
        val musics = ArrayList<Music>()
        mCourPlayBean?.courseExtra?.let { extra ->
            mPlayList.forEach { bean ->
                musics.add(Music().apply {
                    path = bean.url
                    coverPath = extra.pic
                    title = bean.title
                    artist = bean.doctorName
                    canPlay = extra.isBuy || bean.isDemo
                })
            }
        }
        return musics
    }

    override fun addCourseOrder() {
        if (mCourseId == 0) {
            ToastUtil.toastShort("请退出页面重试")
            return
        }
        val userInfo = findRouteService(IUserService::class.java).getUserInfo()
        if (userInfo == null || TextUtils.isEmpty(userInfo.uid)) {
            mView.loginByOneKeyLogin()
            return
        }
        mView.commonPayDialog(userInfo, mCourseId.toString())
    }

    override fun getPlayPosition(): Int = mCurrentPosition
    override fun getPlayList(): List<CourseMediaBean> = mPlayList

    override fun togglePlay(playPosition: Int) {
        if (isCanLoad(playPosition)) {
            mView.load()
        }
    }

    override fun isCanLoad(playPosition: Int): Boolean {
        ifNotNull(
            mCourPlayBean?.courseExtra,
            mPlayList.elementAtOrNull(playPosition)
        ) { extra, bean ->
            if (!bean.isDemo && !extra.isBuy) {
                if (mView.audioIsPlaying()) mView.audioPausePlay()
                mView.buyCourseTipDialog()
            } else {
                mCurrentPosition = playPosition
                mView.setTitle(bean.title)
                return true
            }
        }
        return false
    }

    override fun share() {
        mView.shareDialog(mCourPlayBean?.courseExtra?.shareData)
    }

    override fun showFloatView() {
        if (mView.audioIsPlaying() && PlayerFloatHelper.playingType == PlayTypeEnum.PLAY_TYPE_COURSE) {
            PlayerFloatHelper.playTempData.clear()
            val hashMap = hashMapOf<String, String>()
            hashMap["course_id"] = mCourseId.toString()
            hashMap["media_type"] = COURSE_AUDIO.toString()
            PlayerFloatHelper.playTempData.putAll(hashMap)
        }
    }

}