package com.yidianling.course.coursePlay

import android.content.Intent
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.ViewTarget
import com.bumptech.glide.request.transition.Transition
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayerFloatHelper
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.bean.ShareData
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.router.YdlUserInfo
import com.ydl.ydlcommon.utils.statusBar.StatusBarUtil
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.ydl.ydlcommon.view.dialog.YDLShareDialog
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.course.BuildConfig
import com.yidianling.course.CourseConstants
import com.yidianling.course.R
import com.yidianling.course.bean.CourseExtraBean
import com.yidianling.course.coursePlay.presenter.AudioPlayPresenter
import com.yidianling.course.coursePlay.presenter.IAudioPlayContract
import com.yidianling.course.router.CourseIn
import com.yidianling.course.widget.CourseListDialog
import com.yidianling.course.widget.CourseSpeedDialog
import com.yidianling.ydl_pay.common.CommonPayDialog
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.android.synthetic.main.activity_audio_play.*
import java.util.*


/**
 * 课程音频播放
 */
@Route(path = "/course/audioPlay")
class AudioPlayActivity : BaseMvpActivity<IAudioPlayContract.View, IAudioPlayContract.Presenter>(),
    IAudioPlayContract.View {

    private var mCourseSpeedDialog: CourseSpeedDialog? = null
    private var mCourseListDialog: CourseListDialog? = null

    override fun turnOnImmersiveStatusBar(): Boolean = true

    override fun createPresenter(): IAudioPlayContract.Presenter = AudioPlayPresenter()

    override fun layoutResId(): Int = R.layout.activity_audio_play

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            mPresenter.getNewIntent(it)
        }
    }

    override fun initDataAndEvent() {
        intent?.let {
            initView()
            mPresenter.run {
                getParams(it)
                getCoursePlayData()
            }
        }
    }

    private fun initView() {
        iv_back.run {
            (layoutParams as? ViewGroup.MarginLayoutParams)?.topMargin = StatusBarUtil.getStatusBarHeight(this@AudioPlayActivity)
            setOnClickListener {
                onBackPressed()
            }
        }
        iv_share.setOnClickListener {
            mPresenter.share()
        }
        audio_play.mListener = { playPosition ->
            mPresenter.isCanLoad(playPosition)
        }
    }

    override fun loginByOneKeyLogin() {
        CourseIn.loginByOneKeyLogin(mContext, true)
    }

    override fun goToConsultantInfo(url: String) {
        mPresenter.showFloatView()
        NewH5Activity.start(this, H5Params(url, ""))
    }

    override fun commonPayDialog(userInfo: YdlUserInfo, courseId: String) {
        CommonPayDialog.Build(mContext)
            .setCourseId(courseId)
            .setToken(userInfo.token)
            .setUid(userInfo.userId)
            .setFfrom(PlatformDataManager.getRam().getChannelName())
            .setListener(object : CommonPayDialog.OnPayResultListener {
                override fun onSuccesed() {
                    mPresenter.getCoursePlayData()
                }

                override fun onFailed() {

                }
            })
            .setIsTestEnvironment(BuildConfig.DEBUG).build().show()
    }

    override fun setTitle(title: String) {
        tv_title.text = title
    }

    override fun load() {
        audio_play.load(mPresenter.getPlayPosition())
    }

    override fun buyCourseTipDialog() {
        CommonDialog(this)
            .setMessage("\n购买课程，获取完整课程内容\n")
            .setLeftOnclick("放弃") {}
            .setRightClick("购买") {
                mPresenter.addCourseOrder() // 跳转支付页
            }
            .setCancelAble(false)
            .show()
    }

    override fun onBackPressed() {
        mPresenter.showFloatView()
        super.onBackPressed()
    }

    override fun shareDialog(share: ShareData?) {
        share?.let {
            YDLShareDialog.style1(
                this,
                share.title,
                share.share_url,
                share.desc,
                share.cover,
                "",
                ""
            ).apply {
                setCallBack(object : YDLShareDialog.ICallBack {
                    override fun callBack(type: Int) {
                        if (1 == type) {
                            ModularServiceManager.getPlatformUserService()

                            if (CourseIn.loginByOneKeyLogin(this@AudioPlayActivity, true)) {
                                //分享到心事动态
                                val url =
                                    if (TextUtils.isEmpty(share.url)) share.share_url else share.url
                                CourseIn.getDynamicService()
                                    .publishArticleToTrend(
                                        this@AudioPlayActivity,
                                        url!!,
                                        share.cover!!,
                                        share.title!!
                                    )
                            }
                        }
                    }
                })
            }.show(fragmentManager, "lose")
        } ?: let {
            ToastUtil.toastShort("缺少参数")
        }
    }

    override fun updateView(bean: CourseExtraBean, from: Int) {
        bean.let {
            Glide.with(this)
                .load(it.pic)
                .transition(DrawableTransitionOptions.withCrossFade())
                .apply(RequestOptions.bitmapTransform(BlurTransformation(10, 16)))
                .into(object : ViewTarget<ConstraintLayout, Drawable>(cl_bg) {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        view.background = resource
                    }
                })
            Glide.with(this)
                .load(it.pic)
                .transition(DrawableTransitionOptions.withCrossFade())
                .apply(RequestOptions.bitmapTransform(RoundedCorners(RxImageTool.dp2px(8f))))
                .into(iv_pic)
            Glide.with(this).load(it.doctorHead).error(R.drawable.course_head_place_hold_pic)
                .into(iv_icon)
            tv_title.text = mPresenter.getPlayList().elementAtOrNull(mPresenter.getPlayPosition())?.title.orEmpty()
            tv_name.text = it.doctorName
            iv_icon.setOnClickListener { consultantClick() }
            tv_name.setOnClickListener { consultantClick() }
            tv_detail.setOnClickListener { _ -> detailClick(it) }
            iv_detail.setOnClickListener { _ -> detailClick(it) }
            tv_speed.setOnClickListener { speedClick() }
            iv_speed.setOnClickListener { speedClick() }
            tv_list.setOnClickListener { _ -> listClick(it) }
            iv_list.setOnClickListener { _ -> listClick(it) }
            audio_play.setData(mPresenter.getPlayPosition(), mPresenter.convertToMusics(), from)
        }
    }

    override fun setNonWifiTips(show: Boolean) {
        audio_play.mNonWifiTips = show
    }

    override fun audioIsPlaying(): Boolean = audio_play.isPlaying()

    override fun audioPausePlay() = audio_play.pausePlay()

    override fun getAudioMusic(): Music? = audio_play.getAudioMusic()

    override fun close() = finish()

    private fun detailClick(extra: CourseExtraBean) {
        if (TextUtils.isEmpty(extra.id)) {
            ToastUtil.toastShort("课程id错误")
        } else {
            mPresenter.showFloatView()
            NewH5Activity.start(
                this,
                H5Params(CourseConstants.COURSE_DETAIL_H5 + extra.id, null)
            ) // 跳转课程H5详情
        }
    }

    private fun speedClick() {
        val audioPlay = audio_play
        showFragment(mCourseSpeedDialog ?: CourseSpeedDialog().apply {
            mCourseSpeedDialog = this
            mListener = { speed ->
                audioPlay.setSpeed(speed)
            }
        }, "courseSpeed")
    }

    private fun listClick(extra: CourseExtraBean) {
        extra.let {
            showFragment(mCourseListDialog?.also {
                it.setCurrentPosition(mPresenter.getPlayPosition())
            } ?: CourseListDialog().also { dialog ->
                mCourseListDialog = dialog
                dialog.setData(it.isBuy, mPresenter.getPlayPosition(), mPresenter.getPlayList())
                dialog.mView = this
                dialog.mPresenter = mPresenter
            }, "courseList")
        }
    }

    private fun consultantClick() {
        mPresenter.getConsultantInfo()
    }

    override fun onResume() {
        super.onResume()
        if (PlayerFloatHelper.isShow()) {
            PlayerFloatHelper.removeView()
        }
    }

    override fun onDestroy() {
        audio_play.onDestroy()
        super.onDestroy()
    }
}