using LitJson;
using Newtonsoft.Json.Linq;
using SC.XR.Unity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using Blue;
using UnityEngine.Networking;

public class SceneChoose : BaseUI
{
    private Button m_LeftBtn;
    private Button m_RightBtn;
    private Button m_OkBtn;

    private GameObject m_SceneItem;
    private Transform m_ScenePanel;
    /// <summary>
    /// 场景选择面板中确认的场景
    /// </summary>
    private SceneValue m_CurrentData;
    private List<SChooseItem> m_Items;

    private CarouselImage m_CarImage;

    private List<SceneValue> m_SceneData;

    protected override void OnAwake()
    {
        base.OnAwake();
        m_SceneData = new List<SceneValue>();
        m_Items = new List<SChooseItem>();
        m_CurrentData = null;
        m_LeftBtn = CacheTransform.Find("Left").GetComponent<Button>();
        m_RightBtn = CacheTransform.Find("Right").GetComponent<Button>();
        m_OkBtn = CacheTransform.Find("OK").GetComponent<Button>();

        m_SceneItem = CacheTransform.Find("SceneItem").gameObject;
        m_ScenePanel = CacheTransform.Find("ScenePanel");

        m_ScenePanel.GetComponent<RectTransform>().sizeDelta = new Vector2(400, 150);

        m_LeftBtn.onClick.AddListener(ONClickLeftBtn);
        m_RightBtn.onClick.AddListener(ONClickRightBtn);
        m_OkBtn.onClick.AddListener(OnClickOKBtn);
    }

    #region UI监听事件

    private void ONClickLeftBtn()
    {
        if (m_CarImage != null)
        {
            m_CarImage.MoveToIndex(m_CarImage.CurrentIndex + 1);
        }
    }

    private void ONClickRightBtn()
    {
        if (m_CarImage != null)
        {
            m_CarImage.MoveToIndex(m_CarImage.CurrentIndex - 1);
        }
    }

    private void OnClickOKBtn()
    {
        if (m_CurrentData != null)
        {
            //根据场景数据,下载资源
            Debug.Log("选择的场景为:" + m_CurrentData.name);

            SendSceneDetail detail = new SendSceneDetail();
            detail.id = m_CurrentData.id;
            string str = JsonConvert.SerializeObject(detail);

            this.GetModel<ISceneModel>().sceneID = m_CurrentData.id;
            this.SendCommand(new PointFileGetUrlCommand(detail.id, PointFileType.json));
            this.SendCommand(new PointFileGetUrlCommand(detail.id, PointFileType.bytes));
            this.SendCommand(new PointPosRotDownloadCommand(detail.id));
            this.SendCommand(new GetReferencePosCommand(detail.id));
            this.SendCommand(new MinMapGetSetCommand());

            HttpTool.Instance.PostTest("/project/detail", str, (mes) =>
            {
                if (mes == "UnityWebRequest Error") return;
                JObject jObject = JObject.Parse(mes);
                if (jObject["code"].ToString() == "200")
                {
                    mes = jObject["data"].ToString();
                    SceneValue scene = JsonConvert.DeserializeObject<SceneValue>(mes);
                    GameManager.Instance.MapPicUrl = scene.backgroundImages[0].base64;
                    GameManager.Instance.GetMinMap(scene);
                    GetSNInit();
                }
                else
                {
                    UIManager.Instance.HideUI(UINameConfig.LoadingPanel);
                    Module_Notice.getInstance.SetNoticeInfo("场景地图获取失败", "请至网页端检查场景数据", NoticeType.Normal, 1.7f);
                    Module_Notice.getInstance._Follower.WindowAnchor = TextAnchor.UpperCenter;
                    Module_Notice.getInstance.StartNotice(3f);
                    UIManager.Instance.HideUI(UINameConfig.LoadingPanel);
                }
            });
        }
        else
        {
            ///Module_Notice.getInstance.SetNoticeInfo("未选择导览场景", "请先勾选要进入的场景", NoticeType.Normal, 1.7f);
            //Module_Notice.getInstance._Follower.WindowAnchor = TextAnchor.UpperCenter;
            //Module_Notice.getInstance.StartNotice(3f);
            this.SendCommand(new InstantiateCommand(InstantiateSystem.Instance.BlueObject.WarningPopUp));
        }
    }

