package com.yidianling.course.coursePlay

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
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.media.view.PlayerFloatView
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.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.AudioPlayView
import com.yidianling.course.widget.CourseListDialog
import com.yidianling.course.widget.CourseSpeedDialog
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.ydl_pay.common.CommonPayDialog
import jp.wasabeef.glide.transformations.BlurTransformation


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

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

    private lateinit var iv_back: ImageView
    private lateinit var iv_share: ImageView
    private lateinit var iv_pic: ImageView
    private lateinit var iv_icon: ImageView
    private lateinit var iv_detail: ImageView
    private lateinit var iv_speed: ImageView
    private lateinit var iv_list: ImageView
    private lateinit var audio_play: AudioPlayView
    private lateinit var tv_title: TextView
    private lateinit var tv_name: TextView
    private lateinit var tv_detail: TextView
    private lateinit var tv_speed: TextView
    private lateinit var tv_list: TextView
    private lateinit var cl_bg: ConstraintLayout

    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 findView() {
        iv_back = findViewById(R.id.iv_back)
        iv_share = findViewById(R.id.iv_share)
        audio_play = findViewById(R.id.audio_play)
        tv_title = findViewById(R.id.tv_title)
        tv_name = findViewById(R.id.tv_name)
        iv_pic = findViewById(R.id.iv_pic)
        iv_icon = findViewById(R.id.iv_icon)
        cl_bg = findViewById(R.id.cl_bg)
        tv_detail = findViewById(R.id.tv_detail)
        tv_speed = findViewById(R.id.tv_speed)
        tv_list = findViewById(R.id.tv_list)
        iv_detail = findViewById(R.id.iv_detail)
        iv_speed = findViewById(R.id.iv_speed)
        iv_list = findViewById(R.id.iv_list)
    }

    private fun initView() {
        findView()
        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: UserResponseBean.UserInfo, courseId: String) {
        CommonPayDialog.Build(mContext)
            .setCourseId(courseId)
            .setToken(userInfo.accessToken.orEmpty())
            .setUid(userInfo.uid)
            .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) {
                            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("缺少参数")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun updateView(bean: CourseExtraBean, from: Int) {
        Glide.with(this)
            .load(bean.pic)
            .transition(DrawableTransitionOptions.withCrossFade())
            .apply(RequestOptions.bitmapTransform(BlurTransformation(5, 20)))
            .into(object : ViewTarget<ConstraintLayout, Drawable>(cl_bg) {
                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    view.background = resource
                }
            })
        Glide.with(this)
            .load(bean.pic)
            .transition(DrawableTransitionOptions.withCrossFade())
            .apply(RequestOptions.bitmapTransform(RoundedCorners(RxImageTool.dp2px(8f))))
            .into(iv_pic)
        Glide.with(this).load(bean.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 = bean.doctorName
        iv_icon.setOnClickListener { consultantClick() }
        tv_name.setOnClickListener { consultantClick() }
        tv_detail.setOnClickListener { _ -> detailClick(bean) }
        iv_detail.setOnClickListener { _ -> detailClick(bean) }
        tv_speed.setOnClickListener { speedClick() }
        iv_speed.setOnClickListener { speedClick() }
        tv_list.setOnClickListener { _ -> listClick(bean) }
        iv_list.setOnClickListener { _ -> listClick(bean) }
        tv_speed.text = "${audio_play.getSpeed()}X"
        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详情
        }
    }

    @SuppressLint("SetTextI18n")
    private fun speedClick() {
        showFragment(mCourseSpeedDialog ?: CourseSpeedDialog().also { dialog ->
            mCourseSpeedDialog = dialog
            dialog.setSpeedPosition(audio_play.getSpeed())
            dialog.mListener = { speed ->
                tv_speed.text = "${speed}X"
                audio_play.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 onStop() {
        PlayerFloatHelper.addClickListener(this)
        super.onStop()
    }

    override fun onDestroy() {
        PlayerFloatHelper.removeClickListener(this)
        super.onDestroy()
    }

    override fun onPreClose(): Boolean {
        audio_play.pausePlay()
        PlayerFloatHelper.removeView()
        return false
    }

}