package com.swago.room.vm

import android.app.Application
import android.widget.Toast
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoleType
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.baseroom.viewmodel.AbsMsgVm
import com.swago.baseswago.im.IRoomChat
import com.swago.baseswago.im.ImConstant.anchor_close_room
import com.swago.baseswago.im.ImConstant.cancel_forbid_speak
import com.swago.baseswago.im.ImConstant.delete_room_admin
import com.swago.baseswago.im.ImConstant.follow_anchor_success
import com.swago.baseswago.im.ImConstant.forbid_speak
import com.swago.baseswago.im.ImConstant.force_close_live_room
import com.swago.baseswago.im.ImConstant.game_win_big_prize
import com.swago.baseswago.im.ImConstant.invite_user_on_mic
import com.swago.baseswago.im.ImConstant.jifen_change
import com.swago.baseswago.im.ImConstant.jifen_clear
import com.swago.baseswago.im.ImConstant.lock_un_lock_mic
import com.swago.baseswago.im.ImConstant.lucky_gift
import com.swago.baseswago.im.ImConstant.lucky_gift_prize
import com.swago.baseswago.im.ImConstant.multi_jifen_change
import com.swago.baseswago.im.ImConstant.multi_send_gift
import com.swago.baseswago.im.ImConstant.notice_update
import com.swago.baseswago.im.ImConstant.open_close_mic
import com.swago.baseswago.im.ImConstant.red_envelope
import com.swago.baseswago.im.ImConstant.red_envelope_broadcast
import com.swago.baseswago.im.ImConstant.remove_room
import com.swago.baseswago.im.ImConstant.room_chat_text
import com.swago.baseswago.im.ImConstant.room_dan_mu
import com.swago.baseswago.im.ImConstant.set_room_admin
import com.swago.baseswago.im.ImConstant.svg_gift
import com.swago.baseswago.im.ImConstant.update_audience
import com.swago.baseswago.im.ImConstant.update_mic_list_data
import com.swago.baseswago.im.ImConstant.user_agree_invite_by_anchor
import com.swago.baseswago.im.ImConstant.user_down_mic
import com.swago.baseswago.im.ImConstant.user_exit_room
import com.swago.baseswago.im.ImConstant.user_join_room
import com.swago.baseswago.im.ImConstant.user_refuse_invite_by_anchor
import com.swago.baseswago.model.RedEnvelope
import com.swago.baseswago.model.im.*
import com.swago.baseswago.model.live.ForceCloseModel
import com.swago.baseswago.model.live.ReceiveModel
import com.swago.baseswago.model.im.GamePrize
import com.swago.baseswago.model.live.RoomUserChangeModel
import com.swago.baseswago.model.live.RoomUserModel
import com.swago.baseswago.model.live.audio.*
import com.swago.baseswago.model.live.gift.IMGiftModel
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.UserInfo
import com.swago.room.audio.AudioRoomManager
import com.swago.room.audio.IAudioRoomListener
import com.swago.room.bean.UserRoomModel
import com.swago.room.manager.JoinRoomManager
import java.util.concurrent.CopyOnWriteArrayList

/**
 *@date 2021/10/10 10:00
 *description:
 */
class MsgVm(application: Application) : AbsMsgVm(application) {

    var isReady = false

    var newChatMsgFun: ((iRoomChat: IRoomChat?) -> Unit)? = null

    var anchorRoomClosed: ((data: AnchorRoomClosedBean?) -> Unit)? = null

    //强制关播
    var forceCloseAnchorRoom: ((forceCloseModel: ForceCloseModel) -> Unit)? = null

    var inComeChange: ((income: String) -> Unit)? = null

    var updateHotValue: ((hotValue: String) -> Unit)? = null

    var kickFromRoom: (() -> Unit)? = null

    var forbidSpeakOrCancel: ((cancel: Boolean) -> Unit)? = null

    var addAudioGiftAnimFun: ((audioSendGiftModel:AudioSendGiftModel) -> Unit)? = null

    var updateUserRoom: ((data: ArrayList<RoomUserModel.ListBean>, count: Int) -> Unit)? = null

    var newRedEnvelopeCome: ((redEnvelope: RedEnvelope) -> Unit)? = null

    var multiJiFenChangeFun:((data: List<Jifen>) -> Unit)? = null

    //设置或者取消房间管理员
    var setOrDeleteRoomAdmin: ((isSet: Int) -> Unit)? = null

    //红包传送门
    var openRedEnvelopPortal: ((redEnvelope: RedEnvelope) -> Unit)? = null

    /**
     * 播放svg动画
     */
    var playSvgUrl: ((data: IMGiftModel) -> Unit)? = null

    /**
     * 礼物飘条
     */
    var waftFun: ((data: IPiaoTiao) -> Unit)? = null

    /**
     * 礼物弹道展示
     */
    var showGiftDanDao: ((data: IMGiftModel) -> Unit)? = null

    /**
     * 被邀请的用户展示被邀请弹窗
     */
    var openInviteByAnchorFun: ((imAudioModel: IMAudioModel) -> Unit)? = null

