package com.baijiayun.live.ui.pptpanel

import android.animation.ValueAnimator
import android.graphics.Color
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.baijiayun.bjyutils.drawable.DrawableBuilder
import com.baijiayun.bjyutils.kt.convertLikeCount
import com.baijiayun.bjyutils.kt.dp
import com.baijiayun.bjyutils.kt.removeViewFromParent
import com.baijiayun.bjyutils.log.LPLogger
import com.baijiayun.bjyutils.reactivex.RxUtils
import com.baijiayun.bjyutils.screen.DisplayUtils
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.chat.FloatingChatFullScreenAdapter
import com.baijiayun.live.ui.databinding.BjyLayoutPptMenuBinding
import com.baijiayun.livebase.context.LPConstants
import com.baijiayun.livebase.utils.ThemeDataUtil
import com.baijiayun.livecore.listener.OnPhoneRollCallListener
import com.baijiayun.livecore.models.LPAnswerModel
import com.baijiayun.livecore.models.LPBJTimerModel
import com.baijiayun.livecore.ppt.PPTView
import com.baijiayun.liveuibase.handsuplist.HandsUpListFragment
import com.baijiayun.liveuibase.liveshow.like.LikeUI
import com.baijiayun.liveuibase.ppt.BasePPTFragment
import com.baijiayun.liveuibase.ppt.PadPPTView
import com.baijiayun.liveuibase.speaklist.BaseSwitchItem
import com.baijiayun.liveuibase.speaklist.SpeakItemType
import com.baijiayun.liveuibase.speaklist.Switchable
import com.baijiayun.liveuibase.speaklist.SwitchableStatus
import com.baijiayun.liveuibase.speaklist.SwitchableType
import com.baijiayun.liveuibase.speaklist.item.LocalItem
import com.baijiayun.liveuibase.toolbox.ToolboxWindow
import com.baijiayun.liveuibase.toolbox.bonuspoints.BonusPointsPopupWindow
import com.baijiayun.liveuibase.utils.disposeUntilDestroy
import com.baijiayun.liveuibase.utils.enableRollCall
import com.baijiayun.liveuibase.utils.isAdmin
import com.baijiayun.liveuibase.utils.removeSwitchableFromParent
import com.baijiayun.liveuibase.widgets.dialog.CDNSwitchDialog
import com.baijiayun.liveuibase.widgets.dialog.showClassSwitchDialog
import com.baijiayun.liveuibase.widgets.toolbar.ShapeChangeData
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.bonus_points_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.floating_recycler
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.floating_tv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.heart_layout
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.like_count_tv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.like_menu_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.menu_expand_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.shop_menu_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.switch_cdn_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.tvCountDown
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.tvSpeakApply
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.bonus_points_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciClearAll
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciGraph
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciLaser
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciMark
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciPen
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciPenClear
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciSelect
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ciWord
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.double_teacher_class_change_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivAsCameraStatus
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivEyeCare
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivFullScreen
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivHandsUpImg
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivNotice
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivOperatePPT
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivPPTAuth
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivQa
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivStudentHomeworkEntry
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.ivToolBox
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.left_container
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.llPenMenu
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.media_container
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.menu_expand_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.qaContainer
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.right_container
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.rlSpeakWrapper
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.switch_cdn_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvAudio
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvCountDown
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvHandsUpCount
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvPPTFiles
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvQaTip
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvSpeakApply
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.tvVideo
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.video_menu_iv
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.view_roll_call_going
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.writingboard_ble_container
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.writingboard_ble_icon
import kotlinx.android.synthetic.main.bjy_layout_ppt_menu.view.writingboard_ble_progress
import kotlinx.android.synthetic.main.fragment_pad_ppt.menuContainer
import kotlinx.android.synthetic.main.fragment_pad_ppt.pptContainer
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.TimeUnit


/**
 * Created by Shubo on 2019-10-10.
 *
 */
class PPTFragment : BasePPTFragment() {
    private val handsUpListFragment by lazy {
        HandsUpListFragment.newInstance()
    }

    private val toolboxWindow by lazy {
        val toolboxWindow = ToolboxWindow(contextReference)
        toolboxWindow.setClickListener(object : ToolboxWindow.OnClickListener {
            override fun isClickable(): Boolean = checkClassStart()

            override fun onBrowserClick() {
                routerViewModel.actionOpenBrowser.value = Unit
            }

            override fun onSmallBlackboardClick() {
            }

            override fun onTimerClick() {
                routerViewModel.showTimer.value = true to LPBJTimerModel()
            }

            override fun onAnswererClick() {
                routerViewModel.answerStart.value = LPAnswerModel()
            }

            override fun onRedPacketClick() {
                routerViewModel.redPacketPublish.value = Unit
            }

            override fun onRollCallClick() {
                routerViewModel.showRollCall.value = -1 to null
            }

            override fun onResponderClick() {
                routerViewModel.showResponder.value = true
            }

            override fun onScreenShareClick() {
                if (routerViewModel.broadcastStatus.value == true) {
                    showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                    return
                }
                routerViewModel.startScreenShare.value = Unit
            }

            override fun onTurntableClick() {
                // do nothing
            }
        })
        toolboxWindow.setOnDismissListener {
            pptMenuLayout.ivToolBox.isChecked = false
            pptMenuLayout.ivToolBox.background = if (pptMenuLayout.ivToolBox.isChecked) {
                ContextCompat.getDrawable(contextReference, R.drawable.live_tool_bar_check_layer_bg)
            } else null
        }
        toolboxWindow
    }

    private val floatingChatFullScreenAdapter by lazy {
        FloatingChatFullScreenAdapter(
            contextReference,
            pptViewModel.liveRoom
        )
    }

    private var hiddenSwitchableInFullScreenMode: View? = null
    private var likeUI: LikeUI? = null

