using LitJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using static LangChaoRommMinIo;
using uPLibrary.Networking.M2Mqtt.Messages;

public class MQTTManager : MonoSingleton<MQTTManager>
{

    public string front = "client/";
    public string id = "";
    public string username = "u@unity3";// 需要根据服务器设置
    public string password = null;// 需要根据服务器设置
    public string rid = "mqttx_b4c02ddc"; //其他人的ID
    public string clientId = "";
    public string account;
    public string roomId;
    public string email;
    public string phone;
    public string roleId;
  //  public string resourcePool;
    public string resourcePoolId;
    public string expertType;
    public string _username;
    public string room;
    public static string certification;

    public string topiceNavigation;
    public string topiceSync;
    public string topiceClose;


   public  bool isCreateRoom = false;

    bool isinitCRoom = true;

    private int SignalCount = 0;
    private void Update()
    {
        if(isCreateRoom&& isinitCRoom)
        {
            isinitCRoom = false;

            StartCoroutine(CreateRoom());
        }
    }
    private IEnumerator CreateRoom()
    {
        yield return new WaitForSeconds(1);
       // UICallManager.Instance.EventInvite("", "");
    }

    /// <summary>
    ///  获取信令
    /// </summary>
    public void Signal()
    {
       
       HttpToolLangChao.Instance.Post(HttpActionLang.signal_certification, "", SignalCallBack);     
        SignalCount++;


        //  GameStart.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpActionLang.userinfo, "", UserInfoCallBack));
        // HttpTool.Instance.PostMqtt(HttpAction.signal_certification, "", SignalCallBack);
    }

    public void SetAccoutInfo(string account)
    {
        MQTTManager.Instance.account = account;

    }
    private void SignalCallBack(string msg)
    {
        Debug.Log("SignalCallBack " + msg);

        JObject obj = JObject.Parse(msg);
        if (obj["code"].ToString() == "200")
        {
           

            HttpActionLang.Instance.mqttSocket = obj["data"]["host"].ToString();
           // HttpActionLang.Instance.mqttPort = obj["data"]["port"].ToString();
            MQTTManager.certification = obj["data"]["certification"].ToString();
            MQTTManager.Instance.front = obj["data"]["topicPrefix"].ToString();
            MQTTManager.Instance.clientId = obj["data"]["clientId"].ToString();
            MQTTManager.Instance.username = obj["data"]["username"].ToString();

         
            //if (!string.IsNullOrEmpty( obj["data"]["uinoTopics"].ToString()))
            //{
            //    topiceNavigation = obj["data"]["uinoTopics"]["navigation"].ToString();
            //    topiceSync = obj["data"]["uinoTopics"]["sync"].ToString();
            //    topiceClose = obj["data"]["uinoTopics"]["close"].ToString();
            //}

           // ErrorPopup.Instance.UpdateEmqxState(NetState.Connecting);
            MQTTClient.Instance.Connect();

            SignalCount = 0;

            //  StartCoroutine(TestCreateRoom());
        }
        else
        {
            Debug.LogError("MQTT 获取信令失败 !!!" + obj["code"].ToString());

           if(int.Parse(obj["code"].ToString())>= 500)
            {
                //ErrorPopup.Instance.UpdateEmqxState(NetState.DisConnect);
                //ErrorPopup.Instance.ShowEmqxError("服务器连接失败 "+ msg, -1);
            }
            else
            {
              //  ErrorPopup.Instance.UpdateEmqxState(NetState.StartError);
                if (SignalCount > 5)
                {
                  //  ErrorPopup.Instance.ShowEmqxError("信令请求失败 " + msg , -1);
                }
                else
                {
                    Signal();
                }
            }
        }
    }

    private IEnumerator TestCreateRoom()
    {
        yield return new WaitForSeconds(5);
        while (!RTCRoomManager.Instance.isRTCreate)
        {
            yield return new WaitForSeconds(1);
          //  this.GetService<IRTCService>().CreatRoom();
        }
    }

    private void UserInfoCallBack(string msg)
    {
        Debug.Log(msg);

        JObject obj = JObject.Parse(msg);
        if (obj["code"].ToString() == "200")
        {
            MQTTManager.Instance._username = obj["data"]["name"].ToString();
            MQTTManager.Instance.roleId = obj["data"]["roleId"].ToString();
            MQTTManager.Instance.email = obj["data"]["email"].ToString();
            MQTTManager.Instance.phone = obj["data"]["phone"].ToString();
         //   MQTTManager.Instance.resourcePool = obj["data"]["resourcePool"].ToString();
            MQTTManager.Instance.resourcePoolId = obj["data"]["resourcePoolId"].ToString();
            MQTTManager.Instance.expertType = obj["data"]["expertType"].ToString();
        }
        else
        {
            Debug.LogError("获取用户信息失败 !!!"+ obj["code"].ToString());
        }
    }

    public void SetRoomId(string id)
    {
        MQTTManager.Instance.roomId = id;
     //   MQTTClient.Instance.roomId = "9527";

        // 订阅房间频道

        MQTTClient.Instance.Subscribe(MQTTManager.Instance.front + "room/" + id);

      

    }