    /**
     * 更新语音房公告
     */
    var updateAudioNotice:((notice:String)->Unit)? = null

    /**
     * 弹幕
     */
    var addDanMuFun:((danMuBean:DanMuBean)->Unit)? = null

    /**
     * 红包飘条
     */
    var addHongbaoPiaotiao:((redEnvelop:RedEnvelope)->Unit)? = null

    val joinRoomManager by lazy {
        JoinRoomManager()
    }

    override fun receiveMsg() {
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<RoomChatMsgBean>>(room_chat_text) {
            if (it.getGroupId() == (SwagoRoomManager.iRoomInfo?.getRoomGroupId() ?: "")) {
                it.data?.let {
                    newChatMsgFun?.invoke(it)
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<UserJoinRoomBean>>(user_join_room) {
            if (isReady && it.getGroupId() == (SwagoRoomManager.iRoomInfo?.getRoomGroupId()
                    ?: "")
            ) {
                if (SwagoRoomManager.roleType == RoleType.user || it.data?.senderCode != UserInfo.getUserInfo()?.user_account) {
                    it.data?.let {
                        newChatMsgFun?.invoke(it)
                        updateHotValue?.invoke(it.hotValue)
                        joinRoomManager.addJoinRoomData(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<UserJoinRoomBean>>(user_exit_room) {
            if (it.getGroupId() == (SwagoRoomManager.iRoomInfo?.getRoomGroupId() ?: "")) {
                if (SwagoRoomManager.roleType == RoleType.user || it.data?.senderCode != UserInfo.getUserInfo()?.user_account) {
                    it.data?.let {
                        updateHotValue?.invoke(it.hotValue)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<RoomUserChangeModel>>(update_audience) {
            it.data?.let { model ->
                if (model.room_id == (SwagoRoomManager.iRoomInfo?.getRoomId() ?: "")) {
                    updateUserRoom?.invoke(model.users, model.count)
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<AnchorRoomClosedBean>>(anchor_close_room) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                if (iRoomInfo.getRoomId() == (it.data?.roomId ?: "")) {
                    anchorRoomClosed?.invoke(it.data)
                }
            }
        }

        //后台强制关播
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ForceCloseModel>>(force_close_live_room) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (iRoomInfo.getRoomId() == (it.roomId)) {
                        forceCloseAnchorRoom?.invoke(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMGiftModel>>(svg_gift) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                if (isReady) {
                    it.data?.let {
                        if (iRoomInfo.getRoomId() == (it.roomId ?: "")) {
                            playSvgUrl?.invoke(it)
                            inComeChange?.invoke(it.incomeCount)
                        }
                        waftFun?.invoke(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMGiftModel>>(lucky_gift) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                if (isReady) {
                    it.data?.let {
                        if (iRoomInfo.getRoomId() == (it.roomId ?: "")) {
                            UserInfo.getUserInfo()?.let { userInfoModel ->
                                if (userInfoModel.id != it.senderId) {
                                    showGiftDanDao?.invoke(it)
                                    inComeChange?.invoke(it.incomeCount)
                                }
                            }
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMGiftModel>>(lucky_gift_prize) {
            if (isReady) {
                it.data?.let {
                    if (it.multiple >= 500) {
                        waftFun?.invoke(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<FollowSuccessMsgBean>>(
            follow_anchor_success
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                if (isReady) {
                    it.data?.let {
                        if (iRoomInfo.getRoomId() == (it.roomId ?: "")) {
                            newChatMsgFun?.invoke(it)
                        }
                    }
                }
            }
        }


        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ReceiveModel>>(remove_room) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                UserInfo.getUserInfo()?.let { userInfo ->
                    it.data?.let {
                        if (it.roomId == iRoomInfo.getRoomId() && it.receiverId == userInfo.id) {
                            kickFromRoom?.invoke()
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ReceiveModel>>(forbid_speak) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                UserInfo.getUserInfo()?.let { userInfo ->
                    it.data?.let {
                        if (it.roomId == iRoomInfo.getRoomId() && it.receiverId == userInfo.id) {
                            forbidSpeakOrCancel?.invoke(true)
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ReceiveModel>>(cancel_forbid_speak) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                UserInfo.getUserInfo()?.let { userInfo ->
                    it.data?.let {
                        if (it.roomId == iRoomInfo.getRoomId() && it.receiverId == userInfo.id) {
                            forbidSpeakOrCancel?.invoke(false)
                        }
                    }
                }
            }
        }

        //红包
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<RedEnvelope>>(red_envelope) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId()) {
                        newRedEnvelopeCome?.invoke(it)
                        newChatMsgFun?.invoke(it)
                        it.bigNotice = 0
                        addHongbaoPiaotiao?.invoke(it)
                    }
                }
            }
        }

        //红包全局通知
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<RedEnvelope>>(red_envelope_broadcast) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (isReady && it.roomId != iRoomInfo.getRoomId()) {
                        //其他直播间用户收到这个全局红包的通知触发弹窗
                        openRedEnvelopPortal?.invoke(it)
                        it.bigNotice = 1
                        addHongbaoPiaotiao?.invoke(it)
                    }
                }
            }
        }
        //游戏中奖飘条
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<GamePrize>>(game_win_big_prize) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (isReady) {
                        //游戏飘条
                        waftFun?.invoke(it)
                    }
                }
            }
        }

        //设置管理员
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<BecomeManagerBean>>(set_room_admin) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                UserInfo.getUserInfo()?.let { userInfo ->
                    it.data?.let {
                        if (it.roomId == iRoomInfo.getRoomId()) {
                            if (it.receiverId == userInfo.id) {
                                setOrDeleteRoomAdmin?.invoke(1)
                            }
                            newChatMsgFun?.invoke(it)
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ReceiveModel>>(delete_room_admin) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                UserInfo.getUserInfo()?.let { userInfo ->
                    it.data?.let {
                        if (it.roomId == iRoomInfo.getRoomId() && it.receiverId == userInfo.id) {
                            setOrDeleteRoomAdmin?.invoke(0)
                        }
                    }
                }
            }
        }


        /**
         * 弹幕
         */
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<DanMuBean>>(
            room_dan_mu
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId()) {
                        addDanMuFun?.invoke(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(lock_un_lock_mic) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        AudioRoomManager.dispatchLockOrUnlockSeat(it)
                    }
                }
            }
        }

        //邀请用户上麦
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(invite_user_on_mic) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.receiverId) {
                                //被邀请的用户弹窗
                                openInviteByAnchorFun?.invoke(it)
                            }
                        }
                    }
                }
            }
        }


        //用户同意主播邀请
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(user_agree_invite_by_anchor) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.receiverId) {
                                Toast.makeText(
                                    AppContext.getContext(),
                                    "用户同意了您的邀请",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                }
            }
        }

        //用户拒绝主播邀请
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            user_refuse_invite_by_anchor
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.receiverId) {
                                //被邀请的用户弹窗
                                Toast.makeText(
                                    AppContext.getContext(),
                                    "用户拒绝了您的邀请",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                }
            }
        }

        //麦位数据更新
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioSeatUpdateModel>>(
            update_mic_list_data
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        //列表有数据更新
                        val audioSeatModel = AudioSeatModel(
                            it.maiSeatInfo.userName,
                            it.maiSeatInfo.userAvatar,
                            it.maiSeatInfo.userId,
                            it.maiSeatInfo.maiStatus,
                            it.maiSeatInfo.lock,
                            it.maiSeatInfo.integration,
                            it.maiSeatInfo.voiceUserId,
                            it.maiSeatInfo.maiIndex,
                            0
                        )
                        AudioRoomManager.dispatchUpdateData(audioSeatModel)
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.maiSeatInfo.userId) {
                                AudioRoomManager.isOnMic = true
                                AudioRoomManager.maiIndex = it.maiSeatInfo.maiIndex
                            }
                        }
                    }
                }
            }
        }

        //用户被主播下麦
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            user_down_mic
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.receiverId) {
                                AudioRoomManager.resetData()
                                AudioRoomManager.dispatchDownSeatMic()
                            }
                        }
                    }
                }
            }
        }

        //闭麦和开麦
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            open_close_mic
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        UserInfo.getUserInfo()?.let { userInfoModel ->
                            if (userInfoModel.id == it.receiverId) {
                                if (it.action == 1) {
                                    AudioRoomManager.dispatchOpenSeatMic()
                                } else if (it.action == 2) {
                                    AudioRoomManager.dispatchMuteSeatMic()
                                }
                            }
                        }
                    }
                }
            }
        }


        /**
         * 积分清零
         */
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            jifen_clear
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        AudioRoomManager.dispatchClearJiFen()
                    }
                }
            }
        }

        /**
         * 积分变更
         */
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            jifen_change
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        AudioRoomManager.dispatchChangeJiFen(it)
                    }
                }
            }
        }

        /**
         * 公告更新
         */
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<IMAudioModel>>(
            notice_update
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        updateAudioNotice?.invoke(it.notice)
                        SwagoRoomManager.iRoomInfo?.let {iRoomInfo ->
                            (iRoomInfo as UserRoomModel).roomModel?.yuying_notice_content = it.notice
                        }
                    }
                }
            }
        }

        /**
         * 多人送礼
         */
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<AudioSendGiftModel>>(
            multi_send_gift
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        if (it.isSvga == 1){
                            val imGiftModel = IMGiftModel()
                            imGiftModel.svga = it.svgaUrl
                            playSvgUrl?.invoke(imGiftModel)
                        }
                        //多人送礼动画
                        addAudioGiftAnimFun?.invoke(it)
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<MultiJiFenModel>>(
            multi_jifen_change
        ) {
            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                it.data?.let {
                    if (it.roomId == iRoomInfo.getRoomId() && it.roomSessionId == iRoomInfo.getBroadcastId()) {
                        multiJiFenChangeFun?.invoke(it.jifenList)
                    }
                }
            }
        }

    }


    override fun changeRoom(iRoomInfo: IRoomInfo) {

    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {

    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {

    }

    override fun closeRoomed() {

    }
}