using System;
using LitJson;
using rtc;
using SC.XR.Unity;
using SC.XR.Unity.Module_InputSystem;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using XRTool.Util;
using static ScenesManager;

public class RoomMain : RemoteSingleton<RoomMain>
{
    public static string NOUSER="nouser";
    public  bool isSendAudio = true;
    public  bool isSendVideo = true;
    public  bool isCloseView = true;

    public MeshRenderer bigView;

    public GameObject audioOpenBtn;
    public GameObject audioCloseBtn;

    public GameObject videoOpenBtn;
    public GameObject videoCloseBtn;

    public GameObject changeViewOpenBtn;
    public GameObject changeViewCloseBtn;
    public string userId;

    public TextMeshProUGUI TitleRoomName;
    public TextMeshProUGUI TitleRoomNum;
    public TextMeshProUGUI TitleRoomPeopleCount;

    public SCButton heidMainScreenBtn;
    public ManipulationHandler manipulationHandler;

    public MySlider slider;

    public RawImage agoraRawImage;

    public Button InviteBtn;
    private IQueueSystem mQueueSystem;
    public override void Awake()
    {
        base.Awake();
        //WSHandler.Rtc.onRtcState -= onRtcState;
        //WSHandler.Rtc.onRtcState += onRtcState;
        //WSHandler.Rtc.OnChangeOwner += ChangeOwner;
        if (manipulationHandler)
        {
            manipulationHandler.Target = ShowRoom.Instance.transform;
        }
        heidMainScreenBtn.onClick.AddListener(ShowRoom.Instance.HideMainScreen);
        slider.beiginDrag = OnSliderBeginDrag;
        slider.endDrag = OnSliderEndDrag;

        InviteBtn.onClick.AddListener(()=>{
            if (ShowRoom.Instance)
            {
                ShowRoom.Instance.window[4].SetActive(true);
                if (InviteDlg.Instance)
                {
                    InviteDlg.Instance.ShowHistory();
                }
            }
        });
    }



    private void ChangeOwner(JsonData data)
    {
        string peerId = data["data"]["peerId"].ToString();
        string nickName = data["data"]["nickName"].ToString();
        string isCreator = data["data"]["isCreator"].ToString();
        if (peerId == UserInfo.UnionId && isCreator == "1")
        {
            RoomMainInfo.isCreator = "0";
            RoomMainInfo.RoomOwner = "用户" + nickName + "的房间";
            if (FileList.Instance && RoomFile.Instance)
            {
                if (FileList.Instance.transform.childCount > 0)
                {
                    RoomFile.Instance.ShowClearBtn();
                }
            }
        }
        TitleRoomName.text = "用户" + nickName + "的房间";
        TitleRoomPeopleCount.text = "房间人数:" + RoomMainInfo.roomPeopleNum + "/" + 10;
        RoomOtherUser.Instance.UpdateList();
    }

    /// <summary>
    /// 进度条开始拖动
    /// </summary>
    public void OnSliderBeginDrag()
    {
    }
    /// <summary>
    ///结束
    /// </summary>
    public void OnSliderEndDrag()
    {
        float num = float.Parse(slider.value.ToString("f2"));
        //Debug.Log(num + "AAA");
        RemoteRtc.Instance.setVolume(num);
    }

    public void OnDestroy()
    {
        WSHandler.Rtc.OnChangeOwner -= ChangeOwner;
        WSHandler.Rtc.onRtcState -= onRtcState;

    }

    public override void initShow()
    {
        base.initShow();

        if (PopPeerView.Instance)
        {
            PopPeerView.Instance.list.SetParent(ShowRoom.Instance.transform);
        }
        if (PopUpInfo.Instance)
        {
            PopUpInfo.Instance.transform.SetParent(ShowRoom.Instance.transform);
            PopUpInfo.Instance.HideNetErrorPanel();
        }

        if (ShowRoom.Instance)
        {
            ShowRoom.Instance.transform.position = new Vector3(-0.2f, 0, 0.3f); // 要设置ShowRoom LocalPosition为0,因为Canvas PosZ=0.3,所以为0.3f
            ShowRoom.Instance.transform.eulerAngles = new Vector3(0, -30, 0);
        }

        if (PopCall.Instance)
        {
            PopCall.Instance.gameObject.SetActive(true);
        }

        setBigView(RemoteRtc.Instance.NoUser, NOUSER);

        if (!string.IsNullOrEmpty(RoomMainInfo.RoomOwner))
        {
            TitleRoomName.text = RoomMainInfo.RoomOwner;
        }
        TitleRoomPeopleCount.text ="房间人数:"+ RoomMainInfo.roomPeopleNum + "/"+ RoomMainInfo.roomMaxPeopleNum;
        TitleRoomNum.text ="房间号:"+ RoomMainInfo.roomNum;

        //AgoraVideoAudioManager.Instance.SetChinnelName(RoomMainInfo.roomNum);
        //AgoraVideoAudioManager.Instance.JoinChannel();

        isSendAudio = CustomInfo.isSendAudio;
        isSendVideo = CustomInfo.isSendVideo;
        isCloseView = CustomInfo.isCloseView;
        
        sendAudio(isSendAudio);
        sendVideo(isSendAudio);
        //if(isCloseView)
        //{
        RemoteRtc.Instance.changeViewOpen();
         //   isCloseView = false;
        //}
        //else
        //{
          //  RemoteRtc.Instance.changeViewClose();
            isCloseView = true;
      //  }
        change();
    }
    bool isStartBigView = true;
    public void setBigView(Texture tex,string id)
    {
        if (id!= NOUSER)
        {
            CustomPeer cPeer = (CustomPeer)RemoteRtc.Instance.customPeerList.getPeer(id);
            if (cPeer.isCloseVideo||!cPeer.isVideo)
            {
                tex = RemoteRtc.Instance.NoView;
               
            }
            RoomOtherUser.ShowAction?.Invoke(id);
        }
        userId = id;
        if(isStartBigView)
        {
            isStartBigView = false;
            bigView.material.mainTexture = tex;
        }
      

    }

