package com.swago.room.vm

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.RoleType
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.baseroom.viewmodel.AbsRoomVm
import com.swago.baseswago.http.SwagoException
import com.swago.baseswago.inter.ApiManager
import com.swago.baseswago.model.MomentModel
import com.swago.baseswago.model.RedEnvelope
import com.swago.baseswago.model.im.AnchorRoomClosedBean
import com.swago.baseswago.model.live.*
import com.swago.baseswago.util.*
import com.swago.room.bean.UserRoomModel
import com.swago.room.user.UserRoomActivity

/**
 *@date 2021/10/10 09:59
 *description:
 */
class RoomVm(application: Application) : AbsRoomVm(application) {

    //当前选中的游戏
    var currentGameType = 1

    val roomClosedLiveData by lazy {
        MutableLiveData<AnchorRoomClosedBean>()
    }

    val anchorCloseLiveData by lazy {
        MutableLiveData<AnchorClosedModel>()
    }

    //显示禁播时长弹窗
    var showBannerTime:((time:Long)->Unit)? = null

    override fun afterRoomChange(
        roleType: Int,
        iRoomInfo: IRoomInfo,
        callback: (canJoinRoom: Boolean) -> Unit
    ) {
        if (roleType == RoleType.user) {
            doUserRoomChange(roleType, iRoomInfo, callback)
        } else if (roleType == RoleType.anchor) {
            doAnchorRoomChange(roleType, iRoomInfo, callback)
        }
    }

    private fun doUserRoomChange(
        roleType: Int,
        iRoomInfo: IRoomInfo,
        callback: (canJoinRoom: Boolean) -> Unit
    ) {
        requestData2 {
            requestData {
                val roomModel = ApiManager.roomApi.joinRoom(iRoomInfo.getRoomId())
                val roomInfo = iRoomInfo as UserRoomModel
                roomInfo.roomModel = roomModel
                callback.invoke(true)
            }

            requestError {
                if (it is SwagoException) {
                    if (it.code == 504) {
                        if (SwagoRoomManager.iRoomInfo == null){
                            SwagoRoomManager.closeRoom()
                        }else{
                            SwagoRoomManager.iRoomInfo?.let { iRoomInfo ->
                                if (iRoomInfo is UserRoomModel){
                                    val anchorRoomClosedBean = AnchorRoomClosedBean()
                                    anchorRoomClosedBean.senderName = iRoomInfo.momentModel?.user_name
                                    anchorRoomClosedBean.userAvatar = iRoomInfo.momentModel?.user_head_img_url
                                    anchorRoomClosedBean.userCode = iRoomInfo.momentModel?.user_account
                                    roomClosedLiveData.value = anchorRoomClosedBean
                                }
                            }
                        }
                    } else {
                        Toast.makeText(AppContext.getContext(), it.message, Toast.LENGTH_SHORT)
                            .show()
                        SwagoRoomManager.closeRoom()
                        callback.invoke(false)
                    }
                } else {
                    callback.invoke(false)
                    SwagoRoomManager.closeRoom()
                    Toast.makeText(AppContext.getContext(), it.message, Toast.LENGTH_SHORT).show()
                }

            }

        }
    }

    private fun doAnchorRoomChange(
        roleType: Int,
        iRoomInfo: IRoomInfo,
        callback: (canJoinRoom: Boolean) -> Unit
    ) {
        requestData2(false) {
            requestData {
                SwagoLoading.showLoadingDialog(ActivityManagerUtil.get().currentActivity())
                val roomInfo = iRoomInfo as UserRoomModel
                val roomModel = ApiManager.roomApi.startLive(currentGameType)
                roomInfo.roomModel = roomModel
                callback.invoke(true)
                SwagoLoading.cancelLoadingDialog()
            }

            requestError {
                SwagoLoading.cancelLoadingDialog()
                if (it is SwagoException) {
                    when(it.code){
                        545 -> {
                            showBannerTime?.invoke((it.message?:"0").toLong())
                        }
                        else -> {
                            Toast.makeText(AppContext.getContext(), it.message, Toast.LENGTH_SHORT).show()
                            SwagoRoomManager.closeRoom()
                            callback.invoke(false)
                        }
                    }
                }else{
                    SwagoRoomManager.closeRoom()
                    callback.invoke(false)
                }
            }

        }
    }

