package com.swago.room.pk

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.swago.baseswago.baseroom.IRoomInfo
import com.swago.baseswago.baseroom.SwagoRoomManager
import com.swago.baseswago.baseroom.viewmodel.AbsMsgVm
import com.swago.baseswago.im.ImConstant
import com.swago.baseswago.inter.ApiManager
import com.swago.baseswago.model.im.CusNewMsgBean
import com.swago.baseswago.model.im.RoomChatMsgBean
import com.swago.baseswago.model.live.pk.*
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.UserInfo
import com.swago.room.R

class PkVm(application: Application) : AbsMsgVm(application) {
    //接口调用

    /**
     * pK搜索对应主播
     * 默认主播列表 不传参
     */
    val liveModelListLiveData by lazy {
        MutableLiveData<List<PKLiverModel>?>()
    }

    fun getDefault(search_keyword: String = "") {
        requestData2 {
            requestData {
                val data = ApiManager.roomApi.getPKLiverList(search_keyword)
                liveModelListLiveData.value = data.list
            }

            requestError {
                liveModelListLiveData.value = null
            }
        }
    }


    /**
     * 主播发起邀请
     */
    val inviteSuccessLiveData by lazy {
        MutableLiveData<Int>()
    }
    private var inviteCount = 0
    fun invitePeerPK(pk_user_id: String) {
        requestData {
            ApiManager.roomApi.invitePK(pk_user_id)
            inviteSuccessLiveData.value = inviteCount++
        }
    }


    /**
     * 主播主动取消PK
     */
    val cancelPKSuccessLiveData by lazy {
        MutableLiveData<Int>()
    }
    private var cancelCount = 0
    fun cancelPK() {
        requestData {
            ApiManager.roomApi.cancelInvitePK()
            cancelPKSuccessLiveData.value = cancelCount
        }
    }

    /**
     * 主播接受PK邀请
     */
    fun acceptPKOrRefusePK(type: Int, userId: String) {
        requestData {
            ApiManager.roomApi.acceptRefusePK(type, userId)
        }
    }