    private string dcetype;
    private void onRtcState(string str)
    {
        if (!string.IsNullOrEmpty(RoomMainInfo.RoomOwner))
        {
            TitleRoomName.text = RoomMainInfo.RoomOwner;
        }
        TitleRoomPeopleCount.text = "房间人数:" + RoomMainInfo.roomPeopleNum + "/" + RoomMainInfo.roomMaxPeopleNum;
        TitleRoomNum.text = "房间号:" + RoomMainInfo.roomNum;
        //  change();
        switch(str)
        {
            case "closeProducer":
                if (dcetype == "video")
                {
                    RemoteRtc.Instance.me.cIdV = "";
                }
                else
                {
                    RemoteRtc.Instance.me.cIdA = "";
                }
                break;
        }
    }

    //private void OnEnable()
    //{
    //    AgoraVideoAudioManager.Instance.JoinChannel();
    //}

    void change()
    {
        if (isSendVideo)
        {
            videoOpenBtn.SetActive(false);
            videoCloseBtn.SetActive(true);
        }
        else
        {
            videoOpenBtn.SetActive(true);
            videoCloseBtn.SetActive(false);
        }

        if (isSendAudio)
        {
            audioOpenBtn.SetActive(false);
            audioCloseBtn.SetActive(true);
        }
        else
        {
            audioOpenBtn.SetActive(true);
            audioCloseBtn.SetActive(false);
        }

        if (isCloseView)
        {
            changeViewOpenBtn.SetActive(false);
          //  changeViewCloseBtn.SetActive(true);
        }
        else
        {
          //  changeViewOpenBtn.SetActive(true);
            changeViewCloseBtn.SetActive(false);
        }
    }

    public void LeaveRoom()
    {
        if (PopPeerView.Instance)
        {
            PopPeerView.Instance.list.SetParent(PopPublic.Instance.transform);
            PopPeerView.Instance.list.localPosition = new Vector3(0, 0, 0);
            PopPeerView.Instance.list.localEulerAngles = new Vector3(0, 0, 0);
        }
        if (PopUpInfo.Instance)
        {
            PopUpInfo.Instance.transform.SetParent(PopPublic.Instance.transform);
            PopUpInfo.Instance.transform.localPosition = new Vector3(0, 0, 0);
            PopUpInfo.Instance.transform.localEulerAngles = new Vector3(0, 0, 0);
        }
        //sendAudio(false);
        //sendVideo(false);
        WSHandler.roomRtcCloes();
        WSHandler.Office.ChangeUserType(UserInfo.BusyType);
        ScenesManager.Instance.showWindow(SceneType.ShowChoose);
        if (InviteDlg.Instance)
        {
            InviteDlg.Instance.InvitingUnionIdList.Clear();
        }
        if (ArrowList.Instance)
        {
            ArrowList.Instance.DeleteAll();
        }
        if (RoomFile.Instance)
        {
            RoomFile.Instance.ClearAllFileItem();
        }
        if (PrintscreenList.Instance)
        {
            PrintscreenList.Instance.DeleteAll();
        }
        if (PopPeerView.Instance)
        {
            PopPeerView.Instance.DestoryAll();
        }
        if (PopCall.Instance)
        {
          //  PopCall.Instance.gameObject.SetActive(false);
        }
        if (ShowRoom.Instance)
        {
            ShowRoom.Instance.ShowMainScreen();
            ShowRoom.Instance.transform.localPosition = new Vector3(0, 0, 0);
            ShowRoom.Instance.transform.localEulerAngles = new Vector3(0, 0, 0);
        }
        API_GSXR_Slam.GSXR_Reset_Slam();

    //    AgoraVideoAudioManager.Instance.LeaveChannel();
        RemoteRtc.Instance.FiltrationCamera(true);
    }

