using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Linq;
using System.Collections;
using DataModel.Model;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using LitJson;
using TMPro;
using System.IO;

public class LoadManage : MonoBehaviour
{
    public static LoadManage Instance;


    /// <summary>
    /// 系统模式
    /// </summary>
    public SystemMode systemMode;

    /// <summary>
    /// 本人账户信息
    /// </summary>
    [HideInInspector]
    public User me;
    /// <summary>
    /// 当前训练 (进房间前赋值)
    /// </summary>
    [HideInInspector]
    public practice currentPractice = null;
    /// <summary>
    /// 当前科目
    /// </summary>
    [HideInInspector]
    public practicesubject currentPracticeSubejct = null;
    /// <summary>
    /// 当前岗位
    /// </summary>
    [HideInInspector]
    public practiceseat currentPracticeSeat = null;
    /// <summary>
    /// 当前步骤
    /// </summary>
    [HideInInspector]
    public practicesubjectstep currentPracticeSubjectStep = null;
    /// <summary>
    /// 本人在训练中所有岗位信息 
    /// </summary>
    [HideInInspector]
    public List<practiceseat> myPracticeSeat = new List<practiceseat>();

    /// <summary>
    /// 训练科目 (进房间前赋值)
    /// </summary>
    [HideInInspector]
    public List<practicesubject> psubjects;
    /// <summary>
    /// 训练步骤
    /// </summary>
    [HideInInspector]
    public List<practicesubjectstep> psteps;
    /// <summary>
    /// 训练岗位
    /// </summary>
    [HideInInspector]
    public List<practiceseat> pseats;

    /// <summary>
    /// 音量大小
    /// </summary>
    [DisplayOnly]
    public float SourceLiangValue;
    /// <summary>
    /// 音效大小
    /// </summary>
    [DisplayOnly]
    public float SourceXiaoValue;

    [HideInInspector]
    public string MyId;




    /// <summary>
    /// 房间域 "1room"
    /// </summary>
    [DisplayOnly]
    public string currentRoomArea;
    /// <summary>
    /// 同步Id
    /// </summary>
    [DisplayOnly]
    public int SyncId;
    /// <summary>
    /// 训练状态
    /// </summary>
    public static ProgramState programState = ProgramState.结束;
    /// <summary>
    /// 是否暂停
    /// </summary>
    public static bool isPause;

    /// <summary>
    /// 与RoomServer通信
    /// </summary>
    [DisplayOnly]
    public MyNetMQClient RSclient;

    #region UDP
    [HideInInspector]
    public UdpClient udpClient;
    bool udpRun;
    int refreshTime = 0;
    #endregion


    /// <summary>
    /// 人员
    /// </summary>
    public static List<sys_user> persons = new List<sys_user>();

    private void Awake()
    {
        Instance = this;
        DontDestroyOnLoad(gameObject);
        //启动(测试用)
        udpClient = new UdpClient(8889);

        udpRun = true;
        Thread thread = new Thread(UdpRecive);
        thread.IsBackground = true;
        thread.Start();
#if UNITY_EDITOR
        UnityEngine.Debug.unityLogger.logEnabled = true;
#else
        UnityEngine.Debug.unityLogger.logEnabled = false;
#endif
    }
    void Start()
    {
        //设置不休眠
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        List<string> tmps = File.ReadAllLines(Application.streamingAssetsPath + "/MainSetting.txt").ToList();
        int porta, portb, portc;
        IPAddress ipd;
        tmps.ForEach(a =>
        {
            string[] data = a.Split('=');
            if (a.Split('=')[0] == "协同交互服务UDP")
            {
                IPAddress.Parse(data[1].Split(':')[0]);
                if (int.TryParse(data[1].Split(':')[1], out portb))
                {
                    //MyNetMQClient.SyncServerIP = data[1];
                    MyNetMQClient.SyncServerIP = "192.168.0.103";

                }
                else
                {
                    Debug.LogError("协同交互服务UDP配置错误");
                }
            }
        });
        GetAllUser();
    }

    private void Update()
    {
        if (refreshTime > 0)
        {
            //刷新房间列表
            if (RoomListPanel.instance != null && UnityEngine.SceneManagement.SceneManager.GetActiveScene().name.Contains("MainSence"))
            {
                RoomListPanel.instance.Refresh();
                refreshTime = 0;
            }
        }
    }

