package com.swago.room.base

import android.Manifest
import android.graphics.Rect
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.gyf.immersionbar.ImmersionBar
import com.liulishuo.okdownload.DownloadListener
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.cause.ResumeFailedCause
import com.permissionx.guolindev.PermissionX
import com.swago.baseswago.PersonDataDFragment
import com.swago.baseswago.UserVm
import com.swago.baseswago.agora.AgoraManager
import com.swago.baseswago.baseroom.*
import com.swago.baseswago.constant.ARouteConstant
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.cusview.MediumTextView
import com.swago.baseswago.cusview.SwagoImageView
import com.swago.baseswago.dialog.ChoiceDialogFragment
import com.swago.baseswago.fragment.BaseXFragment
import com.swago.baseswago.im.IRoomChat
import com.swago.baseswago.model.im.GamePrize
import com.swago.baseswago.model.im.RoomSystemMsgBean
import com.swago.baseswago.model.live.RoomConfig
import com.swago.baseswago.model.live.RoomUserModel
import com.swago.baseswago.model.live.audio.AudioSeatModel
import com.swago.baseswago.model.live.audio.IMAudioModel
import com.swago.baseswago.model.live.audio.PositionBean
import com.swago.baseswago.model.live.game.GameModel
import com.swago.baseswago.util.*
import com.swago.room.R
import com.swago.room.adapter.RoomChatAdapter
import com.swago.room.audio.AudioActionDialog
import com.swago.room.audio.AudioRoomManager
import com.swago.room.audio.AudioSeatAdapter
import com.swago.room.audio.IAudioRoomListener
import com.swago.room.audio.widget.AudioGiftAnimManager
import com.swago.room.bean.UserRoomModel
import com.swago.room.databinding.FragmentBaseComBinding
import com.swago.room.dialog.AudienceListDialog
import com.swago.room.dialog.MessageListDialog
import com.swago.room.dialog.SendMsgDialog
import com.swago.room.enum.RoomType
import com.swago.room.game.GamePlayDialog
import com.swago.room.gift.GiftDialog
import com.swago.room.gift.GiftVm
import com.swago.room.gift.control.SvgPlayerManager
import com.swago.room.giftdandao.GiftDanDaoManager
import com.swago.room.hongbao.RedDetailListDialog
import com.swago.room.hongbao.RedEnvelopResultDialog
import com.swago.room.hongbao.RedEnvelopeDialog
import com.swago.room.inter.IFooter
import com.swago.room.inter.IHeader
import com.swago.room.lianmai.LianMaiVm
import com.swago.room.piaotiao.WaftManager
import com.swago.room.pk.IPKListener
import com.swago.room.pk.PKStateManager
import com.swago.room.pk.PkVm
import com.swago.room.user.UserRoomActivity
import com.swago.room.vm.MsgVm
import com.swago.room.vm.RoomOtherVm
import com.swago.room.vm.RoomVm
import com.swago.room.widget.AnchorFooterView
import com.swago.room.widget.ComHeaderView
import com.swago.room.widget.UserFooterView
import io.agora.rtc.IRtcEngineEventHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.lang.Exception
import java.util.concurrent.CopyOnWriteArrayList

/**
 *@date 2021/10/8 16:43
 *description:
 */