    public void CloseRoom()
    {

        LeaveRoom();
        //PopUpInfo.Instance.showPublic(PopUpInfo.PopType.Pop, RtcStrConfig.roomPeopleLeave, "确定", () => { LeaveRoom(); }, "取消"
        //      );



        //if (RoomMainInfo.isCreator == "0")
        //{
        //    PopUpInfo.Instance.showPublic(PopUpInfo.PopType.Pop, RtcStrConfig.roomCreatorLeave, "确定", () => { LeaveRoom(); }, "取消"
        //      );
        //}
        //else
        //{
        //    PopUpInfo.Instance.showPublic(PopUpInfo.PopType.Pop, RtcStrConfig.roomPeopleLeave, "确定", () => { LeaveRoom(); }, "取消"
        //      );
        //}
    }

    public void ShowRoomissolvePop()
    {
        PopUpInfo.Instance.showPublic(PopUpInfo.PopType.PopOk, RtcStrConfig.roomdissolve, "知道了");
    }

    public void sendVideo(bool isSend)
    {
        //if (RemoteRtc.Instance.me.cIdV == "")
        //{
        //    dcetype = "video";
        //    Debug.Log("开启1111");
        //    RemoteRtc.Instance.startCamera();
        //    //  videoBG.gameObject.SetActive(true);
        //    // videoBG.material.mainTexture = RemoteRtc.Instance.rt;
        //    RemoteRtc.Instance.sendVideo(true);
        //    RemoteRtc.Instance.me.cIdV = "";
        //    openVideoEffect();
        //}else if (RemoteRtc.Instance.me.cIdV != "")
        //{
        //    dcetype = "video";
        //    Debug.Log("关闭11111");
        //    WSHandler.Rtc.closeProducer(RemoteRtc.Instance.me.cIdV);
        //    RemoteRtc.Instance.stopCamera();
        //    RemoteRtc.Instance.sendVideo(false);
        //    closeVideoEffect();
        //}

        if(isSend)
        {
            dcetype = "video";
            Debug.Log("开启1111");
            openVideoEffect();
        }
        else
        {
            dcetype = "video";
            closeVideoEffect();
        }
    //    AgoraVideoAudioManager.Instance.EnableLocalVideo(isSend);
    }

    public void sendAudio(bool isSend)
    {
        //if (RemoteRtc.Instance.me.cIdA != "")
        //{
            
        //    dcetype = "audio";
        //    WSHandler.Rtc.closeProducer(RemoteRtc.Instance.me.cIdA);
        //    RemoteRtc.Instance.sendMic(false);
        //    RemoteRtc.Instance.me.cIdA = "";
        //    closeAudioEffect();
        //}
        //else
        //{
        //    dcetype = "audio";
        //    RemoteRtc.Instance.sendMic(true);
        //    // volume = RemoteRtc.Instance.me.volumn;
        //    openAudioEffect();

        //}

        if (!isSend)
        {

            dcetype = "audio";          
            closeAudioEffect();
        }
        else
        {
            dcetype = "audio";
            openAudioEffect();

        }
     //   AgoraVideoAudioManager.Instance.EnableLoacalAudio(isSend);
    }

    private void closeVideoEffect()
    {
        isSendVideo = false;
        videoOpenBtn.SetActive(true);
        videoCloseBtn.SetActive(false);
    }

    private void openVideoEffect()
    {
        isSendVideo = true;
        videoOpenBtn.SetActive(false);
        videoCloseBtn.SetActive(true);
    }


    private void closeAudioEffect()
    {
        isSendAudio = false;
        audioOpenBtn.SetActive(true);
        audioCloseBtn.SetActive(false);
    }

    private void openAudioEffect()
    {
        isSendAudio = true;
        audioOpenBtn.SetActive(false);
        audioCloseBtn.SetActive(true);
    }


    public void openEye()
    {
        isCloseView = false;
        changeViewOpenBtn.SetActive(false);
      //  changeViewCloseBtn.SetActive(true);
        //RemoteRtc.Instance.changeViewOpen();
        // RemoteRtc.Instance.FiltrationCamera(true);
        Filtration(true);
    }

    public void closeEye()
    {
        isCloseView = true;
      //  changeViewOpenBtn.SetActive(true);
        changeViewCloseBtn.SetActive(false);
        //RemoteRtc.Instance.changeViewClose();
        //  RemoteRtc.Instance.FiltrationCamera(false);
        Filtration(false);
    }

    private void Filtration(bool state)
    {
        ArrowList.Instance.gameObject.SetActive(state);
        PngJpgList.Instance.gameObject.SetActive(state);
        ModelList.Instance.gameObject.SetActive(state);
        PdfList.Instance.gameObject.SetActive(state);
        Mp4List.Instance.gameObject.SetActive(state);
    }

    public void ClearAllArrow()
    {
        if (ArrowList.Instance)
        {
            ArrowList.Instance.DeleteAll();
        }
    }
}