    private void UdpRecive()
    {
        while (udpRun)
        {
            try
            {
                IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = udpClient.Receive(ref iPEndPoint);
                int type = BitConverter.ToInt32(data, 0);
                if (type == 13)
                {
                    if (LoadManage.programState == ProgramState.结束)
                    {
                        //开启房间成功
                        UnityEngine.Debug.Log("开启房间成功");
                        string practiceid = Encoding.UTF8.GetString(data, 4, data.Length - 4);
                        refreshTime++;
                    }
                }
                else if (type == 26)
                {
                    if (LoadManage.programState == ProgramState.进行中)
                    {
                        //开启二维软件失败
                        int length = BitConverter.ToInt32(data, 4);
                        string arg = Encoding.UTF8.GetString(data, 8, length);
                        string[] tmps = arg.Split(':');
                        SoftManage.Instance.ChangeSoftSubject(tmps[0], tmps[1], SoftManage.Instance.softName, tmps[2], tmps[3]);
                    }
                }
            }
            catch
            {

            }
        }
    }
    /// <summary>
    /// 发送udp消息
    /// </summary>
    /// <param name="data"></param>
    /// <param name="endPoint"></param>
    public void UdpSend(byte[] data, IPEndPoint endPoint)
    {
        udpClient.Send(data, data.Length, endPoint);
    }