abstract class BaseComFragment<T : FragmentBaseComBinding> : BaseXFragment<T>(),
    IRoomActiveListener, IPKListener,
    RoomTimer.TimeTickListener, IAudioRoomListener {

    val giftVm by activityViewModels<GiftVm>()
    val pkVm by activityViewModels<PkVm>()
    val lianMaiVm by activityViewModels<LianMaiVm>()

    val roomVm by activityViewModels<RoomVm>()
    val roomOtherVm by activityViewModels<RoomOtherVm>()
    val msgVm by activityViewModels<MsgVm>()
    val userVm by activityViewModels<UserVm>()

    /**
     * 麦位信息
     */
    private val allPositionXYList by lazy {
        CopyOnWriteArrayList<PositionBean>()
    }
    var count = 2

    //直播间观众列表
    var roomUserList = CopyOnWriteArrayList<RoomUserModel.ListBean>()

    //聊天消息
    private val dataChatList = CopyOnWriteArrayList<IRoomChat>()

    //暂时仅用户端使用
    var isForbid = false //是否被禁言

    abstract val iHeader: IHeader
    abstract val iFooter: IFooter

    var roomConfig: RoomConfig? = null

    var dialog: SendMsgDialog? = null
    var gameDialog: GamePlayDialog? = null
    var msgListDialog: MessageListDialog? = null

    val gameList by lazy {
        ArrayList<GameModel>()
    }

    private val chatAdapter by lazy {
        RoomChatAdapter()
    }

    private val svgPlayerManager by lazy {
        SvgPlayerManager()
    }

    private val waftManager by lazy {
        WaftManager()
    }

    private val danDaoManager by lazy {
        GiftDanDaoManager()
    }

    private val audioGiftManager by lazy {
        AudioGiftAnimManager()
    }

    override fun loadData() {

    }

    override fun initOther() {
        RoomTimer.timeTickList.add(this)
        PKStateManager.addPKListener(this)
        SwagoRoomManager.addListener(this)
        AudioRoomManager.addListener(this)
        binding.headFl.addView(iHeader.getHeaderView())
        binding.footerFl.addView(iFooter.getFooterView())
        setHeaderViewPosition()
        //获取直播间配置
        roomVm.getRoomConfig()
        //初始话语音列表
        initAudioRvList()
        //飘条
        waftManager.init()
        waftManager.waftViewList.add(binding.waftView)
        waftManager.waftViewList.add(binding.waftView2)
        //弹道
        danDaoManager.init()
        danDaoManager.giftDanDaoViewList.add(binding.danDaoView)
        danDaoManager.giftDanDaoViewList.add(binding.danDaoView2)
        danDaoManager.giftDanDaoViewList.add(binding.danDaoView3)
        //语音直播间动画
        audioGiftManager.init()
        audioGiftManager.audioGiftViewList.add(binding.audioAllGiftView)
        //进场特效
        msgVm.joinRoomManager.initViewStub(binding.joinRoomViewStub, activity)
        //
        binding.danMuView.setActivity(activity)
        binding.hongbaoPiaotiao.setActivity(activity)
        binding.hongbaoPiaotiao.goToTargetRoom = {
            if (SwagoRoomManager.roleType == RoleType.user){
                goToTargetRoom(it)
            }
        }
        val layoutManager = LinearLayoutManager(context)
        layoutManager.stackFromEnd = true
        binding.rv.layoutManager = layoutManager
        binding.rv.addItemDecoration(RoomChatItemDecoration())
        binding.rv.adapter = chatAdapter
        chatAdapter.setNewData(dataChatList)
        context?.let {
            svgPlayerManager.init(it, binding.xSvgaPlayer, binding.svgDanDaoView)
        }

        activity?.let {
            KeyboardUtils.registerSoftInputChangedListener(it.window, listener)
        }

        binding.pkLayoutView.doGetPKInfoFun = {
            SwagoRoomManager.iRoomInfo?.let {
                pkVm.getPKInfo(it.getRoomId())
            }
        }
    }

    private fun initAudioRvList() {
        activity?.let {
            binding.rvAudio.addItemDecoration(GridItemDecoration())
            binding.rvAudio.layoutManager = GridLayoutManager(it, 4)
            binding.rvAudio.adapter = audioSeatAdapter
            audioSeatAdapter.setOnItemClickListener { _, _, position ->
                val audioSeatModel = audioSeatAdapter.data[position]
                if (audioSeatModel.user_id == "0") {
                    //麦位没有人
                    if (SwagoRoomManager.roleType == RoleType.anchor) {
                        //主播点击麦位
                        AudioActionDialog.newInstance(audioSeatModel)
                            .show(childFragmentManager, "AudioActionDialog")
                    } else {
                        //用户点击了空位麦 如果是麦位被锁弹提示
                        //如果麦位没有被锁 先判断自己是否在麦位上 如果在弹提示  如果不在弹上麦弹窗
                        if (audioSeatModel.lock_status == 2) {
                            Toast.makeText(AppContext.getContext(), "当前麦位已被锁", Toast.LENGTH_SHORT)
                                .show()
                        }else{
                            if (AudioRoomManager.isOnMic){
                                Toast.makeText(AppContext.getContext(), "您已经在麦位上", Toast.LENGTH_SHORT)
                                    .show()
                            }else{
                                ChoiceDialogFragment.newInstance("您想要上麦么?").apply {
                                    this.sureFun = {
                                        PermissionX.init(it)
                                            .permissions(
                                                Manifest.permission.RECORD_AUDIO,
                                                Manifest.permission.CAMERA,
                                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                            .request { allGranted, grantedList, deniedList ->
                                                if (allGranted) {
                                                    roomVm.userApplyOnMic(audioSeatModel.maiIndex)
                                                } else {
                                                    Toast.makeText(
                                                        AppContext.getContext(),
                                                        "These permissions are denied: $deniedList",
                                                        Toast.LENGTH_LONG
                                                    ).show()
                                                }
                                            }
                                    }
                                }.show(childFragmentManager,"ChoiceDialogFragment")
                            }
                        }
                    }
                } else {
                    //麦位有人
                    if (SwagoRoomManager.roleType == RoleType.anchor) {
                        //主播点击麦位
                        AudioActionDialog.newInstance(audioSeatModel)
                            .show(childFragmentManager, "AudioActionDialog")
                    } else {
                        //用户点击了有人的麦位
                        //如果点击的麦位不是自己弹资料卡  如果是自己弹操作弹窗
                        SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                            audioSeatModel.user_id?.let {
                                UserInfo.getUserInfo()?.let { userInfoModel ->
                                    if (userInfoModel.id == it){
                                        AudioActionDialog.newInstance(audioSeatModel)
                                            .show(childFragmentManager, "AudioActionDialog")
                                    }else{
                                        PersonDataDFragment.newInstance(it,
                                            SwagoRoomManager.roleType==RoleType.anchor,true,iRoomInfo.getRoomId()).apply {
                                            this.openGiftDialog = { nickName, userId ->
                                                openGiftDialog(nickName, userId)
                                            }
                                            this.sendMsgInRoom = {
                                                if (isForbid) {
                                                    Toast.makeText(
                                                        AppContext.getContext(),
                                                        AppContext.getContext().resources.getString(
                                                            R.string.you_are_been_forbid
                                                        ),
                                                        Toast.LENGTH_SHORT
                                                    ).show()
                                                } else {
                                                    openSendMessageDialog("@${it} ")
                                                }
                                            }
                                        }.show(childFragmentManager,"PersonDataDFragment")
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    var listener = KeyboardUtils.OnSoftInputChangedListener {
        if (it == 0) {
            setChatRvPop(false, it)
        } else {
            setChatRvPop(true, it)
        }
    }

    private fun setHeaderViewPosition() {
        val height = ImmersionBar.getStatusBarHeight(this)
        val params = binding.headFl.layoutParams as ConstraintLayout.LayoutParams
        params.topMargin = height
        binding.headFl.layoutParams = params
    }

    override fun initLiveData() {
        roomVm.roomUserDataLiveData.observe(this) {
            it?.let {
                roomUserList.clear()
                roomUserList.addAll(it.list)
                (iHeader as ComHeaderView).updateRoomUser(roomUserList, it.count)
            }
        }

        msgVm.updateUserRoom = { data, count ->
            roomUserList.clear()
            roomUserList.addAll(data)
            (iHeader as ComHeaderView).updateRoomUser(roomUserList, count)
        }

        chatAdapter.showUserInfoDialog = {
            var isAnchor = false
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                isAnchor = iRoomInfo.getAnchorId() == UserInfo.getUserInfo()?.id
            }
            PersonDataDFragment.newInstance(
                it.getSenderId(),
                isAnchor = isAnchor,
                inRoom = true,
                SwagoRoomManager.iRoomInfo?.getRoomId() ?: ""
            )
                .apply {
                    this.openGiftDialog = { nickName, userId ->
                        openGiftDialog(nickName, userId)
                    }
                    this.sendMsgInRoom = {
                        if (isForbid) {
                            Toast.makeText(
                                AppContext.getContext(),
                                AppContext.getContext().resources.getString(
                                    R.string.you_are_been_forbid
                                ),
                                Toast.LENGTH_SHORT
                            ).show()
                        } else {
                            openSendMessageDialog("@${it} ")
                        }
                    }
                }.show(childFragmentManager, "PersonDataDFragment")
        }

        msgVm.newChatMsgFun = {
            addChatMsgToRv(it)
        }
        msgVm.playSvgUrl = {
            //svg播放
            svgPlayerManager.addSvgUrl(it)
            svgPlayerManager.addSvgDanDaoView(it)
        }
        //飘条
        msgVm.waftFun = {
            //如果是游戏飘条 要判断游戏列表是否有数据有则展示游戏飘条
            if (it is GamePrize) {
                if (gameList.isNotEmpty()) {
                    waftManager.addNewMessage(it)
                }
            } else {
                waftManager.addNewMessage(it)
            }
        }
        msgVm.showGiftDanDao = {
            danDaoManager.addNewMessage(it)
        }

        msgVm.inComeChange = {
            (iHeader as ComHeaderView).updateIncome(it)
        }

        msgVm.updateHotValue = {
            (iHeader as ComHeaderView).updateHotValue(it)
        }

        (iHeader as ComHeaderView).followFun = {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                userVm.followUser(it, 0, iRoomInfo.getBroadcastId())
            }
        }

        (iHeader as ComHeaderView).openAudienceListDialog = {
            AudienceListDialog.newInstance().show(childFragmentManager, "AudienceListDialog")
        }

        //游戏列表
        roomVm.gameListModelLiveData.observe(this) {
            it.game?.let { gameData ->
                iFooter.setGameIcon(gameData.isNotEmpty())
                gameList.addAll(gameData)
            }
        }

        //直播间配置
        roomVm.roomConfigLiveData.observe(this) {
            this.roomConfig = it
            //轮播图
//            binding.bannerView.setData(it.banners)
//            binding.bannerView.jumpToWebFun = { banner ->
//                ARouter.getInstance().build(ARouteConstant.Base.webView)
//                    .withString("url", banner.rotation_url)
//                    .navigation()
//            }
        }

        //语音房麦位列表数据
        roomVm.audioSeatListLiveData.observe(this) {
            if (it != null) {
                audioSeatAdapter.setNewData(it)
                initMaiPosition()
            }
        }

        //红包列表
        roomOtherVm.redEnvelopeListLiveData.observe(this) {
            binding.ivRedEnvelopeView.addRedEnvelopList(it)
        }

        //IM下发新的红包
        msgVm.newRedEnvelopeCome = {
            binding.ivRedEnvelopeView.addIMRedEnvelope(it)
        }

        //更新语音房公告
        msgVm.updateAudioNotice = {
            (iHeader as ComHeaderView).updateAudioNotice(it)
        }

        msgVm.addDanMuFun = {
            binding.danMuView.addQueue(it)
        }

        msgVm.addHongbaoPiaotiao = {
            binding.hongbaoPiaotiao.addQueue(it)
        }

        msgVm.addAudioGiftAnimFun = { data ->
            if (allPositionXYList.size > 0) {
                data.receivers.forEach {
                    if (allPositionXYList.size>=it.maiIndex){
                        it.offSetY = allPositionXYList[it.maiIndex-1].offSetY
                        it.dx = allPositionXYList[it.maiIndex-1].dx
                        it.dy = allPositionXYList[it.maiIndex-1].dy
                    }
                }
                audioGiftManager.addNewMessage(data)
            }
        }

        msgVm.multiJiFenChangeFun = { data  ->
            data.forEach {
                if (audioSeatAdapter.data.size>it.maiIndex-1 && it.maiIndex-1>=0){
                    audioSeatAdapter.data[it.maiIndex-1].voice_jifen = it.voice_jifen
                    val view = audioSeatAdapter.getViewByPosition(binding.rvAudio,it.maiIndex-1,R.id.tvIntegration)
                    if (view != null && view is TextView) {
                        view.text = it.voice_jifen
                    }
                }
            }
        }

        //打开红包
        binding.ivRedEnvelopeView.openRedEnvelope = {
            RedEnvelopResultDialog.newInstance(it.id, it.senderAvatar, it.senderName).apply {
                this.openGiftDialog = {
                    SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                        openGiftDialog(iRoomInfo.getAnchorName(), iRoomInfo.getAnchorId())
                    }
                }
                this.openRedDetailDialog =  {
                    RedDetailListDialog.newInstance(it.id,it.senderAvatar, it.senderName,it.senderLevel).show(parentFragmentManager,"RedDetailListDialog")
                }
                this.addSenderMsgToRoomChatList = {
                    addChatMsgToRv(it)
                }
            }.show(childFragmentManager, "RedEnvelopResultDialog")
        }
    }

    private fun initMaiPosition() {
        allPositionXYList.clear()
        val centerX = DpPxUtil.getScreenWidth() / 2
        val centerY =  DpPxUtil.getScreenHeight() / 2
        binding.apply {
            audioSeatAdapter.data.forEachIndexed { index, _ ->
                val positionXY = IntArray(2)
                val ivAvatar = audioSeatAdapter.getViewByPosition(rvAudio, index, R.id.ivImageView)
                ivAvatar?.let {
                    it.getLocationOnScreen(positionXY)
                    val ivAvatarCenterX = positionXY[0].toFloat() + it.width / 2
                    val ivAvatarCenterY = positionXY[1].toFloat() + it.width / 2
                    val positionBean2 = PositionBean(
                        ivAvatarCenterX - centerX,
                        ivAvatarCenterY - centerY,
                        ivAvatarCenterY - centerY - DpPxUtil.dip2px(50f).toFloat()
                    )
                    allPositionXYList.add(positionBean2)
                }
            }

            //这里为了防止第一次获取位置时获取失败
            lifecycleScope.launch(Dispatchers.Main) {
                if (allPositionXYList.size > 3 && allPositionXYList[1].dx != allPositionXYList[2].dx) {} else {
                    delay(1500)
                    if (count > 0) {
                        count--
                        initMaiPosition()
                    }
                }
            }
        }
    }

    private fun openGiftDialog(nickName: String, userId: String) {
        GiftDialog.newInstance(
            nickName,
            userId
        ).apply {
            this.openSendRedEnvelopeFun = {
                RedEnvelopeDialog.newInstance(roomConfig)
                    .show(this@BaseComFragment.childFragmentManager, "RedEnvelopeDialog")
            }
        }.show(childFragmentManager, "GiftDialog")
    }

    private fun addChatMsgToRv(it: IRoomChat?) {
        if (dataChatList.size > 150) {
            dataChatList.removeAt(0)
        }
        it?.let {
            dataChatList.add(it)
        }
        chatAdapter.notifyDataSetChanged()
        binding.rv.smoothScrollToPosition(dataChatList.size - 1)
    }


    private var keyboardUpRvLayoutParams: ViewGroup.LayoutParams? = null
    private var keyboardCloseRvLayoutParams: ViewGroup.LayoutParams? = null
    private fun setChatRvPop(isPopUp: Boolean, height: Int) {
        if (isPopUp) {
            if (keyboardUpRvLayoutParams == null) {
                keyboardUpRvLayoutParams =
                    ConstraintLayout.LayoutParams(0, DpPxUtil.dip2px(170f)).apply {
                        bottomToBottom = R.id.cl
                        startToStart = R.id.cl
                        endToEnd = R.id.cl
                        marginStart = DpPxUtil.dip2px(10f)
                        marginEnd = DpPxUtil.dip2px(10f)
                        bottomMargin = height + DpPxUtil.dip2px(55f)
                    }
            }
            binding.rv.layoutParams = keyboardUpRvLayoutParams
        } else {
            if (keyboardCloseRvLayoutParams == null) {
                keyboardCloseRvLayoutParams =
                    ConstraintLayout.LayoutParams(0, DpPxUtil.dip2px(170f)).apply {
                        bottomToBottom = R.id.cl
                        startToStart = R.id.cl
                        endToEnd = R.id.cl
                        marginStart = DpPxUtil.dip2px(10f)
                        marginEnd = DpPxUtil.dip2px(10f)
                        bottomMargin = DpPxUtil.dip2px(70f)
                    }
            }
            binding.rv.layoutParams = keyboardCloseRvLayoutParams
        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        dialog = null
        gameDialog = null
        msgListDialog = null
        PKStateManager.removePKListener(this)
        activity?.let {
            KeyboardUtils.unregisterSoftInputChangedListener(it.window)
        }
        AudioRoomManager.removeListener(this)
        SwagoRoomManager.removeListener(this)
    }

    fun openSendMessageDialog(atName: String = "") {
        dialog = SendMsgDialog.newInstance(atName)
        dialog?.addSenderMsgToRoomChatList = {
            addChatMsgToRv(it)
        }
        dialog?.show(childFragmentManager, "SendMsgDialog")
    }

    fun openMessageListDialog() {
        msgListDialog = MessageListDialog.newInstance()
        msgListDialog?.show(childFragmentManager, "MessageListDialog")
    }

    fun openGameDialog() {
        SwagoRoomManager.iRoomInfo?.let {
            val download = checkGameVersion(
                it.getGameType().toString(),
                it.getGameDownLoadUrl(),
                it.getGameVersion().toString()
            )
            if (download) {
                gameDialog =
                    GamePlayDialog.newInstance("file://" + UrlConstant.appGameRootPath + File.separator + it.getGameType() + File.separator + "index.html",it.getIsFullGame())
            } else {
                gameDialog = GamePlayDialog.newInstance(it.getGameUrl(),it.getIsFullGame())
            }
            gameDialog?.show(childFragmentManager, "GamePlayDialog")
        }
    }

    private var isFirst = true
    override fun joinedRoom(iRoomInfo: IRoomInfo) {
        roomOtherVm.getRedEnvelopeList()
        if (iRoomInfo.getRoomType() == RoomType.AUDIO.type) {
            roomVm.getAudioList(iRoomInfo.getAnchorId(), 2)
            binding.rvAudio.visibility = View.VISIBLE
        }else{
            binding.rvAudio.visibility = View.GONE
        }
        if (iRoomInfo.getRoomSystemMsg().isNotEmpty()) {
            val roomSystemMsgBean = RoomSystemMsgBean()
            roomSystemMsgBean.broadcast_notice_content = iRoomInfo.getRoomSystemMsg()
            dataChatList.add(roomSystemMsgBean)
            chatAdapter.notifyDataSetChanged()
        }

        //默认是否自动弹出游戏
        lifecycleScope.launch(Dispatchers.Main) {
            delay(2000)
            roomConfig?.let {
                if (gameList.isNotEmpty() && it.auto_show_game == 1) {
                    if (it.is_repeat_game == 1) {
                        //多次弹出游戏
                        setGameDefaultData(0)
                    } else {
                        if (isFirst) {
                            //只弹出一次
                            setGameDefaultData(0)
                            isFirst = false
                        }
                    }
                }
            }
        }

        if (SwagoRoomManager.roleType == RoleType.user) {
            UserInfo.getUserInfo()?.let {
                if (it.id.isNotEmpty()) {
                    SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                        roomVm.getUserRoomAuth(it.id, iRoomInfo.getRoomId())
                    }
                }
            }
        }
    }

    fun setGameDefaultData(index: Int) {
        SwagoRoomManager.iRoomInfo?.let {
            if (it is UserRoomModel && gameList.size > index) {
                it.roomModel?.game_api_url = gameList[index].game_api_url
                it.roomModel?.game_down_url = gameList[index].game_down_url
                it.roomModel?.game_type = gameList[index].game_type
                it.roomModel?.game_version = gameList[index].game_version
                it.roomModel?.game_icon_url = gameList[index].game_icon_url
                openGameDialog()
            }
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
       binding?.rvAudio?.visibility = View.GONE
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        dataChatList.clear()
        chatAdapter.notifyDataSetChanged()
        if (iRoomInfo.getRoomType() == RoomType.AUDIO.type){
            val data = ArrayList<AudioSeatModel>()
            audioSeatAdapter.setNewData(data)
        }

    }

    override fun closeRoomed() {
        RoomTimer.timeTickList.remove(this)
    }

    inner class RoomChatItemDecoration : RecyclerView.ItemDecoration() {

        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val margin = DpPxUtil.dip2px(10f)
            outRect.set(0, 0, 0, margin)
        }
    }

    override fun onResume() {
        super.onResume()
        msgVm.isReady = true
    }

    override fun onPause() {
        super.onPause()
        gameDialog?.dismissAllowingStateLoss()
        msgVm.isReady = false
    }

    override fun onTimeCount(time: Int) {

    }


    private fun checkGameVersion(
        gameId: String,
        gamePackageUrl: String,
        gameVersionCode: String
    ): Boolean {
        if (gamePackageUrl.isEmpty() || gameVersionCode.isEmpty()) {
            return false
        }

        val zipNames = gamePackageUrl.split("/")
        val gameName = zipNames.last()
        if (TextUtils.isEmpty(UrlConstant.appGameRootPath) || !File(UrlConstant.appGameRootPath + File.separator + gameId).exists()) {
            downLoadGamePackage(gameId, gamePackageUrl, gameVersionCode, gameName)
            return false
        } else {
            return if (!File(UrlConstant.appGameRootPath + File.separator + gameId + File.separator + gameName).exists()) {
                downLoadGamePackage(gameId, gamePackageUrl, gameVersionCode, gameName)
                false
            } else {
                val localGameVersionCode = SpUtil.readInt(gameId)
                if (localGameVersionCode == 0 || (gameVersionCode.isNotEmpty() && localGameVersionCode < gameVersionCode.toInt())) {
                    downLoadGamePackage(gameId, gamePackageUrl, gameVersionCode, gameName)
                    false
                } else {
                    true
                }
            }
        }

    }

    private fun downLoadGamePackage(
        gameId: String,
        gamePackageUrl: String,
        gameVersionCode: String,
        name: String
    ) {
        val path = UrlConstant.appGameRootPath + File.separator + gameId
        val file = File(path)
        if (file.exists()) {
            file.delete()
        }
        file.mkdirs()

        val task = DownloadTask.Builder(gamePackageUrl, path, name).build()
        task.enqueue(object : DownloadListener {
            override fun taskStart(task: DownloadTask) {}

            override fun connectTrialStart(
                task: DownloadTask,
                requestHeaderFields: MutableMap<String, MutableList<String>>
            ) {
            }

            override fun connectTrialEnd(
                task: DownloadTask,
                responseCode: Int,
                responseHeaderFields: MutableMap<String, MutableList<String>>
            ) {
            }

            override fun downloadFromBeginning(
                task: DownloadTask,
                info: BreakpointInfo,
                cause: ResumeFailedCause
            ) {
            }

            override fun downloadFromBreakpoint(task: DownloadTask, info: BreakpointInfo) {}

            override fun connectStart(
                task: DownloadTask,
                blockIndex: Int,
                requestHeaderFields: MutableMap<String, MutableList<String>>
            ) {
            }

            override fun connectEnd(
                task: DownloadTask,
                blockIndex: Int,
                responseCode: Int,
                responseHeaderFields: MutableMap<String, MutableList<String>>
            ) {
            }

            override fun fetchStart(task: DownloadTask, blockIndex: Int, contentLength: Long) {}

            override fun fetchProgress(task: DownloadTask, blockIndex: Int, increaseBytes: Long) {}

            override fun fetchEnd(task: DownloadTask, blockIndex: Int, contentLength: Long) {}

            override fun taskEnd(task: DownloadTask, cause: EndCause, realCause: Exception?) {
                GlobalScope.launch(Dispatchers.IO) {
                    val packagePath = path + File.separator + name
                    FileUtil.upZipFile(packagePath, path + File.separator)
                    SpUtil.putInt(gameId, gameVersionCode.toInt())
                }
            }

        })
    }

    private val audioSeatAdapter by lazy {
        AudioSeatAdapter()
    }

    fun setAudioRvState(isVisible: Boolean) {
        binding.rvAudio.visibility = if (isVisible) View.VISIBLE else View.GONE
    }
    fun goToTargetRoom(it: String) {
        activity?.let { activity ->
            if (activity is UserRoomActivity) {
                activity.gotoTargetRoom(it)
            }
        }
    }

    inner class GridItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            val margin = DpPxUtil.dip2px(14f)
            val middle = DpPxUtil.dip2px(10f)

            val itemPosition = parent.getChildAdapterPosition(view)
            when (itemPosition % 4) {
                0 -> {
                    outRect.set(margin, 0, middle, 0)
                }

                1 -> {
                    outRect.set(middle, 0, middle, 0)
                }

                2 -> {
                    outRect.set(middle, 0, middle, 0)
                }

                3 -> {
                    outRect.set(middle, 0, margin, 0)
                }
            }
        }
    }


    /***************语音房*******************/
    override fun lockOrUnlockSeat(imAudioModel: IMAudioModel) {
        if (audioSeatAdapter.data.size > imAudioModel.maiIndex - 1) {
            //会偶现空指针
            val view = audioSeatAdapter.getViewByPosition(
                binding.rvAudio,
                imAudioModel.maiIndex - 1,
                R.id.ivImageView
            )
            if (view != null && view is SwagoImageView) {
                if (imAudioModel.action == 1){
                    view.loadImage(R.mipmap.ic_audio_lock)
                }else{
                    view.loadImage(R.mipmap.ic_audio_seat)
                }
            }
            if (imAudioModel.action == 1) {
                audioSeatAdapter.data[imAudioModel.maiIndex - 1].lock_status = 2
            } else {
                audioSeatAdapter.data[imAudioModel.maiIndex - 1].lock_status = 1
            }
        }
    }

    override fun openSeatMic() {

    }

    override fun muteSeatMic() {

    }

    override fun onSeatMic() {

    }
    override fun downSeatMic() {

    }
    override fun changeJiFen(imAudioModel: IMAudioModel) {
        if (audioSeatAdapter.data.size > imAudioModel.maiIndex - 1) {
            audioSeatAdapter.data[imAudioModel.maiIndex-1].voice_jifen = imAudioModel.voice_jifen
            val view = audioSeatAdapter.getViewByPosition(
                binding.rvAudio,
                imAudioModel.maiIndex - 1,
                R.id.tvIntegration
            )
            if (view != null && view is MediumTextView) {
                view.text = imAudioModel.voice_jifen
            }
        }
    }
    override fun clearJiFen() {
        audioSeatAdapter.data.forEach {
            it.voice_jifen = "0"
        }
        audioSeatAdapter.notifyDataSetChanged()
    }
    override fun updateData(audioSeatModel: AudioSeatModel) {
        if (audioSeatAdapter.data.size > audioSeatModel.maiIndex - 1) {
            audioSeatAdapter.data[audioSeatModel.maiIndex-1] = audioSeatModel
            audioSeatAdapter.notifyItemChanged(audioSeatModel.maiIndex-1)
        }
    }

    override fun onAudioVolumeIndication(speakers: Array<out IRtcEngineEventHandler.AudioVolumeInfo>?) {
        super.onAudioVolumeIndication(speakers)
        speakers?.let { data ->
            audioSeatAdapter.data.forEachIndexed { index, audioSeatModel ->
                if (speakers.isEmpty()){
                    if (audioSeatModel.showVoice == 1){
                        audioSeatModel.showVoice = 0
                        val view = audioSeatAdapter.getViewByPosition(
                            binding.rvAudio,
                            audioSeatModel.maiIndex - 1,
                            R.id.ivAudioState
                        )
                        if (view != null) {
                            if (audioSeatModel.voice_status==1){
                                view.visibility = View.GONE
                            }else{
                                view.visibility = View.VISIBLE
                            }
                        }
                    }
                }else{
                    speakers.forEach {
                        if (it.uid == 0){
                            UserInfo.getUserInfo()?.let { userInfo ->
                                if (userInfo.id == audioSeatModel.user_id && it.vad==1){
                                    audioSeatModel.showVoice = 1
                                    val view = audioSeatAdapter.getViewByPosition(
                                        binding.rvAudio,
                                        audioSeatModel.maiIndex - 1,
                                        R.id.ivAudioState
                                    )
                                    if (view != null && view is ImageView) {
                                        view.visibility = View.VISIBLE
                                        view.setImageResource(R.mipmap.live_unmute)
                                    }
                                }
                            }
                        }else{
                            val view = audioSeatAdapter.getViewByPosition(
                                binding.rvAudio,
                                audioSeatModel.maiIndex - 1,
                                R.id.ivAudioState
                            )
                            if (it.uid.toString() == audioSeatModel.user_id){
                                audioSeatModel.showVoice = 1
                                if (view != null && view is ImageView) {
                                    view.visibility = View.VISIBLE
                                    view.setImageResource(R.mipmap.live_unmute)
                                }
                            }else{
                                audioSeatModel.showVoice = 0
                                if (view != null && view is ImageView ) {
                                    if (audioSeatModel.voice_status==1){
                                        view.visibility = View.GONE
                                    }else{
                                        view.visibility = View.VISIBLE
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }

}