using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI.PackgTool;

namespace UnityEditor.UI
{
    public class UGUISpriteAtlasSelectWindow : EditorWindow
    {
        private static System.Action<SpriteAtlas, Sprite> callBack;
        private static string jsonPackPath;

        private static List<SpriteAtlas> atlasList = new List<SpriteAtlas>();
        private static string spriteAtlasPath = "/Res/UIAtlas";
        float mClickTime = 0f;
        private static List<Texture> allSprite = new List<Texture>();
        private List<SpriteAtlas> currSelectSpriteAtlas = new List<SpriteAtlas>();
        private Sprite currSelectSprite;
        private static string packName;

        private static PackInfo packInfo;

        private string findText;
        public static void OpenWidow(PackInfo packInfo, System.Action<SpriteAtlas, Sprite> callBack)
        {
            UGUISpriteAtlasSelectWindow.packInfo = packInfo;
            allSprite.Clear();
            jsonPackPath = packInfo.PackageJsonPath;
            UGUISpriteAtlasSelectWindow.callBack = callBack;
            atlasList = UGUICacheInfo.atlasList;
            string  path = Application.dataPath + UGUISpriteAtlasSelectWindow.jsonPackPath;

            List<string> gameAllModel = new List<string>();
            string jsonPath = File.ReadAllText(path);
            TextrueJson textrueJson = JsonUtility.FromJson<TextrueJson>(jsonPath);
         
            packName = textrueJson.packName;
            for (int i = 0; i < textrueJson.newTextureJson.Count; i++)
            {
                string texturePath = "Assets/Art/UIAssets"+ textrueJson.newTextureJson[i].filePath;
                Texture texture = AssetDatabase.LoadAssetAtPath<Texture>(texturePath);
                if (texture != null)
                {
                    allSprite.Add(texture);
                }
            }


            UGUISpriteAtlasSelectWindow window = EditorWindow.GetWindow<UGUISpriteAtlasSelectWindow>();
            window.currSelectSpriteAtlas.Clear();
            window.name = "选择一个一个当前图片";
            window.Show();
        }


        Vector2 pos = Vector2.zero;


        private PackInfo GetPackInfo(TextrueJson textrueJson)
        {
            for (int i = 0; i < UGUICacheInfo.uguiPackDB.allPackgInfos.Count; i++)
            {
                if (UGUICacheInfo.uguiPackDB.allPackgInfos[i].packName.Equals(textrueJson.packName))
                {
                    return UGUICacheInfo.uguiPackDB.allPackgInfos[i];
                }
            }


            PackInfo packInfo = UGUICacheInfo.AddNewPackInfo(jsonPackPath, textrueJson);
            return packInfo;
        }

        private void GUISpriteAtlas()
        {
            GUI.DrawTexture(new Rect(EditorGUIUtility.currentViewWidth / 2 - 64, 0, 128, 128), currSelectSprite.texture);
            GUILayout.Space(150);
            GUILayout.Label($"请选择{currSelectSprite.name}需要使用的图集");
            pos = GUILayout.BeginScrollView(pos);
            for (int i = 0; i < currSelectSpriteAtlas.Count; i++)
            {
                if (GUILayout.Button(currSelectSpriteAtlas[i].name))
                {
                    GUILayout.EndScrollView();
                    callBack?.Invoke(currSelectSpriteAtlas[i], currSelectSprite);
                    Close();
                    return;
                }
            }

            GUILayout.EndScrollView();
        }


        private List<Texture> GetShowTextrue()
        {
            if (string.IsNullOrEmpty(findText))
            {
                return allSprite;
            }

            List<Texture> showSpr = new List<Texture>();
            for (int i = 0; i < allSprite.Count; i++)
            {
                if (allSprite[i].name.Contains(findText))
                {
                    showSpr.Add(allSprite[i]);
                }
            }

            return showSpr;
        }

        private Sprite GetSprite(Texture t)
        {
          string p=  AssetDatabase.GetAssetPath(t);
         return AssetDatabase.LoadAssetAtPath<Sprite>(p);
        }

        private void GUISprite()
        {
            findText = GUI.TextField(new Rect(0, 10, 256, 24),findText);
            if ( GUI.Button(new Rect(256, 10, 24, 24),"x"))
            {
                findText = "";
            }
            float size = 80f;
            float padded = size + 10f;
            Rect rect = new Rect(10f, 0, size, size);
            int screenWidth = (int) EditorGUIUtility.currentViewWidth;
            int columns = Mathf.FloorToInt(screenWidth / padded);
            if (columns < 1) columns = 1;
            GUILayout.Space(50);
            pos = GUILayout.BeginScrollView(pos);
            int offset = 0;
            int rows = 1;

            List<Texture> showSpr=   GetShowTextrue();
            
            while (offset < showSpr.Count)
            {
                int col = 0;
                rect.x = 10f;
                GUILayout.BeginHorizontal();
                for (; offset < showSpr.Count; offset++)
                {
                    
                    if (GUI.Button(rect, ""))
                    {
                        float delta = Time.realtimeSinceStartup - mClickTime;
                        mClickTime = Time.realtimeSinceStartup;
                        if (delta < 0.5f)
                        {
                            List<SpriteAtlas> spriteAtlasList = UGUICacheInfo.GetAllSpriteAtlas(showSpr[offset].name);
                            if (spriteAtlasList.Count > 1)//找到匹配的图集
                            {
                                SpriteAtlas currSpriteAtlas = spriteAtlasList[0];
                                for (int i = 0; i < spriteAtlasList.Count; i++)
                                {
                                    if (spriteAtlasList[i].name.Equals(packInfo.packName))
                                    {
                                        currSpriteAtlas = spriteAtlasList[i];
                                        break;
                                    }
                                }
                                callBack?.Invoke(currSpriteAtlas, GetSprite(showSpr[offset]));
                                Close();
                            }
                            else if (spriteAtlasList.Count == 1)
                            {
                                callBack?.Invoke(spriteAtlasList[0], GetSprite(showSpr[offset]));
                                Close();
                            }
                            else
                            {
                                callBack?.Invoke(null,  GetSprite(showSpr[offset]));
                                Close();
                            }
                        }
                    }

                    GUI.DrawTexture(rect, showSpr[offset],ScaleMode.ScaleToFit);
                    GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);
                    GUI.contentColor = new Color(1f, 1f, 1f, 0.7f);
                    GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), showSpr[offset].name);
                    GUI.contentColor = Color.white;
                    GUI.backgroundColor = Color.white;
                    rect.x += padded;
                    if (++col >= columns)
                    {
                        ++offset;
                        break;
                    }
                }

                GUILayout.EndHorizontal();
                GUILayout.Space(padded);
                rect.y += padded + 26;


                ++rows;
            }

            GUILayout.Space(rows * 26);
            GUILayout.EndScrollView();
        }

        void OnGUI()
        {
            if (currSelectSpriteAtlas.Count > 0)
            {
                GUISpriteAtlas();
            }
            else
            {
                GUISprite();
            }
        }
    }
}