    /// <summary>
    /// 获取所有本系统人员数据,导调角色,操作手
    /// </summary>
    private void GetAllUser()
    {
        //使用真实接口

        //172.16.1.92:8087

        //获取士兵
        StartCoroutine(MyNetMQClient.CallGet("http://" + MyNetMQClient.userIP + ":8087/role?roleName=士兵", result1 =>
            {
                JsonData jd = JsonMapper.ToObject(result1);
                if (jd["success"].ValueAsBoolean())
                {

                    List<int> tmp = new List<int>();
                    foreach (JsonData item in jd["value"])
                    {
                        tmp.Add(int.Parse(item["roleId"].ToString()));
                    }
                    if (tmp.Count > 0)
                    {
                        string tmpjsonvalue = JsonMapper.ToJson(tmp);
                    //获取所有士兵user
                    StartCoroutine(MyNetMQClient.InvokeWebPostByUploadhandler("http://" + MyNetMQClient.userIP + ":8087/user/queryAllUsers", JsonMapper.ToJson(new { limit = 1000, roleDtoList = tmpjsonvalue }), (ok, result2) =>
                         {
                            if (ok)
                            {
                                JsonData jd2 = JsonMapper.ToObject(result2);
                                if (jd2["success"].ValueAsBoolean())
                                {
                                    foreach (JsonData item in jd2["value"]["results"])
                                    {
                                        sys_user tmpUser = new sys_user();
                                    //在这里取数据
                                    tmpUser.user_name = item["userName"].ToString();
                                        if (item["userCode"] != null)
                                            tmpUser.user_code = item["userCode"].ToString();
                                        tmpUser.user_id = int.Parse(item["userId"].ToString());
                                        if (item["deptId"] != null)
                                            tmpUser.dept_id = int.Parse(item["deptId"].ToString());
                                        if (item["jobId"] != null)
                                            tmpUser.job_id = int.Parse(item["jobId"].ToString());
                                        if (item["nickName"] != null)
                                            tmpUser.nickName = item["nickName"].ToString();
                                        if (item["avatar"] != null)
                                            tmpUser.avatar = item["avatar"].ToString();
                                        if (item["certificateNumber"] != null)
                                            tmpUser.introduce = item["certificateNumber"].ToString();
                                        persons.Add(tmpUser);
                                    }


                                //获取所有指挥员
                                StartCoroutine(MyNetMQClient.CallGet("http://" + MyNetMQClient.userIP + ":8087/role?roleName=指挥员", result3 =>
                                    {
                                        JsonData jd3 = JsonMapper.ToObject(result3);
                                        if (jd3["success"].ValueAsBoolean())
                                        {
                                            List<int> tmp2 = new List<int>();
                                            foreach (JsonData item in jd3["value"])
                                            {
                                                tmp2.Add(int.Parse(item["roleId"].ToString()));
                                            }
                                            if (tmp2.Count > 0)
                                            {
                                                string tmpjsonvalue2 = JsonMapper.ToJson(tmp2);
                                            //获取所有指挥员user
                                            StartCoroutine(MyNetMQClient.InvokeWebPostByUploadhandler("http://" + MyNetMQClient.userIP + ":8087/user/queryAllUsers", JsonMapper.ToJson(new { limit = 1000, roleDtoList = tmpjsonvalue2 }), (ok2, result4) =>
                                                {
                                                    if (ok2)
                                                    {
                                                        JsonData jd4 = JsonMapper.ToObject(result4);
                                                        if (jd4["success"].ValueAsBoolean())
                                                        {
                                                            foreach (JsonData item in jd4["value"]["results"])
                                                            {
                                                                sys_user tmpUser = new sys_user();
                                                            //在这里取数据
                                                            tmpUser.user_name = item["userName"].ToString();
                                                                if (item["userCode"] != null)
                                                                    tmpUser.user_code = item["userCode"].ToString();
                                                                tmpUser.user_id = int.Parse(item["userId"].ToString());
                                                                if (item["deptId"] != null)
                                                                    tmpUser.dept_id = int.Parse(item["deptId"].ToString());
                                                                if (item["jobId"] != null)
                                                                    tmpUser.job_id = int.Parse(item["jobId"].ToString());
                                                                if (item["nickName"] != null)
                                                                    tmpUser.nickName = item["nickName"].ToString();
                                                                persons.Add(tmpUser);
                                                            }

                                                            Debug.Log("获取人员完成");

                                                        //获取考核配置
                                                        StartCoroutine(MyNetMQClient.CallGet("http://" + MyNetMQClient.CallIP + "/3DConfig/考核动作标题配置.xml", back =>
                                                                {
                                                                    ScoreManage.SetXml(back);
                                                                    Debug.Log("考核配置获取完成");
                                                                //跳转
                                                                if (systemMode == SystemMode.PC)
                                                                    {
                                                                        SceneManager.LoadScene("LoginSencePC");
                                                                    }
                                                                    else if (systemMode == SystemMode.MR)
                                                                    {
                                                                        SceneManager.LoadScene("LoginSenceMR");
                                                                    }
                                                                }));
                                                        }
                                                        else
                                                        {
                                                            string msg = jd4["msg"].ToJson();
                                                            MessagePanel.ShowMessage(msg, GameObject.Find("Canvas").transform, null);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        MessagePanel.ShowMessage(result4, GameObject.Find("Canvas").transform, null);
                                                    }
                                                }));
                                            }
                                        }
                                        else
                                        {
                                            string msg = jd3["msg"].ToJson();
                                            MessagePanel.ShowMessage(msg, GameObject.Find("Canvas").transform, null);
                                        }
                                    }));

                                }
                                else
                                {
                                    string msg = jd2["msg"].ToJson();
                                    MessagePanel.ShowMessage(msg, GameObject.Find("Canvas").transform, null);
                                }
                            }
                            else
                            {
                                MessagePanel.ShowMessage(result2, GameObject.Find("Canvas").transform, null);
                            }
                        }));
                    }
                }
                else
                {
                    string msg = jd["msg"].ToJson();
                    MessagePanel.ShowMessage(msg, GameObject.Find("Canvas").transform, null);
                }
            }));
    }


    /// <summary>
    /// 创建与roomServer通信的客户端
    /// </summary>
    public void CreateRoomServerClient(string roomServerSubIP, string roomServerPubIP, string roomArea, int syncId)
    {
        if (RSclient == null)
        {
            //测试
            //roomServerPubIP = "tcp://192.168.1.125:56987";
            // roomServerSubIP = "tcp://192.168.1.125:56991";
            RSclient = gameObject.AddComponent<MyNetMQClient>();
            SyncId = syncId;
            currentRoomArea = roomArea;
            RSclient.Init(roomServerPubIP, roomServerSubIP, roomArea, ReciveFromRoomServerInThread, ReciveFromRoomServerInMono, "roomServer");
            Debug.Log("开启roomServer:" + roomServerPubIP + "------" + roomServerSubIP + "-------" + roomArea);
        }
    }

    public void RemoveRoomServerClient()
    {
        if (RSclient != null)
        {
            RSclient.Destroy();
            // RSclient = null;
            Debug.Log("RSclient置空");
        }
    }

    /// <summary>
    /// RoomServer,mono
    /// </summary>
    /// <param name="stS"></param>
    private void ReciveFromRoomServerInThread(st_Motions stS)
    {
        //同步域
        if (programState == ProgramState.进行中)
        {
            if (stS.m_iOperaType == 10006)
            {
                //单值同步
                int syncid = BitConverter.ToInt32(stS.m_sOperaData, 0);
                if (LoadManage.Instance.SyncId != syncid)
                {
                    int legth = BitConverter.ToInt32(stS.m_sOperaData, 4);
                    string id = Encoding.UTF8.GetString(stS.m_sOperaData, 8, legth);
                    if (OneValueSyncObject.OneAxisSyncObjectList.ContainsKey(id))
                    {
                        if (stS.m_sOperaData[9 + legth] == 0)
                        {
                            //无回调
                            OneValueSyncObject.OneAxisSyncObjectList[id].SetValue(8 + legth, stS.m_sOperaData);
                        }
                        else
                        {
                            //有回调
                            RSclient._netMqListener.AddToMono(stS);
                        }
                    }
                }
            }
            else if (stS.m_iOperaType == 10007)
            {
                //坐标角度同步
                int syncid = BitConverter.ToInt32(stS.m_sOperaData, 0);
                if (LoadManage.Instance.SyncId != syncid)
                {
                    int legth = BitConverter.ToInt32(stS.m_sOperaData, 4);
                    string id = Encoding.UTF8.GetString(stS.m_sOperaData, 8, legth);
                    if (FunctionSync_PositionRoate.positionRoateSyncObejctList.ContainsKey(id))
                    {
                        FunctionSync_PositionRoate.positionRoateSyncObejctList[id].SetValue(8 + legth, stS.m_sOperaData);
                    }
                }
            }
            else if (stS.m_iOperaType == 61)
            {
                //心跳检测
                //XinTiaoCheck();
            }
            else
            {
                RSclient._netMqListener.AddToMono(stS);
            }
        }
    }

    /// <summary>
    /// RoomServer,mono
    /// </summary>
    /// <param name="data"></param>
    public void ReciveFromRoomServerInMono(st_Motions data)
    {

#if !UNITY_EDITOR
        try
        {
#endif


        switch (data.m_iOperaType)
        {
            case 16:
                {
                    //结束房间
                    if (GameManage.Instance != null)
                    {
                        GameManage.Instance.action_close.Invoke();
                    }
                }
                break;
            case 25:
                {
                    //二维通信(2维-->3维)
                    int length = BitConverter.ToInt32(data.m_sOperaData, 0);
                    string msg = Encoding.UTF8.GetString(data.m_sOperaData, 4, length);
                    MessageModel messageModel = JsonMapper.ToObject<MessageModel>(msg);
                    if (SoftManage.Instance != null)
                    {
                        SoftManage.Instance.SoftHandle(messageModel);
                    }
                }
                break;
            case 31:
                {
                    //开始暂停
                    int length = BitConverter.ToInt32(data.m_sOperaData, 0);
                    string practiceid = Encoding.UTF8.GetString(data.m_sOperaData, 4, length);
                    isPause = (data.m_sOperaData[4 + length] == 1 ? false : true);
                    if (GameManage.Instance.action_Pause != null)
                    {
                        GameManage.Instance.action_Pause.Invoke(isPause);
                    }
                }
                break;
            case 33://得到房间所有数据
                if (programState == ProgramState.进行中)
                {
                    GetRoomData(data.m_sOperaData);
                }
                break;
            case 41:
                {
                    //科目启停
                    int length = BitConverter.ToInt32(data.m_sOperaData, 0);
                    string msg = Encoding.UTF8.GetString(data.m_sOperaData, 4, length);
                    if (GameManage.Instance != null)
                    {
                        GameManage.Instance.SubjectChange(msg);
                    }
                }
                break;
            case 51:
                {
                    //步骤启停
                    int length = BitConverter.ToInt32(data.m_sOperaData, 0);
                    string msg = Encoding.UTF8.GetString(data.m_sOperaData, 4, length);
                    if (GameManage.Instance != null)
                    {
                        GameManage.Instance.StepChange(msg);
                    }
                }
                break;







            case 1000://测试

                break;
            case 10006://单值同步
                if (programState == ProgramState.进行中)
                {
                    int legth = BitConverter.ToInt32(data.m_sOperaData, 4);
                    string id = Encoding.UTF8.GetString(data.m_sOperaData, 8, legth);
                    OneValueSyncObject.OneAxisSyncObjectList[id].SetValue(8 + legth, data.m_sOperaData);
                    OneValueSyncObject.OneAxisSyncObjectList[id].callbackInmono.Invoke(id, false);
                }
                break;
            case 10008://生成物体
                if (programState == ProgramState.进行中)
                {
                    int syncId = BitConverter.ToInt32(data.m_sOperaData, 0);
                    if (LoadManage.Instance.SyncId != syncId)
                    {
                        if (FunctionSync_CreateObejct.Instance != null)
                        {
                            FunctionSync_CreateObejct.Instance.CallBack(data.m_sOperaData);
                        }
                    }
                }
                break;
            case 10010:
                if (programState == ProgramState.进行中)
                {
                    //自己也要执行
                    int legth = BitConverter.ToInt32(data.m_sOperaData, 0);
                    string id = Encoding.UTF8.GetString(data.m_sOperaData, 4, legth);
                    if (FunctionSync_Media.functionSync_MediaDic.ContainsKey(id))
                    {
                        FunctionSync_Media.functionSync_MediaDic[id].CallBack(data.m_sOperaData);
                    }
                }
                break;
        }




#if !UNITY_EDITOR
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
        }
#endif

    }



    public void GetRoomData(byte[] data)
    {
        //索引
        int index = 0;
        //暂停
        isPause = (data[0] == 1 ? true : false);
        index++;
        Debug.Log(isPause ? "暂停" : "开始");
        if (GameManage.Instance.action_Pause != null)
        {
            GameManage.Instance.action_Pause.Invoke(isPause);
        }

        //打分
        int countScore = BitConverter.ToInt32(data, index);
        index += 4;
        for (int i = 0; i < countScore; i++)
        {
            //取数据
            int tmpnum = BitConverter.ToInt32(data, index);
            index += 4;
            byte[] tmp = new byte[tmpnum];
            Array.Copy(data, index, tmp, 0, tmpnum);
            index += tmpnum;
            //解析
            HandleScore(Encoding.UTF8.GetString(tmp));
        }

        //10008生成
        int countCreate = BitConverter.ToInt32(data, index);
        index += 4;
        for (int i = 0; i < countCreate; i++)
        {
            //取数据
            int tmpnum = BitConverter.ToInt32(data, index);
            index += 4;
            byte[] tmp = new byte[tmpnum];
            Array.Copy(data, index, tmp, 0, tmpnum);
            index += tmpnum;
            //解析
            FunctionSync_CreateObejct.Instance.CallBack(tmp);
        }
        //10006单值
        int couOneValue = BitConverter.ToInt32(data, index);
        index += 4;
        for (int i = 0; i < couOneValue; i++)
        {
            //取数据
            int tmpnum = BitConverter.ToInt32(data, index);
            index += 4;
            byte[] tmp = new byte[tmpnum];
            Array.Copy(data, index, tmp, 0, tmpnum);
            index += tmpnum;
            //解析
            int legth = BitConverter.ToInt32(tmp, 4);
            string id = Encoding.UTF8.GetString(tmp, 8, legth);
            if (OneValueSyncObject.OneAxisSyncObjectList.ContainsKey(id))
            {
                OneValueSyncObject.OneAxisSyncObjectList[id].SetValue(8 + legth, tmp);
                if (tmp[9 + legth] == 1)
                {
                    OneValueSyncObject.OneAxisSyncObjectList[id].callbackInmono.Invoke(id, true);
                }
            }
            else
            {
                Debug.LogError("不存在此物体:" + id);
            }
        }

        //10007坐标旋转
        int countPosRot = BitConverter.ToInt32(data, index);
        index += 4;
        for (int i = 0; i < countPosRot; i++)
        {
            //取数据
            int tmpnum = BitConverter.ToInt32(data, index);
            index += 4;
            byte[] tmp = new byte[tmpnum];
            Array.Copy(data, index, tmp, 0, tmpnum);
            index += tmpnum;
            //解析
            int legth = BitConverter.ToInt32(tmp, 4);
            string id = Encoding.UTF8.GetString(tmp, 8, legth);
            if (FunctionSync_PositionRoate.positionRoateSyncObejctList.ContainsKey(id))
            {
                FunctionSync_PositionRoate.positionRoateSyncObejctList[id].SetValue(8 + legth, tmp);
            }
        }

        Debug.Log("数据已恢复");
    }

    private void HandleScore(string str)
    {
        var ys = str.Split('|');
        if (ys[0] == "评估点")
        {
            //评估点 | 科目物体名称 | 评估点序号 | 当前index
            ScoreBase sb = GameManage.Instance.scoreManage.transform.Find(ys[1]).GetComponentsInChildren<ScoreBase>(true).ToList().Find(a => a.code.ToString() == ys[2]);
            sb.IsRight = true;
            sb.Completed = int.Parse(ys[3]);
        }
        else if (ys[1] == "操作点")
        {
            //操作点 | 科目物体名称 | 评估点序号 | 操作点物体名称 | index
            ScoreJudge_FixedValue tmp = GameManage.Instance.scoreManage.transform.Find(ys[1]).GetComponentsInChildren<ScoreBase>(true).ToList().Find(a => a.code.ToString() == ys[2]).transform.Find(ys[3]).GetComponent<ScoreJudge_FixedValue>();
            tmp.Isright = true;
            tmp.index = int.Parse(ys[4]);
        }

        Debug.Log("打分恢复:" + str);
    }

    /// <summary>
    /// 心跳检测响应
    /// </summary>
    public void XinTiaoCheck()
    {
        if (programState == ProgramState.进行中 && LoadManage.Instance != null && !string.IsNullOrEmpty(LoadManage.Instance.MyId) && !string.IsNullOrEmpty(LoadManage.Instance.currentRoomArea))
        {
            if (GameManage.Instance != null)
            {
                UnityEngine.Debug.Log("重置6秒");
                GameManage.Instance.checkTime = 6;
            }
            byte[] tmp = Encoding.UTF8.GetBytes(LoadManage.Instance.MyId);
            byte[] data = new byte[4 + tmp.Length];
            Array.Copy(BitConverter.GetBytes(tmp.Length), 0, data, 0, 4);
            Array.Copy(tmp, 0, data, 4, tmp.Length);
            RSclient.Send(LoadManage.Instance.currentRoomArea, 6, data);
            Debug.Log("心跳" + LoadManage.Instance.currentRoomArea);
        }
    }

    //public void StartRoom(string roomid)
    //{
    //    byte[] roomidbytes = Encoding.UTF8.GetBytes(roomid);
    //    byte[] tmp = new byte[4 + roomidbytes.Length];
    //    Array.Copy(BitConverter.GetBytes(roomidbytes.Length), 0, tmp, 0, 4);
    //    Array.Copy(roomidbytes, 0, tmp, 4, roomidbytes.Length);
    //    MSclient.Send("mainServer", 100, tmp);
    //    Debug.Log("启动房间:" + roomidbytes);
    //}
    //public void CloseRoom(string roomId, string pcArea, string roomArea)
    //{
    //    //string roomId = "abcdasdadasd";
    //    byte[] roomidbytes = Encoding.UTF8.GetBytes(roomId);
    //    //string pcArea = "pcserver125";
    //    byte[] pcbytes = Encoding.UTF8.GetBytes(pcArea);
    //    //string roomArea = "room1";
    //    byte[] roombytes = Encoding.UTF8.GetBytes(roomArea);
    //    byte[] tmp = new byte[12 + roomidbytes.Length + pcbytes.Length + roombytes.Length];
    //    Array.Copy(BitConverter.GetBytes(roomidbytes.Length), 0, tmp, 0, 4);
    //    Array.Copy(roomidbytes, 0, tmp, 4, roomidbytes.Length);
    //    Array.Copy(BitConverter.GetBytes(pcbytes.Length), 0, tmp, 4 + roomidbytes.Length, 4);
    //    Array.Copy(pcbytes, 0, tmp, 8 + roomidbytes.Length, pcbytes.Length);
    //    Array.Copy(BitConverter.GetBytes(roombytes.Length), 0, tmp, 8 + roomidbytes.Length + pcbytes.Length, 4);
    //    Array.Copy(roombytes, 0, tmp, 12 + roomidbytes.Length + pcbytes.Length, roombytes.Length);
    //    MSclient.Send("mainServer", 110, tmp);
    //    Debug.Log("关闭房间:" + roomId);
    //}

    private void OnDestroy()
    {
        Debug.Log("OnDestroy");
        udpRun = false;
        if (RSclient != null)
        {
            RSclient.Destroy();
        }

        if (udpClient != null)
        {
            udpClient.Close();
        }
    }
}

public enum SystemMode
{
    PC,
    MR
}