    private val switch2FullScreenObserver by lazy {
        Observer<Pair<Boolean, Switchable?>> {
            it?.let {
                pptMenuLayout.apply {
                    ivQa.visibility = if (enableQaBtn()) View.VISIBLE else View.GONE
                    qaContainer.visibility = if (enableQaBtn()) View.VISIBLE else View.GONE
                    ivStudentHomeworkEntry.visibility =
                        if (enableStudentHomework()) View.VISIBLE else View.GONE
                    updateAVButtonVisibility()
                    ivFullScreen.isSelected = isFullScreen()
                    ivEyeCare.visibility = View.VISIBLE
                    reLayoutPPTMenu(it.first)
                    pptMenuLayout.ivAsCameraStatus?.visibility =
                        if (isShowAsCamera(it)) View.VISIBLE else View.GONE
                    video_menu_iv.visibility = if (enableVideoMenuBtn()) View.VISIBLE else View.GONE
                }
                resetSVGA()
                updateToolbarVisible()
                updateFloatChatVisible()
                // 切到全屏（替换container的view，退回时需要考虑还原问题）
                if (it.first) {
                    pptContainer.getChildAt(0)?.let {
                        it.visibility = View.GONE
                        hiddenSwitchableInFullScreenMode = it
                    }
                    it.second?.run {
                        removeSwitchableFromParent(this)
                        pptContainer.addView(
                            view,
                            FrameLayout.LayoutParams.MATCH_PARENT,
                            FrameLayout.LayoutParams.MATCH_PARENT
                        )
                    }
                    val linearLayoutManager = LinearLayoutManager(context)
                    linearLayoutManager.stackFromEnd = true
                    floating_recycler.layoutManager = linearLayoutManager
                    floating_recycler.adapter = floatingChatFullScreenAdapter
                    if (isLiveWallAndEnableFullScreen()) {
                        floatingChatFullScreenAdapter.subscribe()
                    }
                    floating_tv.setOnClickListener {
                        routerViewModel.actionShowSendMessageFragment.value = ""
                    }
                } else {
                    if (isLiveWallAndEnableFullScreen()) {
                        floatingChatFullScreenAdapter.unSubscribe()
                    }
                    hiddenSwitchableInFullScreenMode?.let {
                        it.visibility = View.VISIBLE
                    }
                }
                checkWarmingUpVideoPlaying()
            }
        }
    }


    /**
     * 切换容器会触发 onDetachedFromWindow
     * 设置 clearsAfterDetached 后 imageView 的 drawable 会被清空
     */
    private fun resetSVGA() {
        // new URL needs try catch.
        try {
            // 先设置图片避免后续加载图片出现闪动现象
            like_menu_iv.setImageResource(R.drawable.bjy_base_ic_like)
            shop_menu_iv.setImageResource(R.drawable.bjy_base_ic_shop)
            val svgaParser = SVGAParser.shareParser()
            svgaParser.decodeFromURL(
                URL(LIKE_URL),
                object : SVGAParser.ParseCompletion {
                    override fun onComplete(videoItem: SVGAVideoEntity) {
                        like_menu_iv.setVideoItem(videoItem)
                        like_menu_iv.startAnimation()
                    }

                    override fun onError() {
                        like_menu_iv.setImageResource(R.drawable.bjy_base_ic_like)
                    }
                }, null
            )
            svgaParser.decodeFromURL(
                URL(SHOP_URL),
                object : SVGAParser.ParseCompletion {
                    override fun onComplete(videoItem: SVGAVideoEntity) {
                        shop_menu_iv.setVideoItem(videoItem)
                        shop_menu_iv.startAnimation()
                    }

                    override fun onError() {
                        shop_menu_iv.setImageResource(R.drawable.bjy_base_ic_shop)
                    }
                }, null
            )
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        }
    }