    private void GetSNInit()
    {
        // 选择场景
        SendInit send = new SendInit();

        send.sn = SendSN.GetSN();
        //send.sn = API_GSXR_Slam.SlamManager.plugin.SN;

        send.projectId = m_CurrentData.id;
        string jsonString = JsonConvert.SerializeObject(send);
        UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), (int)ELoadState.sceneChoose);
        //通过SN获取场景数据
        HttpTool.Instance.PostTest("/sn/init", jsonString, (message) =>
        {
            if (message == "UnityWebRequest Error") return;
            Debug.Log("SN:" + send.sn);
            Debug.Log("通过SN获取场景数据:" + message);
            if (!string.IsNullOrWhiteSpace(message))
            {
                JObject jobject = JObject.Parse(message);

                if (jobject.GetValue("code") != null)
                {
                    if (jobject["code"].ToString() == "400")
                    {
                        UIManager.Instance.HideUI(UINameConfig.LoadingPanel);
                        //Module_Notice.getInstance.SetNoticeInfo("场景数据获取失败", jobject["data"].ToString(), NoticeType.Normal, 1.7f);
                        //Module_Notice.getInstance._Follower.WindowAnchor = TextAnchor.UpperCenter;
                        //Module_Notice.getInstance.StartNotice(3f);
                    }
                }
                else
                {
                    message = jobject["data"].ToString();
                    GameManager.Instance.text.text = message;
                  //  SceneValue scene = JsonMapper.ToObject<SceneValue>(message);

                    SceneValue scene = JsonConvert.DeserializeObject<SceneValue>(message);
                    DataManager.Instance.CurrentScene = scene;
                    DataManager.Instance.ProjectID = m_CurrentData.id;
                    UIManager.Instance.ShowUI(UINameConfig.LoadingPanel, typeof(LoadingPanel), (int)ELoadState.createScene);
                    StartCoroutine(GetSpoitValueDetail(scene));
                    GameManager.Instance.text.text = JsonConvert.SerializeObject(scene);
                    Debug.Log("当前选择场景数据: " + JsonConvert.SerializeObject(scene));
                }
            }
            else
            {
                UIManager.Instance.HideUI(UINameConfig.LoadingPanel);
            }
           
        });
    }


    private IEnumerator GetSpoitValueDetail(SceneValue scene)
    {
        var spoits = scene.listSpoit;
        for (int i = 0; i < spoits.Count; i++)
        {
            //通过ID获取场景详情
            SendSceneDetail detail = new SendSceneDetail();
            detail.id = spoits[i].id;
            string jsonString = JsonConvert.SerializeObject(detail);

            yield return StartCoroutine(HttpTool.Instance.PostRequestSpoitDetail("/viewpoint/detail", jsonString, (message) =>
            {
                //Debug.Log("当前选择场景数据: " + message);
                JObject jObject = JObject.Parse(message);
                if (jObject["code"].ToString() == "200")
                {
                    message = jObject["data"].ToString();
                    SpoitValueDetail spoit = JsonConvert.DeserializeObject<SpoitValueDetail>(message);
                    GameManager.Instance.SpoitsValueDetail.Add(spoit.id, spoit);
                }
            }));
        }
        Debug.Log(scene.vuforiaXML);
        string xmlName = Path.GetFileName(scene.vuforiaXML);

        if (xmlName != null)
        {
            xmlName = xmlName.Substring(0, xmlName.Length - 4);
            AppConfigConst.IMAGE_TARGET_FILE_NAME = xmlName;
        }


      

        if (scene.vuforiaXML != null)
        {
            DownloadData xml = new DownloadData();
            string filename = Path.GetFileName(scene.vuforiaXML);
            xml.name = filename;
            xml.type = 8;
            xml.downloadPath = scene.vuforiaXML;
            xml.updateTime = (int)scene.updateTime;
            xml.localSavePath = Application.persistentDataPath + "/StreamingAssets/Vuforia/" + filename;
            DownloadManager.Instance.AddDownloadData(xml);

            DownloadData dat = new DownloadData();
            string filename2 = Path.GetFileName(scene.vuforiaDat);
            dat.name = filename2;
            dat.type = 8;
            dat.downloadPath = scene.vuforiaDat;
            dat.updateTime = (int)scene.updateTime;
            dat.localSavePath = Application.persistentDataPath + "/StreamingAssets/Vuforia/" + filename2;

            DownloadManager.Instance.AddDownloadData(dat);
        }

        yield return new WaitForSeconds(1f);
        //创建场景
        GameManager.Instance.CreateScene(scene);
        Hide();
        
    }

    private void UpdateSceneItem()
    {
        if (m_SceneData == null)
        {
            return;
        }
        ClearItem();
        for (int i = 0; i < m_SceneData.Count; i++)
        {
            var obj = Instantiate(m_SceneItem);
            obj.transform.SetParent(m_ScenePanel);
            var item = obj.AddComponent<SChooseItem>();
            obj.gameObject.SetActive(true);
            obj.transform.localScale = new Vector3(1, 1, 1);
            obj.transform.localEulerAngles = Vector3.zero;

            item.OnSelectScene += OnClickSceneItem;
            item.SceneData = m_SceneData[i];
            item.Init();
            m_Items.Add(item);
        }

        if (m_CarImage == null)
        {
            m_CarImage = m_ScenePanel.gameObject.AddComponent<CarouselImage>();
        }
        m_CarImage.mCellSize = new Vector2(400, 150);
        m_CarImage.mSpacing = new Vector2(0, 0);
        m_CarImage.mAutoLoop = false;
        m_CarImage.mDrag = true;
        m_CarImage.mLoopSpaceTime = 5f;
        m_CarImage.resizeChildren();
    }

    private void OnClickSceneItem(SceneValue item, bool b)
    {
        m_CurrentData = b ? item : null;
    }

    #endregion
    protected override void OnInit()
    {
        base.OnInit();
    }

    protected override void OnShow(object param)
    {
        base.OnShow(param);
        m_SceneData = (List<SceneValue>)param;
        UpdateSceneItem();
    }

    protected override void OnHide()
    {
        base.OnHide();
    }
    /// <summary>
    /// 清除所有场景信息
    /// </summary>
    private void ClearItem()
    {
        while (m_Items.Count > 0)
        {
            var item = m_Items[0];
            m_Items.RemoveAt(0);
            Destroy(item.gameObject);
        }
    }
}