    /**
     * 获取PK信息接口
     */
    fun getPKInfo(roomId: String) {
        requestData {
            //| 1直播 2正在PK 3赢 4输  5平局 |
            val data = ApiManager.roomApi.getPKInfo(roomId)
            when (data.roomState) {
                1 -> {
                    if (PKStateManager.roomState != PKStateManager.LIVING) {
                        PKStateManager.roomState = PKStateManager.LIVING
                        PKStateManager.pkId = "0"
                        PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                            val stopPKModel = StopPKModel()
                            stopPKModel.roomId = roomId
                            ipkListener.stopPK(stopPKModel)
                        }
                    }
                }
                2 -> {
                    if (PKStateManager.roomState != PKStateManager.PK) {
                        PKStateManager.roomState = PKStateManager.PK
                        PKStateManager.pkId = data.pkId
                        PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                            val startPKModel = StartPKModel()
                            startPKModel.oppositeUserId = data.oppositeUserId
                            startPKModel.roomId = data.roomId
                            startPKModel.pkResultTime = data.pkResultTime
                            startPKModel.destToken = ""
                            startPKModel.sourceToken = ""
                            startPKModel.userId = data.userId
                            startPKModel.oppositeAvatar = data.oppositeAvatar
                            startPKModel.oppositeName = data.oppositeUserName
                            startPKModel.oppositeRoomId = data.oppositeRoomId
                            startPKModel.pkEndTime = startPKModel.pkEndTime
                            startPKModel.pkResultTime = startPKModel.pkResultTime
                            startPKModel.pkId = data.pkId
                            ipkListener.startPK(startPKModel, false)

                            val processPKModel = ProcessPKModel(
                                data.roomId,
                                data.progressValue,
                                data.roomAudienceList,
                                data.oppositeRoomId,
                                data.oppositeProgressValue,
                                data.oppositeRoomAudienceList
                            )
                            ipkListener.processChangePK(processPKModel, false)
                        }
                    }
                }
                3, 4, 5 -> {
                    if (PKStateManager.roomState != PKStateManager.PUNISH) {
                        PKStateManager.roomState = PKStateManager.PUNISH
                        PKStateManager.pkId = data.pkId
                        PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                            val punishPKModel = PunishPKModel()
                            punishPKModel.oppositeUserId = data.oppositeUserId
                            punishPKModel.roomResult = data.roomResult
                            punishPKModel.oppositeName = data.oppositeUserName
                            punishPKModel.oppositeAvatar = data.oppositeAvatar
                            punishPKModel.roomId = data.roomId
                            punishPKModel.oppositeRoomId = data.oppositeRoomId
                            punishPKModel.oppositeRoomResult = data.oppositeRoomResult
                            punishPKModel.pkId = data.pkId
                            punishPKModel.userId = data.userId
                            punishPKModel.pkEndTime = data.pkEndTime
                            punishPKModel.pkResultTime = data.pkResultTime
                            ipkListener.punishPK(punishPKModel, false)

                            val processPKModel = ProcessPKModel(
                                data.roomId,
                                data.progressValue,
                                data.roomAudienceList,
                                data.oppositeRoomId,
                                data.oppositeProgressValue,
                                data.oppositeRoomAudienceList
                            )
                            ipkListener.processChangePK(processPKModel, false)
                        }
                    }
                }
            }
        }
    }


    /**
     * PK确认
     */
    fun pkSure(pkId: String) {
        requestData {
            ApiManager.roomApi.pkSure(pkId)
        }
    }


    val acceptOrRefuseLiveData by lazy {
        MutableLiveData<Int>()
    }
    val acceptFromSenderPKLiveData by lazy {
        MutableLiveData<SendPKModel>()
    }

    override fun receiveMsg() {
        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<SendPKModel>>(ImConstant.pk_send) {
            it.data?.let {
                UserInfo.getUserInfo()?.apply {
                    //1(发起PK) 2(发送方取消PK) 3(拒绝PK) 4(接受PK) 5(自动拒绝PK)
                    when (it.actionType) {
                        1 -> {
                            if (this.id == it.receiverId) {
                                //接收方收到对方发起的PK邀请
                                acceptFromSenderPKLiveData.value = it
                            }
                        }
                        2 -> {
                            if (this.id == it.receiverId) {
                                //接收方收到对方取消PK的邀请
                                Toast.makeText(
                                    AppContext.getContext(),
                                    AppContext.getContext()
                                        .getString(R.string.send_pk_liver_cancel),
                                    Toast.LENGTH_SHORT
                                ).show()
                                acceptOrRefuseLiveData.value = it.actionType
                            }
                        }
                        3, 4, 5 -> {
                            if (this.id == it.senderId) {
                                if (it.actionType == 3 || it.actionType == 5) {
                                    Toast.makeText(
                                        AppContext.getContext(),
                                        AppContext.getContext()
                                            .getString(R.string.peer_liver_refuse_pk),
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }
                                acceptOrRefuseLiveData.value = it.actionType
                            }
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<StartPKModel>>(ImConstant.pk_start) {
            it.data?.let {
                SwagoRoomManager.iRoomInfo?.apply {
                    if (this.getRoomId() == it.roomId) {
                        if (PKStateManager.roomState != PKStateManager.PK) {
                            PKStateManager.roomState = PKStateManager.PK
                            PKStateManager.pkId = it.pkId
                            PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                                ipkListener.startPK(it, true)
                            }
                        }
                    }
                }
            }

        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<ProcessPKModel>>(ImConstant.pk_process) {
            it.data?.let {
                SwagoRoomManager.iRoomInfo?.apply {
                    if (this.getRoomId() == it.roomId) {
                        PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                            ipkListener.processChangePK(it, true)
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<PunishPKModel>>(ImConstant.pk_punish) {
            it.data?.let {
                SwagoRoomManager.iRoomInfo?.apply {
                    if (this.getRoomId() == it.roomId) {
                        if (PKStateManager.roomState != PKStateManager.PUNISH) {
                            PKStateManager.roomState = PKStateManager.PUNISH
                            PKStateManager.pkId = it.pkId
                            PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                                ipkListener.punishPK(it, true)
                            }
                        }
                    }
                }
            }
        }

        imGroupNewMsgListener.handleMsgType<CusNewMsgBean<StopPKModel>>(ImConstant.pk_stop) {
            it.data?.let {
                SwagoRoomManager.iRoomInfo?.apply {
                    if (this.getRoomId() == it.roomId) {
                        if (PKStateManager.roomState != PKStateManager.LIVING) {
                            PKStateManager.roomState = PKStateManager.LIVING
                            PKStateManager.pkId = "0"
                            PKStateManager.pkIPKListenerList.forEach { ipkListener ->
                                ipkListener.stopPK(it)
                            }
                        }
                    }
                }
            }
        }
    }

    override fun changeRoom(iRoomInfo: IRoomInfo) {
    }

    override fun leaveRoom(iRoomInfo: IRoomInfo) {
    }

    override fun joinedRoom(iRoomInfo: IRoomInfo) {
    }

    override fun endRoom(iRoomInfo: IRoomInfo?) {
    }

    override fun closeRoomed() {
    }
}