package com.adealink.weparty.room.micseat.dispatcenter

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.Rlt
import com.adealink.frame.guide.GuideCenter
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.Router
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.dialogfragment.RoomTextActionDialog
import com.adealink.weparty.commonui.toast.ToastCompat
import com.adealink.weparty.commonui.toast.util.showFailedToast
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.module.joinus.JoinUs
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.room.Room
import com.adealink.weparty.module.room.data.MIC_ASSIGN_BY_REMOTE
import com.adealink.weparty.module.room.data.MicIndex
import com.adealink.weparty.module.room.data.isRemoteMute
import com.adealink.weparty.module.room.data.isSeatEmpty
import com.adealink.weparty.module.room.data.micUid
import com.adealink.weparty.room.R
import com.adealink.weparty.room.applymic.ApplyMicDialog
import com.adealink.weparty.room.applymic.viewmodel.ApplyMicViewModel
import com.adealink.weparty.room.chatroom.page.dispatchcenter.DispatchRoomEventViewModel
import com.adealink.weparty.room.data.ApplyMicOnlyHostError
import com.adealink.weparty.room.databinding.FragmentSeatsTemplateDispatchCenterBinding
import com.adealink.weparty.room.guide.RoomGuideType
import com.adealink.weparty.room.invite.InviteMicDialog
import com.adealink.weparty.room.micseat.BaseSeatsTemplate
import com.adealink.weparty.room.micseat.viewmodel.RoomSeatViewModel
import com.adealink.weparty.room.sdk.service.roomService
import com.adealink.weparty.room.viewmodel.RoomViewModelFactory
import com.adealink.weparty.R as APP_R