    public void UnSubscribe( string id)
    {
        MQTTClient.Instance.UnSubscribe(MQTTManager.Instance.front + "room/" + id);
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="msg"></param>
    public void PushMsg(string msg)
    {
        if (!string.IsNullOrEmpty(msg))
        {
            JsonData json = new JsonData();
            json["account"] = MQTTManager.Instance.account;
            json["Sid"] = "sid";//选择的场景id
            json["msg"] = msg;
            MQTTClient.Instance.publish(Encoding.UTF8.GetBytes(json.ToJson()));
            
        }

    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="msg"></param>
    public void PushMsg(string channelID, string msg)
    {

        Debug.Log("DGJ ===> MQTT Test "+ msg);
        if (!string.IsNullOrEmpty(msg))
        {
            MQTTClient.Instance.publish(channelID, Encoding.UTF8.GetBytes(msg));

        }

    }

    /// <summary>
    ///  接受消息
    /// </summary>
    /// <param name="msg"></param>
    public void Received(string msg)
    {
        JObject obj = JObject.Parse(msg);

       // Debug.Log("Received  ===>  " + obj["action"].ToString());
        if(obj["action"]!=null)
        switch (obj["action"].ToString())
        {
            case "timeout": // 超时
               // UICallManager.Instance.EventTimeOut();
                break;

            case "invite": // 邀请

                if(obj["control"] !=null)
                {
                    string id = obj["control"]["id"].ToString();
                    RTCRoomManager.Instance.controlId = id;
                   
                    if(RTCRoomManager.Instance.rtcState != RTCEnum.OFF) // 当前已经在房间内 直接发送当前房间号
                    {
                        JsonData data = new JsonData();
                        data["action"] = "invite";
                        data["rtcRoom"] =RTCRoomManager.Instance.mRTCRoomInfo.roomId.ToString();
                        data["personnel"] = new JsonData();
                        data["personnel"]["id"] = MQTTManager.Instance.id;
                        data["personnel"]["name"] = MQTTManager.Instance._username;
                        //data["personnel"]["resourcePoo1"] = MQTTManager.Instance.resourcePool;
                        data["personnel"]["resourcePoolId"] = MQTTManager.Instance.resourcePoolId;
                        data["personnel"]["room"] = MQTTManager.Instance.room;
                        data["personnel"]["phone"] = MQTTManager.Instance.phone;
                        // 用MQTT 向中考发送邀请
                        MQTTManager.Instance.PushMsg(MQTTManager.Instance.front + "online/" + RTCRoomManager.Instance.controlId, data.ToJson());
                    }
                    else // 不在房间内,创建房间后 发送邀请
                    {
                        //string roomid = obj["rtcRoom"].ToString();                       
                        //string resourcePool = obj["control"]["resourcePoo1"].ToString();
                        RTCRoomManager.Instance.isInvite = true;
                       // UICallManager.Instance.EventInvite(obj["control"].ToString(), "");
                        Debug.Log(phone);
                    }
                }
                else
                {
                    Debug.LogError(" 非控制台邀请 ");
                }
              
                break;

            case "noExpert": // 无专家

             //   UICallManager.Instance.EventNoExpert();
                break;
            case "chat": // 聊天消息

                // 拆解用户名  和 聊天内容  显示到聊天框里

                string username = obj["from"].ToString();
                string chatMsg = obj["chatMessage"].ToString();

                FileList.Instance.AddMsgItem(null, username, chatMsg);

                break;
            case "share": // 接受文件

                Debug.Log(" DGJ ===> share  " + obj["chatMessage"].ToString());
                // 拆解用户名  和 文件名称  显示到聊天框里   下载文件
                FileConfig fileConfig = JsonConvert.DeserializeObject<FileConfig>(obj["chatMessage"].ToString());
                fileConfig.From = obj["from"].ToString();

                Debug.Log(" DGJ ===> FileConfig  " + JsonConvert.SerializeObject(fileConfig));

            


                FileList.Instance.AddItem(fileConfig);
                break;
            case "remark": // 空间标注
                float Valuex = float.Parse(obj["chatMessage"]["x"].ToString());
                float Valuey = float.Parse(obj["chatMessage"]["y"].ToString());

                ArrowList.Instance.AddArrow(Valuex, Valuey);
                break;
            case "clearRemark":
                ArrowList.Instance.DeleteAll();
                break;

            case "leave":
                // 退出房间
                string roleId = obj["roleId"].ToString();
                if (roleId == "2")
                {

                //    RTCRoomManager.Instance.UserOffline(UserEnum.Expert);

                }

                if (roleId == "1")
                {
                //    RTCRoomManager.Instance.UserOffline(UserEnum.Conterl);
                }

                break;
              case "stop":
                    // 停止同步位置信息

                    SynPlayerTransform.Instance.isPushPos = false;

                    break;
                default:
                break;
        }

        if (obj["image_data"]!=null&&!string.IsNullOrEmpty( obj["image_data"].ToString()))
        {
           // UILogManager.Instance.text2.text = msg;
            SynPlayerTransform.Instance.isPushPos = true;

          //  LangChaoMailManager.Instance.ReceiverMail(obj);
           
        }
    }

    public void Received(MqttMsgPublishEventArgs MsgData)
    {
        string msg = Encoding.UTF8.GetString(MsgData.Message);
        JObject obj = JObject.Parse(msg);

        // Debug.Log("Received  ===>  " + obj["action"].ToString());
        if (obj["action"] != null)
            switch (obj["action"].ToString())
            {
                case "timeout": // 超时
                  //  UICallManager.Instance.EventTimeOut();
                    break;

                case "invite": // 邀请

                    if (obj["control"] != null)
                    {
                        string id = obj["control"]["id"].ToString();
                        RTCRoomManager.Instance.controlId = id;

                        if (RTCRoomManager.Instance.rtcState != RTCEnum.OFF) // 当前已经在房间内 直接发送当前房间号
                        {
                            JsonData data = new JsonData();
                            data["action"] = "invite";
                            data["rtcRoom"] = RTCRoomManager.Instance.mRTCRoomInfo.roomId.ToString();
                            data["personnel"] = new JsonData();
                            data["personnel"]["id"] = MQTTManager.Instance.id;
                            data["personnel"]["name"] = MQTTManager.Instance._username;
                            //data["personnel"]["resourcePoo1"] = MQTTManager.Instance.resourcePool;
                            data["personnel"]["resourcePoolId"] = MQTTManager.Instance.resourcePoolId;
                            data["personnel"]["room"] = MQTTManager.Instance.room;
                            data["personnel"]["phone"] = MQTTManager.Instance.phone;
                            // 用MQTT 向中考发送邀请
                            MQTTManager.Instance.PushMsg(MQTTManager.Instance.front + "online/" + RTCRoomManager.Instance.controlId, data.ToJson());
                        }
                        else // 不在房间内,创建房间后 发送邀请
                        {
                            //string roomid = obj["rtcRoom"].ToString();                       
                            //string resourcePool = obj["control"]["resourcePoo1"].ToString();
                            RTCRoomManager.Instance.isInvite = true;
                        //    UICallManager.Instance.EventInvite(obj["control"].ToString(), "");
                            Debug.Log(phone);
                        }
                    }
                    else
                    {
                        Debug.LogError(" 非控制台邀请 ");
                    }

                    break;

                case "noExpert": // 无专家

                   // UICallManager.Instance.EventNoExpert();
                    break;
                case "chat": // 聊天消息

                    // 拆解用户名  和 聊天内容  显示到聊天框里

                    string username = obj["from"].ToString();
                    string chatMsg = obj["chatMessage"].ToString();

                    FileList.Instance.AddMsgItem(null, username, chatMsg);

                    break;
                case "share": // 接受文件

                    Debug.Log(" DGJ ===> share  " + obj["chatMessage"].ToString());
                    // 拆解用户名  和 文件名称  显示到聊天框里   下载文件
                    FileConfig fileConfig = JsonConvert.DeserializeObject<FileConfig>(obj["chatMessage"].ToString());
                    fileConfig.From = obj["from"].ToString();

                    Debug.Log(" DGJ ===> FileConfig  " + JsonConvert.SerializeObject(fileConfig));




                    FileList.Instance.AddItem(fileConfig);
                    break;
                case "remark": // 空间标注
                    float Valuex = float.Parse(obj["chatMessage"]["x"].ToString());
                    float Valuey = float.Parse(obj["chatMessage"]["y"].ToString());

                    ArrowList.Instance.AddArrow(Valuex, Valuey);
                    break;
                case "clearRemark":
                    ArrowList.Instance.DeleteAll();
                    break;

                case "leave":
                    // 退出房间
                    string roleId = obj["roleId"].ToString();
                    if (roleId == "2")
                    {

                        //    RTCRoomManager.Instance.UserOffline(UserEnum.Expert);

                    }

                    if (roleId == "1")
                    {
                        //    RTCRoomManager.Instance.UserOffline(UserEnum.Conterl);
                    }

                    break;
                default:
                    break;
            }


        switch (MsgData.Topic)
        {
            case "yunyi/coordinate/close":
                if (obj["action"] != null&& (obj["action"].ToString()== "stop"))
                {
                    // 停止同步位置信息

                    SynPlayerTransform.Instance.isPushPos = false;

                //    MailUIContent.Instance.CloseSync.SetActive(false);
                }

                    break;
            case "yunyi/navigation/diagram":
                if (obj["image_data"] != null && !string.IsNullOrEmpty(obj["image_data"].ToString()))
                {
                  //  UILogManager.Instance.text2.text = msg;
                    SynPlayerTransform.Instance.isPushPos = true;
                    //MailUIContent.Instance.CloseSync.SetActive(true);
                    //LangChaoMailManager.Instance.ReceiverMail(obj);

                }
                break;
            default:
                break;
        }

      
    }
}