    private val switch2MaxScreenObserver by lazy {
        Observer<Switchable?> {
            it?.let {
                removeSwitchableFromParent(it)
                val pptContainerLayoutParams: ConstraintLayout.LayoutParams = pptContainer.layoutParams as ConstraintLayout.LayoutParams
                if (routerViewModel.liveRoom.partnerConfig.enableSynchronizePPTStatus && it is PadPPTView) {
                    pptContainerLayoutParams.dimensionRatio = "4:3"
                } else {
                    pptContainerLayoutParams.dimensionRatio = null
                }
                val layoutParams = if (it is PadPPTView) {
                    FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.WRAP_CONTENT,
                        FrameLayout.LayoutParams.WRAP_CONTENT
                    )
                } else {
                    FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT
                    )
                }
                layoutParams.gravity = Gravity.CENTER
                LPLogger.d(TAG,"addView pptContainer, id:${it.identity}--type:${it.switchableType}")
                pptContainer.addView(it.view, layoutParams)
                if (it.switchableType == SwitchableType.MainItem) {
                    routerViewModel.mainVideoItem = it
                }
                pptMenuLayout.ivAsCameraStatus?.visibility =
                    if (it is LocalItem && routerViewModel.liveRoom.speakQueueVM.enableAttachPhoneCamera()) View.VISIBLE else View.GONE
                pptMenuLayout.ivOperatePPT?.visibility =
                    if (enableOperateH5PPT()) View.VISIBLE else View.GONE
                // 这时是切到max status没变，见switchToMaxScreen实现,用showPPTMenu()不准
                if (it.itemType == SpeakItemType.PPT && pptViewModel.isEnableDrawing()) {
                    brushDragLayout.visibility = View.VISIBLE
                } else {
                    brushDragLayout.visibility = View.GONE
                }
                if (it.itemType != SpeakItemType.PPT) {
                    clearLastCheckDrawItem()
                    pptViewModel.changeDrawingStatus(ShapeChangeData(LPConstants.PPTEditMode.Normal))
                    pptMenuLayout.video_menu_iv?.visibility =
                        if (enableVideoMenuBtn()) View.VISIBLE else View.GONE
                } else {
                    pptMenuLayout.video_menu_iv?.visibility = View.GONE
                }
                checkWarmingUpVideoPlaying()
            }
        }
    }

    private val leftContainerWidth by lazy {
        pptMenuLayout.left_container.measuredWidth
    }

    private var isMenuExpand = true
    private var menuDataBinding: BjyLayoutPptMenuBinding? = null
    private var eyeCareIsEnable: Boolean = false
    private var disposableOfBonusPointsTimer: Disposable? = null
    private var bonusPointPopupWindow: BonusPointsPopupWindow? = null
    private var cdnSwitchDialog: CDNSwitchDialog? = null
    private var menuAnim: ValueAnimator? = null

    override fun init(view: View) {
        pptView = routerViewModel.ppt
    }

    override fun initView() {
        pptMenuLayout = LayoutInflater.from(context).inflate(R.layout.bjy_layout_ppt_menu, null)
        if (routerViewModel.liveRoom.isAudition) {
            pptMenuLayout.visibility = View.GONE
        }
        brushDragLayout = pptMenuLayout.llPenMenu
        menuDataBinding = DataBindingUtil.bind(pptMenuLayout)
        menuDataBinding?.let {
            it.pptviewmodel = this.pptViewModel
            it.lifecycleOwner = this@PPTFragment
        }
        eraserCheckImageView = brushDragLayout.ciPenClear
        doodleBrushCheckImageView = brushDragLayout.ciPen
        markBrushCheckImageView = brushDragLayout.ciMark
        graphBrushCheckImageView = brushDragLayout.ciGraph
        selectBrushCheckImageView = brushDragLayout.ciSelect
        wordBrushCheckImageView = brushDragLayout.ciWord
        laserBrushCheckImageView = brushDragLayout.ciLaser
        eraserAllImageView = brushDragLayout.ciClearAll

        initBrushMenu()
        pptMenuLayout.run {
            view_roll_call_going.background = DrawableBuilder()
                .solidColor(
                    ThemeDataUtil.getColorFromThemeConfigByAttrId(
                        context,
                        R.attr.base_theme_live_product_color
                    )
                )
                .oval()
                .build()
            //学生没有同意举手的按钮,把音视频按钮放举手左边
            if (!pptViewModel.isTeacherOrAssistant() && media_container.layoutParams is ConstraintLayout.LayoutParams) {
                val layoutParams = media_container.layoutParams as ConstraintLayout.LayoutParams
                layoutParams.endToStart = R.id.rlSpeakWrapper
            }
            updateAVButtonVisibility()
            with(ivFullScreen) {
                visibility = View.VISIBLE
                isSelected = isFullScreen()
                setOnClickListener {
                    if (isFullScreen()) {
                        routerViewModel.switch2FullScreen.value?.second?.run {
                            switchToFullScreen(false)
                        }
                    } else {
                        routerViewModel.switch2MaxScreen.value?.run {
                            switchToFullScreen(true)
                        }
                    }
                }
            }
            //工具箱
            ivToolBox.setOnClickListener {
                changePopupWindowState(toolboxWindow, ivToolBox)
                ivToolBox.isChecked = true
                ivToolBox.background = if (ivToolBox.isChecked) {
                    ContextCompat.getDrawable(
                        contextReference,
                        R.drawable.live_tool_bar_check_layer_bg
                    )
                } else null
            }
            ivHandsUpImg.setOnClickListener {
                showDialogFragment(handsUpListFragment)
                pptViewModel.hasRead.value = true
            }

            tvPPTFiles.setOnClickListener {
                if (routerViewModel.broadcastStatus.value == true) {
                    showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                    return@setOnClickListener
                }
                routerViewModel.actionShowPPTManager.value = true
            }
            ivNotice.setOnClickListener {
                routerViewModel.actionShowAnnouncementFragment.value = true
            }
            double_teacher_class_change_iv.visibility =
                if (routerViewModel.liveRoom.enableSwitchClass()) View.VISIBLE else View.GONE
            double_teacher_class_change_iv.isSelected = routerViewModel.liveRoom.isParentRoom

            qaContainer.visibility = if (enableQaBtn()) View.VISIBLE else View.GONE
            ivQa.visibility = if (enableQaBtn()) View.VISIBLE else View.GONE
            ivQa.setOnClickListener {
                routerViewModel.actionShowQAInteractiveFragment.value = Unit
                routerViewModel.hasNewQa.value = false
            }
            if (routerViewModel.isShowEyeCare.value != null) {
                eyeCareIsEnable = routerViewModel.isShowEyeCare.value!!
            }
            ivEyeCare.setImageDrawable(
                ContextCompat.getDrawable(
                    context, if (eyeCareIsEnable) {
                        R.drawable.icon_eye_care_checked
                    } else R.drawable.icon_eye_care_normal
                )
            )
            ivEyeCare.setOnClickListener {
                eyeCareIsEnable = !eyeCareIsEnable
                routerViewModel.isShowEyeCare.value = eyeCareIsEnable
                ivEyeCare.setImageDrawable(
                    ContextCompat.getDrawable(
                        context,
                        if (eyeCareIsEnable) R.drawable.icon_eye_care_checked
                        else R.drawable.icon_eye_care_normal
                    )
                )
            }
            ivStudentHomeworkEntry.visibility =
                if (enableStudentHomework()) View.VISIBLE else View.GONE
            ivStudentHomeworkEntry.setOnClickListener {
                routerViewModel.actionShowPPTManager.value = true
            }
            ivNotice.visibility = if (enableNoticeBtn()) View.VISIBLE else View.GONE
            ivOperatePPT.visibility = if (enableOperateH5PPT()) View.VISIBLE else View.GONE
            ivAsCameraStatus.visibility = if (enableAsCamera()) View.VISIBLE else View.GONE
            writingboard_ble_container.visibility =
                if (enableWritingBoard()) View.VISIBLE else View.GONE
            //学生隐藏操作摄像头按钮
            if (liveHideStudentCamera()) {
                tvVideo.visibility = View.GONE
            }
            // 初始化的时候不用speakQueueVM.isMixModeOn(时机不对，isMixModeOn还未赋值)
            // 使用speakQueueVM.isSupportMixStreaming
            switch_cdn_iv.visibility = if (routerViewModel.liveRoom.player.cdnCountOfMixStream > 1
                && routerViewModel.liveRoom.speakQueueVM.isSupportMixStreaming
                && !routerViewModel.liveRoom.isTeacher
            ) {
                View.VISIBLE
            } else View.GONE
            switch_cdn_iv.setOnClickListener {
                if (cdnSwitchDialog == null) {
                    cdnSwitchDialog = CDNSwitchDialog()
                    cdnSwitchDialog!!.itemClickListener =
                        object : CDNSwitchDialog.ItemClickListener {
                            override fun onClick(index: Int) {
                                val switchSuccess =
                                    routerViewModel.liveRoom.player.switchCDNOfMixStream(index)
                                showToastMessage(
                                    getString(
                                        if (switchSuccess) R.string.bjy_live_cdn_switch_success
                                        else R.string.bjy_live_cdn_switch_fail
                                    )
                                )
                            }
                        }
                }
                cdnSwitchDialog?.let {
                    it.count = routerViewModel.liveRoom.player.cdnCountOfMixStream
                    it.index = routerViewModel.liveRoom.player.cdnIndexOfMixStream
                    showDialogFragment(it)
                }
            }
            ivPPTAuth.setOnClickListener {
                if (routerViewModel.broadcastStatus.value == true) {
                    showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                    return@setOnClickListener
                }
                clearLastCheckDrawItem(false)
                ivPPTAuth.isChecked = !ivPPTAuth.isChecked
                ivPPTAuth.background = if (ivPPTAuth.isChecked) {
                    ContextCompat.getDrawable(
                        contextReference,
                        R.drawable.live_tool_bar_check_layer_bg
                    )
                } else null
                val pptModel =
                    if (ivPPTAuth.isChecked) LPConstants.PPTEditMode.PPTTouchMode else LPConstants.PPTEditMode.Normal
                pptViewModel.changeDrawingStatus(ShapeChangeData(pptModel))
            }
            ivOperatePPT.setOnClickListener {
                if (routerViewModel.liveRoom.studentSwitchPPTState) {
                    showToastMessage(getString(R.string.bjy_live_operate_ppt_fail_tip))
                    return@setOnClickListener
                }
                if (!routerViewModel.liveRoom.hasH5PPTAuth()) {
                    routerViewModel.liveRoom.requestH5PPTAuth(true)
                } else {
                    pptView.showH5PPTAuthDialog(false)
                }
            }
            ivAsCameraStatus.setOnClickListener {
                if (routerViewModel.liveRoom.speakQueueVM.isReplacedUser) {
                    if (routerViewModel.mainVideoItem is LocalItem) {
                        (routerViewModel.mainVideoItem as LocalItem).endScannerCamera()
                    }
                } else {
                    if (routerViewModel.mainVideoItem is LocalItem) {
                        (routerViewModel.mainVideoItem as LocalItem).startScannerCamera()
                    }
                }
            }
            video_menu_iv.setOnClickListener {
                val maxScreenItem = routerViewModel.switch2MaxScreen.value
                if (maxScreenItem is BaseSwitchItem) {
                    maxScreenItem.showOptionDialog()
                }
            }
            bonus_points_iv.setOnClickListener {
                routerViewModel.actionShowBonusPointsWindow.value =
                    if (routerViewModel.actionShowBonusPointsWindow.value == null) true
                    else {
                        !routerViewModel.actionShowBonusPointsWindow.value!!
                    }
            }
            bonus_points_iv.visibility = if (enableBonusPoints()) View.VISIBLE else View.GONE

            RxUtils.clicks(tvVideo).throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .disposeUntilDestroy(this@PPTFragment)
                .subscribe {
                    if (routerViewModel.isClassStarted.value != true) {
                        showToastMessage(getString(R.string.pad_class_start_tip))
                        return@subscribe
                    }
                    if (routerViewModel.broadcastStatus.value == true) {
                        showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                        return@subscribe
                    }
                    if (routerViewModel.liveRoom.recorder.isScreenSharing) {
                        routerViewModel.actionCloseScreenShare.value = Unit
                        return@subscribe
                    }
                    if (!clickableCheck()) {
                        showToastMessage(getString(R.string.live_frequent_error))
                    } else {
                        pptViewModel.changeVideo()
                    }
                }

            compositeDisposable.add(RxUtils.clicks(tvAudio).throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (routerViewModel.isClassStarted.value != true) {
                        showToastMessage(getString(R.string.pad_class_start_tip))
                        return@subscribe
                    }
                    if (routerViewModel.broadcastStatus.value == true) {
                        showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                        return@subscribe
                    }
                    if (!clickableCheck()) {
                        showToastMessage(getString(R.string.live_frequent_error))
                    } else {
                        pptViewModel.changeAudio()
                    }
                })

            compositeDisposable.add(RxUtils.clicks(tvSpeakApply).throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (routerViewModel.isClassStarted.value != true) {
                        showToastMessage(getString(R.string.live_hand_up_error))
                        return@subscribe
                    }
                    if (routerViewModel.liveRoom.isBroadcasting) {
                        showToastMessage(getString(R.string.bjy_live_broadcast_operate_tip))
                        return@subscribe
                    }
                    if (!clickableCheck()) {
                        showToastMessage(getString(R.string.live_frequent_error))
                    } else {
                        pptViewModel.speakApply()
                    }
                })

            compositeDisposable.add(RxUtils.clicks(double_teacher_class_change_iv)
                .throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    showClassSwitchDialog(context, routerViewModel) {
                        routerViewModel.liveRoom.requestSwitchClass()
                    }
                })

            compositeDisposable.add(routerViewModel.liveRoom.observableOfClassSwitchState
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    double_teacher_class_change_iv.isSelected =
                        !double_teacher_class_change_iv.isSelected
                })

            when (routerViewModel.liveRoom.currentUser.type) {
                LPConstants.LPUserType.Teacher -> {
                    rlSpeakWrapper.visibility = View.GONE
                }

                LPConstants.LPUserType.Assistant -> {
                    rlSpeakWrapper.visibility = View.GONE
                }

                else -> {
                    tvPPTFiles.visibility = View.GONE
                    tvHandsUpCount.visibility = View.GONE
                    ivHandsUpImg.visibility = View.GONE
                    if (!routerViewModel.liveRoom.hasStudentRaise()) {
                        rlSpeakWrapper.visibility = View.GONE
                    }
                }
            }
            if (routerViewModel.liveRoom.roomInfo.isMockLive || routerViewModel.liveRoom.roomInfo.isPushLive) {
                rlSpeakWrapper.visibility = View.GONE
            }
        }

        pptView.run {
            start()
            if (!isInFullScreen) {
                switchToMaxScreen()
            }
            checkSyncPPTVideo()
        }
        //fix 'The specified child already has a parent'bug.
        //断线重连和重进，内存异常重启都已经移除了fragment
        //这么处理暂时规避问题，toolbars 是lazy的跟随this对象（尽量不用lazy）
        removeViewFromParent(pptMenuLayout)
        menuContainer.addView(
            pptMenuLayout,
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )
        pptMenuLayout.post {
            reLayoutPPTMenu(false)
            if (routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Assistant) {
                showAssistantMenu(routerViewModel.liveRoom.adminAuth)
            }
        }
        checkWarmingUpVideoPlaying()
        compositeDisposable.add(RxUtils.clicks(menu_expand_iv)
            .throttleFirst(400, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                // ConstraintLayout width=0dp 等价于 match_constraint(full width or full height)，这里最小只能为1
                if (isMenuExpand) {
                    startMenuAnim(leftContainerWidth, 1)
                } else {
                    startMenuAnim(1, leftContainerWidth)
                }
                pptMenuLayout.menu_expand_iv.isSelected = isMenuExpand
                isMenuExpand = !isMenuExpand
            })
        compositeDisposable.add(routerViewModel.liveRoom.toolBoxVM.observableOfBonusPointsAdd
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                bonusPointPopupWindow?.dismiss()
                bonusPointPopupWindow = BonusPointsPopupWindow(contextReference, it)
                bonusPointPopupWindow!!.run {
                    setOnDismissListener {
                        RxUtils.dispose(disposableOfBonusPointsTimer)
                    }
                    show(bonus_points_iv)
                    RxUtils.dispose(disposableOfBonusPointsTimer)
                    disposableOfBonusPointsTimer = Observable.timer(2, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            bonusPointPopupWindow?.dismiss()
                        }
                }
            })

        compositeDisposable.add(routerViewModel.liveRoom.toolBoxVM.observableOfBonusPointsRemainUpdate
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (!it.success) {
                    showToastMessage(getString(R.string.base_bouns_points_not_enough_tip))
                }
            })

        compositeDisposable.add(routerViewModel.liveRoom.speakQueueVM.observableOfWebrtcMode
            .mergeWith(routerViewModel.liveRoom.speakQueueVM.observableOfActiveUsers
                .map { true })
            .mergeWith(routerViewModel.liveRoom.player.observableOfCDNCountOfMixStream
                .map { true })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                switch_cdn_iv.visibility = if (enableSwitchCDN()) View.VISIBLE else View.GONE
            })

        if (isLiveWallAndEnableFullScreen() && pptViewModel.liveRoom.currentRoomLayout == LPConstants.RoomLayoutMode.GALLERY) {
            pptViewModel.routerViewModel.actionAutoMainVideo2FullScreen.value = true
        }
        if (routerViewModel.isSupportLiveShow()) {
            initLiveShow()
        } else {
            like_menu_iv.visibility = View.GONE
        }
    }

    private fun initLiveShow() {
        likeUI = LikeUI(routerViewModel.liveRoom)
        val itemBackground = DrawableBuilder()
            .rounded()
            .solidColor(
                ContextCompat.getColor(requireContext(), R.color.bjy_base_live_show_item_bg_color)
            )
            .build()
        like_menu_iv.background = itemBackground
        shop_menu_iv.background = itemBackground
        like_count_tv.background = DrawableBuilder()
            .cornerRadius(8.dp)
            .solidColor(Color.WHITE)
            .build()
        if (likeUI?.isSupportLiveLike() != true) {
            like_menu_iv.visibility = View.GONE
            like_count_tv.visibility = View.GONE
        }
        if (isAdmin(routerViewModel.liveRoom)) {
            like_menu_iv.isEnabled = false
            shop_menu_iv.visibility = View.VISIBLE
        } else {
            shop_menu_iv.visibility = if (routerViewModel.liveRoom.liveShowVM.isProductVisible) View.VISIBLE else View.GONE
        }
        likeUI?.run {
            setCountChangeListener {
                showRealLikeCount(it)
            }
        }
        like_menu_iv.setOnClickListener {
            // 偏移后对应上 like_menu_iv 的位置
            likeUI?.addFavor(heart_layout, resources.getDimensionPixelSize(R.dimen.ppt_menu_widget_root_margin))
        }
        shop_menu_iv.setOnClickListener {
            routerViewModel.showShop.value = Unit
        }
        routerViewModel.actionProductVisible.observe(this@PPTFragment) {
            if (routerViewModel.liveRoom.currentUser.type == LPConstants.LPUserType.Student) {
                shop_menu_iv.visibility = if (it == false) View.GONE else View.VISIBLE
            }
        }
    }

    private fun showRealLikeCount(likeCount: Int) {
        like_count_tv.visibility = if (likeCount <= 0) View.GONE else View.VISIBLE
        like_count_tv.text = convertLikeCount(likeCount)
    }

    override fun getBleProgress() = pptMenuLayout.writingboard_ble_progress

    override fun getBleContainer() = pptMenuLayout.writingboard_ble_container

    override fun getBleIcon() = pptMenuLayout.writingboard_ble_icon

    private fun isLiveWallAndEnableFullScreen(): Boolean {
        return pptViewModel.liveRoom.templateType == LPConstants.TemplateType.LIVE_WALL
                && pptViewModel.liveRoom.partnerConfig.isEnableAutoVideoFullscreen
    }

    private fun startMenuAnim(startWidth: Int, endWidth: Int) {
        menuAnim = ValueAnimator.ofInt(startWidth, endWidth)
        menuAnim!!.run {
            duration = 300
            addUpdateListener {
                val animatedValue = it.animatedValue as Int
                val layoutParams = ConstraintLayout.LayoutParams(
                    animatedValue,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
                layoutParams.startToEnd = R.id.menu_expand_iv
                layoutParams.bottomMargin =
                    resources.getDimension(R.dimen.ppt_menu_item_margin_bottom).toInt()
                pptMenuLayout.left_container.layoutParams = layoutParams
            }
            start()
        }
    }

    private fun enableStudentHomework() = !routerViewModel.liveRoom.isTeacherOrAssistant
            && !routerViewModel.liveRoom.isGroupTeacherOrAssistant
            && routerViewModel.liveRoom.partnerConfig.enableUseHomeWork == 1

    private fun enableOperateH5PPT() =
        routerViewModel.canOperateH5PPT() && (isFullScreen() || routerViewModel.switch2MaxScreen.value?.itemType == SpeakItemType.PPT) && routerViewModel.broadcastStatus.value == false

    private fun enableNoticeBtn() =
        routerViewModel.liveRoom.roomInfo.roomType != LPConstants.LPRoomType.OneOnOne && !isFullScreen()

    private fun enableVideoMenuBtn() =
        !isFullScreen() && routerViewModel.switch2MaxScreen.value?.itemType != SpeakItemType.PPT

    //只支持主讲分享二维码
    private fun enableAsCamera(): Boolean {
        //在全屏或者课件区显示
        return routerViewModel.liveRoom.speakQueueVM.enableAttachPhoneCamera() && (routerViewModel.mainVideoItem?.isInFullScreen == true
                || routerViewModel.mainVideoItem?.switchableStatus == SwitchableStatus.MaxScreen)
    }

    private fun enableBonusPoints() = routerViewModel.liveRoom.toolBoxVM.enableUseBonusPoints()

    private fun enableSwitchCDN() = routerViewModel.liveRoom.player.cdnCountOfMixStream > 1
            && routerViewModel.liveRoom.speakQueueVM.isMixModeOn && !routerViewModel.liveRoom.isTeacher
    // endregion

    /**
     * 暖场视频隐藏底部icon
     */
    private fun checkWarmingUpVideoPlaying() {
        if (enableWarmingUpVideo()) {
            hideBottomMenu()
        } else {
            showBottomMenu()
        }
    }

    /**
     * 手机端布局调整
     * 正常情况下在音视频按钮上24dp位置
     * 全屏时显示在右上位置
     */
    private fun reLayoutPPTMenu(showTop: Boolean? = true) = context?.apply {
        if (!DisplayUtils.isPad(this)) {
            val layoutParams = ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.WRAP_CONTENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT
            )
            if (showTop != true) {
                layoutParams.rightToRight = ConstraintSet.PARENT_ID
                layoutParams.bottomToBottom = ConstraintSet.PARENT_ID
                layoutParams.topToTop = ConstraintSet.UNSET
                layoutParams.bottomMargin =
                    resources.getDimensionPixelSize(R.dimen.ppt_menu_margin_bottom) + pptMenuLayout.ivFullScreen.measuredHeight
                layoutParams.rightMargin =
                    resources.getDimensionPixelSize(R.dimen.ppt_menu_widget_root_margin)
            } else {
                layoutParams.topToTop = ConstraintSet.PARENT_ID
                layoutParams.rightToRight = ConstraintSet.PARENT_ID
                layoutParams.bottomToBottom = ConstraintSet.UNSET
                layoutParams.topMargin =
                    resources.getDimensionPixelSize(R.dimen.ppt_menu_widget_root_margin)
                layoutParams.rightMargin =
                    resources.getDimensionPixelSize(R.dimen.ppt_menu_widget_root_margin)
            }
            pptMenuLayout.llPenMenu.layoutParams = layoutParams
        }
    }

    override fun clearLastCheckDrawItem(pptAuth: Boolean?) {
        super.clearLastCheckDrawItem(pptAuth)
        if (pptMenuLayout.ivPPTAuth.isChecked && pptAuth != false) {
            pptMenuLayout.ivPPTAuth.isChecked = false
            pptMenuLayout.ivPPTAuth.background = null
        }
    }

    override fun hideBottomMenu() {
        if (!routerViewModel.liveRoom.speakQueueVM.enableWarmingUpVideo()) {
            return
        }
        pptMenuLayout.run {
            right_container.visibility = View.GONE
            menu_expand_iv.visibility = View.GONE
            left_container.visibility = View.GONE
        }
    }

    override fun showBottomMenu() {
        if (!routerViewModel.liveRoom.speakQueueVM.enableWarmingUpVideo()) {
            return
        }
        pptMenuLayout.run {
            right_container.visibility = View.VISIBLE
            menu_expand_iv.visibility = View.VISIBLE
            left_container.visibility = View.VISIBLE
        }
    }

    // endregion
    override fun initPPTViewObserve() {
        super.initPPTViewObserve()
        routerViewModel.run {
            // endregion
            //ppt全屏不要公告问答和摄像头音频,视频全屏时，只有举手按钮
            switch2FullScreen.observeForever(switch2FullScreenObserver)
            switch2MaxScreen.observeForever(switch2MaxScreenObserver)
            if (enableQaBtn()) {
                hasNewQa.observe(this@PPTFragment, Observer {
                    pptMenuLayout.tvQaTip.visibility =
                        if (it == true && !isQaOpen) View.VISIBLE else View.GONE
                })
            }
            showRollCall.observeForever(showRollCallObserver)
            dismissRollCall.observeForever(dismissRollCallObserver)
        }
    }

    /**
     * 启用时调用此方法以检查 ppt 状态，如果不在黑板区则恢复至黑板区
     */
    override fun checkAndResetInSync(pptView: PPTView): Boolean {
        (pptView as PadPPTView).run {
            //不能用isFullScreen判断是不是全屏中
            if (switchableStatus != SwitchableStatus.MaxScreen && routerViewModel.switch2FullScreen.value?.first != true) {
                switchPPTVideoWithoutSync()
                return true
            }
            return false
        }
    }

    private val showRollCallObserver by lazy {
        Observer<Pair<Int, OnPhoneRollCallListener.RollCall?>> {
            it?.let {
                if (it.first != -1 && enableRollCall(routerViewModel.liveRoom)) {
                    pptMenuLayout.view_roll_call_going.visibility = View.VISIBLE
                    //点名
                    toolboxWindow.setDotsVisibility(
                        getString(R.string.base_toolbox_roll_call),
                        true
                    )
                }
            }
        }
    }

    private val dismissRollCallObserver by lazy {
        Observer<Boolean> {
            if (!it && enableRollCall(routerViewModel.liveRoom)) {
                pptMenuLayout.view_roll_call_going.visibility = View.GONE
                //点名
                toolboxWindow.setDotsVisibility(
                    getString(R.string.base_toolbox_roll_call), false
                )
            }
        }
    }

    private fun updateToolbarVisible() {
        if (pptViewModel.isEnableDrawing()) {
            brushDragLayout.visibility =
                if ((pptView.switchableStatus == SwitchableStatus.MaxScreen && !pptView.isClosingByExtCamera && !isFullScreen())
                    || pptView.isInFullScreen
                ) View.VISIBLE else View.GONE
        } else {
            brushDragLayout.visibility = View.GONE
        }
    }

    private fun updateFloatChatVisible() {
        // 非ppt全屏且大班课开了配置项才显示聊天飘窗入口
        floating_recycler.visibility =
            if (isLiveWallAndEnableFullScreen() &&
                isFullScreen() && !pptView.isInFullScreen
            ) View.VISIBLE else View.GONE
        floating_tv.visibility =
            if (isLiveWallAndEnableFullScreen() &&
                isFullScreen() && !pptView.isInFullScreen
            ) View.VISIBLE else View.GONE
    }

    private fun checkSyncPPTVideo() {
        if (routerViewModel.registerSyncPPTVideo.value != true) {
            routerViewModel.registerSyncPPTVideo.value = true
        }
    }

    override fun showSpeakClosedByTeacher(isSmallGroup: Boolean) {
        tvSpeakApply.isChecked = false
        if (!isSmallGroup) {
            enableAllToolbarItem(false)
        }
        tvCountDown.visibility = View.INVISIBLE
        pptView.changeTouchAble(false)
    }

    override fun showSpeakClosedByServer() {
        showToastMessage(getString(R.string.live_media_speak_closed_by_server))
        with(pptMenuLayout) {
            tvSpeakApply.isChecked = false
            enableAllToolbarItem(false)
            tvCountDown.visibility = View.INVISIBLE
        }
    }

    override fun showForceSpeakDenyByServer() {
        showToastMessage(getString(R.string.live_force_speak_closed_by_server))
        with(pptMenuLayout) {
            tvSpeakApply.isChecked = false
            enableAllToolbarItem(false)
            tvCountDown.visibility = View.INVISIBLE
        }
    }

    override fun showSpeakApplyCountDown(countDownTime: Int, total: Int) {
        with(pptMenuLayout) {
            tvCountDown.visibility = View.VISIBLE
            tvCountDown.setRatio(countDownTime / total.toFloat())
        }
    }

    override fun showSpeakApplyDisagreed() {
        with(pptMenuLayout) {
            tvSpeakApply.isEnabled = true
            tvSpeakApply.isChecked = false
            showToastMessage(getString(R.string.live_media_speak_apply_disagree))
            tvCountDown.visibility = View.INVISIBLE
        }
    }

    override fun showSpeakApplyCanceled() {
        tvSpeakApply.isEnabled = true
        tvSpeakApply.isChecked = false
        enableAllToolbarItem(false)
        tvCountDown.visibility = View.INVISIBLE
        pptView.changeTouchAble(false)
    }

    override fun showTeacherMenu(isGroupAdmin: Boolean) {
        super.showTeacherMenu(isGroupAdmin)
        with(pptMenuLayout) {
            if (routerViewModel.liveRoom.isGroupTeacherOrAssistant) {
                tvPPTFiles.visibility = View.GONE
            } else {
                tvPPTFiles.visibility = View.VISIBLE
            }
            ivPPTAuth.visibility = View.VISIBLE
            ivToolBox.visibility = if (checkToolboxCanUse()) View.VISIBLE else View.GONE
            tvSpeakApply.visibility = View.GONE
        }
    }

    override fun showStudentMenu() {
        super.showStudentMenu()
        with(pptMenuLayout) {
            tvPPTFiles.visibility = View.GONE
            tvSpeakApply.visibility = View.VISIBLE
        }
    }

    override fun hidePPTDrawBtn() {
        super.hidePPTDrawBtn()
        showToastMessage(getString(R.string.live_student_no_auth_drawing))
    }

    override fun showPPTDrawBtn() {
        super.showPPTDrawBtn()
        showToastMessage(getString(R.string.live_student_auth_drawing))
    }

    // region 获得发言权限
    override fun showAutoSpeak(isDrawingEnable: Boolean) {
        super.showAutoSpeak(isDrawingEnable)
        pptMenuLayout.rlSpeakWrapper.visibility = View.GONE
        clearLastCheckDrawItem()
    }

    override fun showForceSpeak(isDrawingEnable: Boolean) {
        super.showForceSpeak(isDrawingEnable)
        pptMenuLayout.tvSpeakApply.isChecked = true
        pptMenuLayout.tvCountDown.visibility = View.INVISIBLE
        clearLastCheckDrawItem()
    }

    override fun showSpeakApplyAgreed(isDrawingEnable: Boolean) {
        super.showSpeakApplyAgreed(isDrawingEnable)
        showToastMessage(getString(R.string.live_media_speak_apply_agree))
        tvSpeakApply.isChecked = true
        tvCountDown.visibility = View.INVISIBLE
        clearLastCheckDrawItem()
    }

    override fun setAudition() {
        super.setAudition()
        pptMenuLayout.run {
            // 试听，隐藏所有
            tvPPTFiles.visibility = View.GONE
            tvAudio.visibility = View.GONE
            tvVideo.visibility = View.GONE
        }
    }

    override fun showVideoStatus(isOn: Boolean) {
        pptMenuLayout.tvVideo.isChecked = isOn
        if (routerViewModel.liveRoom.speakQueueVM.isReplacedUser) {
            pptMenuLayout.ivAsCameraStatus.isSelected = isOn
        } else {
            pptMenuLayout.ivAsCameraStatus.isSelected = false
        }
        showToastMessage(if (isOn) getString(R.string.live_camera_on) else getString(R.string.live_camera_off))
    }

    override fun showAudioStatus(isOn: Boolean) {
        pptMenuLayout.tvAudio.isChecked = isOn
        showToastMessage(if (isOn) getString(R.string.live_mic_on) else getString(R.string.live_mic_off))
    }

    override fun enableSpeakerMode() {
        with(pptMenuLayout) {
            if (routerViewModel.liveRoom.partnerConfig.liveHideStudentCamera != 1) {
                tvVideo.visibility = View.VISIBLE
            }
            tvAudio.visibility = View.VISIBLE
        }
    }

    override fun disableSpeakerMode() {
        with(pptMenuLayout) {
            tvVideo.visibility = View.GONE
            tvAudio.visibility = View.GONE
        }
    }

    private var showToastCache = false

    override fun showH5PPTAuth(auth: Boolean?) {
        if (routerViewModel.canOperateH5PPT()) {
            pptMenuLayout.ivOperatePPT.isSelected = auth ?: false
        }
        if (!isAdmin(routerViewModel.liveRoom)) {
            pptMenuLayout.ivPPTAuth.visibility = if (auth == true) View.VISIBLE else View.GONE
            if (auth != true) {
                pptMenuLayout.ivPPTAuth.isChecked = false
                pptMenuLayout.ivPPTAuth.background = null
                pptViewModel.changeDrawingStatus(ShapeChangeData(LPConstants.PPTEditMode.Normal))
            }
            val resId =
                if (auth == true) R.string.live_h5_ppt_auth_confirm_tip else R.string.live_h5_ppt_auth_cancel_tip
            if (showToastCache) {
                showToastMessage(getString(resId))
            } else {
                showToastCache = true
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        likeUI?.release()
        menuAnim?.removeAllUpdateListeners()
        menuAnim?.cancel()
        cdnSwitchDialog?.dismissAllowingStateLoss()
        bonusPointPopupWindow?.dismiss()
        routerViewModel.showRollCall.removeObserver(showRollCallObserver)
        routerViewModel.dismissRollCall.removeObserver(dismissRollCallObserver)
        routerViewModel.switch2FullScreen.removeObserver(switch2FullScreenObserver)
        routerViewModel.switch2MaxScreen.removeObserver(switch2MaxScreenObserver)
        RxUtils.dispose(disposableOfBonusPointsTimer)
    }

    override fun getLayoutId(): Int = R.layout.fragment_pad_ppt

    /**
     * 更新音视频按钮可见性
     */
    private fun updateAVButtonVisibility() {
        if (isShowAvButton()) {
            pptMenuLayout.media_container.visibility = View.GONE
        } else {
            pptMenuLayout.media_container.visibility = View.VISIBLE
        }
    }

    private fun isShowAvButton() =
        enableWarmingUpVideo() || isFullScreen() || routerViewModel.liveRoom.roomInfo.isMockLive || routerViewModel.liveRoom.roomInfo.isPushLive

    private fun isShowAsCamera(pair: Pair<Boolean, Switchable?>) =
        (pair.first || pair.second?.switchableStatus == SwitchableStatus.MaxScreen)
                && pair.second is LocalItem && routerViewModel.liveRoom.speakQueueVM.enableAttachPhoneCamera()

    companion object {
        fun newInstance() = PPTFragment()
        const val TAG: String = "LPSpeakQueueViewModel"
        const val LIKE_URL = "https://img.baijiayun.com/0baijiatools/f5000c8c2332757d6fec37de5daec5ee/love.svga"
        const val SHOP_URL = "https://img.baijiayun.com/0baijiatools/f5000c8c2332757d6fec37de5daec5ee/shopping_cart.svga"
    }
}