class DispatchCenterSeatsTemplate :
    BaseSeatsTemplate<DispatchCenterSeatView, RoomSeatViewModel>(R.layout.fragment_seats_template_dispatch_center) {

    override val viewModel: RoomSeatViewModel by viewModels(ownerProducer = { requireActivity() })

    private val eventViewModel by activityViewModels<DispatchRoomEventViewModel>()
    private val applyMicViewModel by viewModels<ApplyMicViewModel> { RoomViewModelFactory() }
    private val binding by viewBinding(FragmentSeatsTemplateDispatchCenterBinding::bind)


    override fun initViews() {
        super.initViews()
        binding.vHowToPlay.onClick {
            GuideCenter.activeGuide(RoomGuideType.HOW_TO_ORDER)
        }
    }

    override fun bindSeatViews() {
        setSeatView(MicIndex(MIC_HOST) {
            getCompatString(APP_R.string.room_mic_host)
        }, binding.micHost)
        setSeatView(MicIndex(MIC_GUEST) {
            getCompatString(APP_R.string.room_mic_guest)
        }, binding.micGuest.apply {

        })

        setSeatView(MicIndex(MIC_1) {
            getCompatString(APP_R.string.room_mic_1)
        }, binding.mic1)
        setSeatView(MicIndex(MIC_2) {
            getCompatString(APP_R.string.room_mic_2)
        }, binding.mic2)
        setSeatView(MicIndex(MIC_3) {
            getCompatString(APP_R.string.room_mic_3)
        }, binding.mic3)
        setSeatView(MicIndex(MIC_4) {
            getCompatString(APP_R.string.room_mic_4)
        }, binding.mic4)
        setSeatView(MicIndex(MIC_5) {
            getCompatString(APP_R.string.room_mic_5)
        }, binding.mic5)
        setSeatView(MicIndex(MIC_6) {
            getCompatString(APP_R.string.room_mic_6)
        }, binding.mic6)
        setSeatView(MicIndex(MIC_7) {
            getCompatString(APP_R.string.room_mic_7)
        }, binding.mic7)
        setSeatView(MicIndex(MIC_8) {
            getCompatString(APP_R.string.room_mic_8)
        }, binding.mic8)
    }

    override fun onSeatClick(seatView: DispatchCenterSeatView) {
        val isLock = seatView.micSeatInfo?.isLocked ?: false
        val isOnMic = roomService.seatController.isOnMic(ProfileModule.getMyUid())
        val onMicIndex = roomService.seatController.getMicSeatIndex(ProfileModule.getMyUid())
        val isMicEmpty = seatView.micSeatInfo == null || seatView.micSeatInfo?.isSeatEmpty() == true

        if (isOnMic) {
            //麦上
            if (onMicIndex == MIC_HOST) {
                //"我"是否是主持人/管理员
                if (isMicEmpty) {
                    //操作空麦位
                    showMicActionList(seatView, mutableListOf<Pair<Int, String>>().apply {
                        if (isLock) {
                            add(Pair(R.id.id_mic_operate_unlock, getCompatString(R.string.room_mic_operate_unlock)))
                        } else {
                            add(Pair(R.id.id_mic_operate_invite, getCompatString(R.string.room_mic_operate_invite)))
                            add(Pair(R.id.id_mic_operate_lock, getCompatString(R.string.room_mic_operate_lock)))
                        }
                    })

                } else if (seatView.micIndex.index == onMicIndex) {
                    //操作自己的麦位
                    showMicActionList(seatView, mutableListOf<Pair<Int, String>>().apply {
                        add(Pair(R.id.id_mic_operate_member_info, getCompatString(R.string.room_mic_operate_member_info)))
                        add(Pair(R.id.id_mic_operate_off, getCompatString(R.string.room_mic_operate_off)))
                    })

                } else {
                    //操作他人麦位
                    showMicActionList(seatView, mutableListOf<Pair<Int, String>>().apply {
                        add(Pair(R.id.id_mic_operate_member_info, getCompatString(R.string.room_mic_operate_member_info)))
                        add(Pair(R.id.id_mic_operate_kick, getCompatString(R.string.room_mic_operate_kick)))
                        add(Pair(R.id.id_mic_operate_lock, getCompatString(R.string.room_mic_operate_lock)))
                        if (seatView.micSeatInfo?.isRemoteMute() == true) {
                            add(Pair(R.id.id_mic_operate_un_mute, getCompatString(R.string.room_mic_operate_un_mute)))
                        } else {
                            add(Pair(R.id.id_mic_operate_mute, getCompatString(R.string.room_mic_operate_mute)))
                        }
                    })
                }
            } else {
                //"我"是普通身份
                if (isMicEmpty) {
                    //Ntd.
                } else if (seatView.micIndex.index == onMicIndex) {
                    //操作自己的麦位
                    showMicActionList(seatView, mutableListOf<Pair<Int, String>>().apply {
                        add(Pair(R.id.id_mic_operate_member_info, getCompatString(R.string.room_mic_operate_member_info)))
                        add(Pair(R.id.id_mic_operate_off, getCompatString(R.string.room_mic_operate_off)))
                    })

                } else {
                    //actionList.add(Pair(R.id.id_mic_operate_member_info, getCompatString(R.string.room_mic_operate_member_info)))
                    Router.getRouterInstance<BottomDialogFragment>(Room.RoomMemberInfo.PATH)?.apply {
                        arguments = Bundle().apply {
                            putString(Room.Common.EXTRA_UID, seatView.micSeatInfo?.micUid())
                        }
                    }?.show(childFragmentManager)
                }
            }
        } else {
            //不在麦位
            if (isLock) {
                return
            }
            if (isMicEmpty) {
                //麦上没人,申请上麦
                if (seatView.micIndex.index == MIC_HOST) {
                    //申请上主持人麦位
                    applyMicViewModel.applyMic(MIC_HOST).observe(viewLifecycleOwner) { rlt ->
                        when(rlt){
                            is Rlt.Failed -> {
                                if (rlt.error is ApplyMicOnlyHostError) {
                                    showToast(rlt.error.msg, style = ToastCompat.Style.WARNING)
                                } else {
                                    showFailedToast(rlt)
                                }
                            }
                            is Rlt.Success -> {
                                //Ntd.
                            }
                        }
                    }
//                    if (eventViewModel.isHost()) {
//
//                    } else {
//                        showToast(R.string.room_request_host_mic_fail_for_no_host_permission)
//                    }
                } else if (seatView.micIndex.index == MIC_GUEST) {
                    //申请上嘉宾麦位
                    ApplyMicDialog().apply {
                        setApplyMic(MIC_GUEST)
                    }.show(childFragmentManager)

                } else {
                    //申请上陪玩师麦位
                    if (ProfileModule.getMyUserInfo()?.isPlaymate() == true) {
                        ApplyMicDialog().apply {
                            setApplyMic(MIC_ASSIGN_BY_REMOTE)
                        }.show(childFragmentManager)
                    } else {
                        showMicActionList(seatView, mutableListOf<Pair<Int, String>>().apply {
                            add(Pair(R.id.id_mic_operate_register_playmate, getCompatString(R.string.room_mic_operate_register_playmate)))
                        })
                    }
                }
                return
            } else {
                //麦上有人
                //actionList.add(Pair(R.id.id_mic_operate_member_info, getCompatString(R.string.room_mic_operate_member_info)))
                Router.getRouterInstance<BottomDialogFragment>(Room.RoomMemberInfo.PATH)?.apply {
                    arguments = Bundle().apply {
                        putString(Room.Common.EXTRA_UID, seatView.micSeatInfo?.micUid())
                    }
                }?.show(childFragmentManager)
            }

        }
    }

    private fun showMicActionList(seatView: DispatchCenterSeatView, actionList: List<Pair<Int, String>>) {
        RoomTextActionDialog
            .Builder()
            .addTitle(
                seatView.micIndex.micName.invoke()
            ).apply {
                for (action in actionList) {
                    addItem(action.first, action.second)
                }
            }.actionListener(object : RoomTextActionDialog.RoomTextActionListener {
                override fun onActionClick(viewId: Int) {
                    when (viewId) {
                        R.id.id_mic_operate_invite -> {
                            val inviteIndex = when (seatView.micIndex.index) {
                                in MIC_1..MIC_8 -> {
                                    MIC_ASSIGN_BY_REMOTE
                                }

                                MIC_GUEST -> {
                                    MIC_GUEST
                                }

                                else -> {
                                    return
                                }
                            }
                            InviteMicDialog().apply {
                                inviteMicIndex(inviteIndex)
                                filterPlaymate(seatView.micIndex.index != MIC_HOST && seatView.micIndex.index != MIC_GUEST)
                                enableFilter(seatView.micIndex.index != MIC_HOST && seatView.micIndex.index != MIC_GUEST)
                            }.show(childFragmentManager)
                        }

                        R.id.id_mic_operate_on -> {
                            val reqMicIndex = when (seatView.micIndex.index) {
                                in MIC_1..MIC_8 -> {
                                    MIC_ASSIGN_BY_REMOTE
                                }

                                MIC_GUEST -> {
                                    MIC_GUEST
                                }

                                else -> {
                                    return
                                }
                            }
                            ApplyMicDialog().apply {
                                setApplyMic(reqMicIndex)
                            }.show(childFragmentManager)
                        }

                        R.id.id_mic_operate_off -> {
                            roomService.seatController.micOff(
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }

                        R.id.id_mic_operate_kick -> {
                            val seatInfo = seatView.micSeatInfo
                            if (seatInfo == null || seatInfo.isSeatEmpty() || seatInfo.userInfo.userID.isNullOrEmpty()) {
                                return
                            }
                            roomService.seatController.kick(
                                seatInfo.userInfo.userID,
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }

                        R.id.id_mic_operate_member_info -> {
                            Router.getRouterInstance<BottomDialogFragment>(Room.RoomMemberInfo.PATH)?.apply {
                                arguments = Bundle().apply {
                                    putString(Room.Common.EXTRA_UID, seatView.micSeatInfo?.micUid())
                                }
                            }?.show(childFragmentManager)
                        }

                        R.id.id_mic_operate_lock -> {
                            roomService.seatController.micLock(
                                seatView.micIndex.index,
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }

                        R.id.id_mic_operate_unlock -> {
                            roomService.seatController.micUnLock(
                                seatView.micIndex.index,
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }


                        R.id.id_mic_operate_mute -> {
                            val seatInfo = seatView.micSeatInfo
                            if (seatInfo == null || seatInfo.isSeatEmpty() || seatInfo.userInfo.userID.isNullOrEmpty()) {
                                return
                            }
                            roomService.seatController.micMute(
                                seatInfo.userInfo.userID,
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }

                        R.id.id_mic_operate_un_mute -> {
                            val seatInfo = seatView.micSeatInfo
                            if (seatInfo == null || seatInfo.isSeatEmpty() || seatInfo.userInfo.userID.isNullOrEmpty()) {
                                return
                            }
                            roomService.seatController.micUnMute(
                                seatInfo.userInfo.userID,
                                onSuccess = {},
                                onFail = {
                                    showToast(it)
                                }
                            )
                        }

                        R.id.id_mic_operate_register_playmate -> {
                            activity?.let { act ->
                                Router.build(act, JoinUs.JoinUs.PATH).start()
                            }
                        }
                    }
                }
            })
            .build().show(childFragmentManager)
    }

    override fun loadData() {
        super.loadData()
        //获取专属麦位配置信息
    }

    override fun observeViewModel() {
        super.observeViewModel()
    }

    companion object {
        private const val TAG = "DefaultSeatsTemplate"
    }

}