using LitJson;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XRTool.Util;

public class UserSceneManager : XRTool.Util.Singleton<UserSceneManager>
{
    public delegate void UserSceneInitEnd(bool b);

    //下载回调
    public UserSceneInitEnd callback;

    int max;
    int now;

    //场景中的模型
    public Dictionary<string, UserSceneItem> SceneList = new Dictionary<string, UserSceneItem>();
    //初始化场景
    public IEnumerator initScene(string msg)
    {
        UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), (int)ELoadState.sninfo);
        SceneList.Clear();
        JsonData data = JsonMapper.ToObject(msg);
        Debug.Log("initScene init"+ msg);
        if (data["data"]["list"].IsArray)
        {
            max = data["data"]["list"].Count;
                Debug.Log("initScene IsArray");
            for (int i = 0; i < data["data"]["list"].Count; i++)
            {
               yield return GameManager.Instance.StartCoroutine( init(data["data"]["list"][i]["id"].ToString(), data["data"]["list"][i]["name"].ToString()));
            }
           
        }
        else
        {
            callback?.Invoke(true);
        }
    }

    public IEnumerator init(string id, string name)
    {
        SendSnInfo sendNet = new SendSnInfo();
        sendNet.sn = SendSN.GetSN();
        sendNet.projectId = int.Parse(id);
        string jsonData = JsonMapper.ToJson(sendNet);
        SendInit detail = new SendInit();
        yield return GameScene.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpAction.client_snInfo, jsonData, (message) =>
        {
            Debug.Log(" 初始化场景 client_snInfo==》" + message);
            detail.projectId = int.Parse(id);
            detail.sn = SendSN.GetSN();

        }));

        yield return null;

        string str = JsonConvert.SerializeObject(detail);

        UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), " 正在初始化场景");
        yield return GameScene.Instance.StartCoroutine(HttpTool.Instance.SendHttp(HttpAction.sn_init, str, (mes) =>
        {
            Debug.Log(" 初始化场景 sn_init==》" + mes + "===>id" + detail.projectId.ToString());
            JsonData data = JsonMapper.ToObject(mes);
            if (data["data"].ToString() != null)
            {
                CreateItem(data["data"]["info"], detail.projectId.ToString());
            }else
            {

                UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), HttpAction.sn_init+" 网络通讯异常 请重启应用");
            }

        }));
    }
    Dictionary<string,JsonData> msglist = new Dictionary<string,JsonData>();
    public static JsonData smsg;
    void CreateItem(JsonData msg,string id)
    {
        msglist.Add(id,msg);
        //   JsonConvert.DeserializeObject<UserSceneItem>(msg.ToJson());

        UserSceneItem usi = new UserSceneItem();//
        usi.id = id;
        usi.name = msg["name"].ToString();
        if(msg["sentiment"]!=null)
            usi.sentiment = msg["sentiment"].ToString();
        if (msg["updateTime"] != null)
            usi.updateTime = msg["updateTime"].ToString();
        if (msg["navLines"] != null)
            usi.navLines = msg["navLines"].ToString();
        if (msg["status"] != null)
            usi.status = msg["status"].ToString();
        if (msg["describe"] != null)
            usi.describe = msg["describe"].ToString();
        if (msg["image"] != null)
            usi.image = msg["image"].ToString();
        if (msg["map"] != null)
            usi.map = msg["map"].ToString();
        if (msg["sandTable"] != null)
            usi.sandTable = msg["sandTable"].ToString();
        GameManager.Instance.m_scene = usi;
        if (msg["listSpoit"] != null)
        {
            if(msg["listSpoit"].IsArray)
            {
                for (int i = 0; i < msg["listSpoit"].Count; i++)
                {
                    SpotsItem si = new SpotsItem();
                    si.usi = usi;
                    si.position = JsonConvert.DeserializeObject<List<sspos>>(msg["listSpoit"][i]["spoitTransform"].ToJson());
                    si.id = msg["listSpoit"][i]["id"].ToString();
                    si.name = msg["listSpoit"][i]["name"].ToString();
                    si.triggerImageMark = msg["listSpoit"][i]["triggerImageMark"].ToString();
                    if (msg["listSpoit"][i]["spoittf"]!=null)
                    {
                        si.initSpoitTfInfo(msg["listSpoit"][i]["spoittf"]);
                    }
                    else
                    {
                        si.SpotsObj.transform.localPosition = Vector3.zero;
                        si.SpotsObj.transform.localEulerAngles = Vector3.zero;
                        si.SpotsObj.transform.localScale = Vector3.one;
                    }
                    si.updateTime = msg["listSpoit"][i]["updateTime"].ToString();
                    si.triggerImageId =int.Parse( msg["listSpoit"][i]["triggerImageId"].ToString());
                    if ( msg["listSpoit"][i].Keys.Contains("triggerImage"))
                        si.triggerImage = msg["listSpoit"][i]["triggerImage"].ToString();
                    if(msg["listSpoit"][i]["material"]!=null&& msg["listSpoit"][i]["material"].IsArray)
                    {
                        for (int j = 0; j < msg["listSpoit"][i]["material"].Count; j++)
                        {
                            if(ModelManager.Instance.modellist.ContainsKey(int.Parse(msg["listSpoit"][i]["material"][j]["id"].ToString())))
                            {
                                ModelList modellist = ModelManager.Instance.GetModelList(int.Parse(msg["listSpoit"][i]["material"][j]["id"].ToString()));

                                Debug.Log("DGJ   ====> "+ msg["listSpoit"][i]["material"][j]["id"].ToString() + "_" +(msg["listSpoit"][i]["material"][j]["objectTransform"].ToJson()));
                                modellist.objectTransform = JsonConvert.DeserializeObject<ObjectTransform>(msg["listSpoit"][i]["material"][j]["objectTransform"].ToJson());
                               // modellist._model.transform.parent = si.SpotsObj.transform;
                                modellist.spotsItem = si;
                                modellist.select = bool.Parse(msg["listSpoit"][i]["material"][j]["select"].ToString());
                                modellist.init(false); 
                                for (int l = 0; l < modellist.materialList.Count; l++)
                                {
                                    Debug.Log("DGJ New  ====> " + modellist.materialList[l].name);
                                    modellist.materialList[l].modelList = modellist.Model;
                                }
                                si.modelList.Add(msg["listSpoit"][i]["material"][j]["id"].ToString(), modellist);
                               
                                if (msg["listSpoit"][i]["material"][j]["materialList"]!=null&& msg["listSpoit"][i]["material"][j]["materialList"].IsArray)
                                {
                                    for (int z = 0; z < msg["listSpoit"][i]["material"][j]["materialList"].Count; z++)
                                    {
                                        Debug.Log("DGJ2   ====> "+ si.triggerImage + "_" + msg["listSpoit"][i]["material"][j]["materialList"][z]["id"].ToJson() + "_" + (msg["listSpoit"][i]["material"][j]["materialList"][z]["objectTransform"].ToJson()));
                                        modellist.materialList[z].objectTransform = JsonConvert.DeserializeObject<ObjectTransform>(msg["listSpoit"][i]["material"][j]["materialList"][z]["objectTransform"].ToJson());
                                        //modellist.materialList[z].initModelObj();
                                        Debug.Log("DGJ2   ====> " + indexa+"_" + modellist.materialList[z].id+"_"+ msg["listSpoit"][i]["material"][j]["materialList"][z]["id"].ToJson());
                                        modellist.materialList[z].name = si.triggerImage;
                                        indexa++;
                                        //  GameManager.Instance.StartCoroutine(modellist.materialList[z].initFrist());
                                    }
                                }
                                si.init();
                            }
                            else
                            {
                                Debug.Log("沒有找到===》" + int.Parse(msg["listSpoit"][i]["material"][j]["id"].ToString()));
                                Debug.Log("沒有找到===》" + (msg["listSpoit"][i]["material"][j]["objectTransform"].ToJson()));
            }
                        }
                    }

                    usi.SpotsList.Add(si.id,si);
                    Debug.Log("UI   Data   添加d景点===>" + si.name+"_"+ si.triggerImageMark);
                }
            }
        }

        usi.vufroiaTrigger = new VufroiaTrigger();
        //  usi.vufroiaTrigger.init(msg);
        usi.vufroiaTrigger.msg = msg;
        usi.vufroiaTrigger.usi = usi;
      
        SceneList.Add(usi.id, usi);
        foreach (var usi2 in UserSceneManager.Instance.SceneList.Values)
        {
            foreach (var si in usi2.SpotsList.Values)
            {
                foreach (var item in si.modelList.Keys)
                {
                    for (int ij = 0; ij < si.modelList[item].materialList.Count; ij++)
                    {

                        Debug.Log("測試====》" + si.modelList[item].materialList[ij].name+"_" + si.triggerImageMark);
                    }
                }
            }
        }
        Debug.Log("UI   Data   添加场景===>"+ usi.id);
        now++;
        if(max<=now)
        {
            callback?.Invoke(true);
        }
    }
    public static int indexa=0;
    public string nowId;
    public void gotoScene(string id)
    {
        nowId = id;
        if (SceneList.ContainsKey(id))
        SceneList[id].load();
        DataManager.Instance.ProjectID = int.Parse(id);

        JsonData msg = UserSceneManager.smsg;

        smsg = msglist[id];
        GameScene.Instance.o20.SetActive(true);
    }

        public Dictionary<string, UserSceneItem> GetScenes()
    {
        return SceneList;
    }

    
}