    //观众列表
    val roomUserDataLiveData by lazy {
        MutableLiveData<RoomUserModel?>()
    }

    fun loadRoomData(page:Int=1) {
        requestData2 {
            requestData {
                SwagoRoomManager.iRoomInfo?.let {
                    val data = ApiManager.roomApi.getRoomUser(it.getRoomId(),page)
                    roomUserDataLiveData.value = data
                }
            }

            requestError {
                roomUserDataLiveData.value = null
            }
        }
    }

    //观众列表弹窗
    val roomUserListDialogLiveData by lazy {
        MutableLiveData<RoomUserModel?>()
    }

    fun loadUserInDialogData(page:Int=1) {
        requestData2 {
            requestData {
                SwagoRoomManager.iRoomInfo?.let {
                    val data = ApiManager.roomApi.getRoomUser(it.getRoomId(),page)
                    roomUserListDialogLiveData.value = data
                }
            }

            requestError {
                roomUserListDialogLiveData.value = null
            }
        }
    }





    override fun leaveRoom(iRoomInfo: IRoomInfo) {
        leaveCurrentRoom(iRoomInfo)
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {}

    override fun endRoom(iRoomInfo: IRoomInfo?) {

    }

    override fun closeRoomed() {
        when (SwagoRoomManager.roleType) {
            RoleType.anchor -> {
                if (SwagoRoomManager.iRoomInfo == null) {
                    ActivityManagerUtil.get().currentActivity().finish()
                } else {
                    requestData2(false) {
                        requestData {
                            SwagoLoading.showLoadingDialog(
                                ActivityManagerUtil.get().currentActivity()
                            )
                            val data = ApiManager.roomApi.closeLive()
                            SwagoLoading.cancelLoadingDialog()
                            anchorCloseLiveData.value = data
                        }

                        requestError {
                            ActivityManagerUtil.get().currentActivity().finish()
                        }
                    }
                }
            }

            RoleType.user -> {
                SwagoRoomManager.iRoomInfo?.let {
                    leaveCurrentRoom(it)
                }
                if (ActivityManagerUtil.get().currentActivity() is UserRoomActivity) {
                    ActivityManagerUtil.get().finishTopActivity()
                }
            }
        }
    }

    private fun leaveCurrentRoom(iRoomInfo: IRoomInfo) {
        requestData2(false) {
            requestData {
                ApiManager.roomApi.leaveRoom(iRoomInfo.getRoomId())
            }

            requestError {

            }
        }
    }

    val roomAuthLiveData by lazy {
        MutableLiveData<RoomAuthModel>()
    }

    fun getUserRoomAuth(userId: String, roomId: String) {
        requestData {
            roomAuthLiveData.value = ApiManager.roomApi.getUserRoomAuth(roomId,userId)
        }
    }


    /***
     * 直播间配置
     */
    val roomConfigLiveData by lazy {
        MutableLiveData<RoomConfig>()
    }
    fun getRoomConfig(){
        requestData {
            roomConfigLiveData.value = ApiManager.roomApi.getRoomConfig()
        }
    }

    /**
     * 主播
     */
    val momentModelLiveData by lazy {
        MutableLiveData<MomentModel>()
    }
    fun getMomentModel(anchorId: String) {
        requestData {
            SwagoRoomManager.iRoomInfo?.let {
                momentModelLiveData.value  = ApiManager.roomApi.getMomentModel(anchorId)
            }
        }
    }

}