using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TextureCombineEditor;
using UnityEditor;
using UnityEngine;

namespace Thousandto.DIY
{
    public class ChangeUITextureSize : EditorWindow
    {
        [MenuItem("Ares/UITexture出包优化(出包时前使用优化内存)")]
        static void Open()
        {
            if (Application.isPlaying)
            {
                return;
            }
            var win = (ChangeUITextureSize)EditorWindow.GetWindow(typeof(ChangeUITextureSize));
            LoadWhiteNames();
            win.Show();
        }

        private string _prefabPath = string.Empty;
        private const string WhiteNameKey = "ChangeUITextureSizeWhiteName";
        private static List<string> _whiteNames = null;
        private string _addWhiteText = string.Empty;
        //保存图片优化白名单的文件
        private static string _whiteTexCfgFile = "../Main/Assets/GameAssets/ExportResources/EditorConfig/TextureConfig.txt";

        static void LoadWhiteNames()
        {
            _whiteNames = new List<string>();
            if (File.Exists(_whiteTexCfgFile))
            {
                List<string> cfgFileNameList = new List<string>(File.ReadAllLines(_whiteTexCfgFile));
                for (int i = 0; i < cfgFileNameList.Count; i++)
                {
                    _whiteNames.Add(cfgFileNameList[i].Trim());
                }
            }
            var names = PlayerPrefs.GetString(WhiteNameKey);
            if (!string.IsNullOrEmpty(names))
            {
                var paramArray = names.Split(';');
                for (int i = 0; i < paramArray.Length; ++i)
                {
                    if (!string.IsNullOrEmpty(paramArray[i]) && !_whiteNames.Contains(paramArray[i]))
                    {
                        _whiteNames.Add(paramArray[i]);
                    }
                }
                PlayerPrefs.DeleteKey(WhiteNameKey);
                SaveWhiteNames();
            }
        }
        static void SaveWhiteNames()
        {
            var strBuilder = new StringBuilder(10240);
            for (int i = 0; i < _whiteNames.Count; ++i)
            {
                if (!string.IsNullOrEmpty(_whiteNames[i]))
                {
                    strBuilder.AppendLine(_whiteNames[i]);
                }
            }
            if (!File.Exists(_whiteTexCfgFile))
            {
                File.Create(_whiteTexCfgFile).Dispose();
            }
            File.WriteAllText(_whiteTexCfgFile, strBuilder.ToString());
        }

        void OnGUI()
        {
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("选择路径");
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("需要优化UITexture路径");
            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("浏览", GUILayout.Width(50)))
            {
                _prefabPath = EditorUtility.OpenFolderPanel("ChangeTexture Path", _prefabPath, "");
            }
            if (string.IsNullOrEmpty(_prefabPath))
            {
                EditorGUILayout.LabelField("null...");
            }
            else
            {
                EditorGUILayout.LabelField(_prefabPath);
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();

            EditorGUILayout.BeginVertical();
            GUILayout.Label("白名单(不压缩,用于带文字的图片)");
            bool isSaveWhite = false;
            if(_whiteNames == null)
            {
                LoadWhiteNames();
            }
            for (int i = _whiteNames.Count - 1; i >= 0; --i)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label(_whiteNames[i]);
                if (GUILayout.Button("X", GUILayout.Width(30)))
                {
                    _whiteNames.RemoveAt(i);
                    isSaveWhite = true;
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUILayout.BeginHorizontal();
            _addWhiteText = EditorGUILayout.TextField(_addWhiteText);
            if (GUILayout.Button("添加白名单", GUILayout.Width(100)))
            {
                if (!string.IsNullOrEmpty(_addWhiteText) && !_whiteNames.Contains(_addWhiteText))
                {
                    _whiteNames.Add(_addWhiteText);
                    isSaveWhite = true;
                }
            }
            if (isSaveWhite)
            {
                SaveWhiteNames();
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();


            if (GUILayout.Button("开始优化", GUILayout.Width(100)))
            {
                if (string.IsNullOrEmpty(_prefabPath))
                    return;
                if (Directory.Exists(_prefabPath))
                {
                    DirectoryInfo direction = new DirectoryInfo(_prefabPath);
                    FileInfo[] files = direction.GetFiles("*.*", SearchOption.TopDirectoryOnly);

                    var doCount = 0;
                    for (int i = 0; i < files.Length; ++i)
                    {
                        var path = files[i].FullName;
                        if (path.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase) || path.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase))
                        {
                            path = path.Replace('\\', '/');
                            var starIndex = path.IndexOf("/Assets/", 0);
                            path = path.Remove(0, starIndex + 1);

                            var name = files[i].Name;
                            starIndex = name.LastIndexOf('.');
                            name = name.Remove(starIndex);
                            if (SetTextureFormat(path))
                            {
                                ++doCount;
                            }
                        }
                    }
                    UnityEngine.Debug.LogErrorFormat("优化完成,共优化{0}张图片", doCount);
                }
            }
        }

        public static bool SetTextureFormat(string path)
        {
            if(_whiteNames == null)
            {
                LoadWhiteNames();
            }
            path = path.Replace('\\', '/');
            var startIndex = path.LastIndexOf('/');
            var endIndex = path.LastIndexOf('.');
            string fileName = path.Substring(startIndex + 1, endIndex - startIndex - 1);

            AssetImporter ai = AssetImporter.GetAtPath(path);
            bool isChanged = false;
            if (ai != null && ai is UnityEditor.TextureImporter)
            {
#if UNITY_STANDALONE
                //pc版本资源不做图片压缩
                if (true)
#else
                if (_whiteNames.Contains(fileName))
#endif
                {
                    TextureImporter textureImporter = (TextureImporter)ai;
                    if (textureImporter.isReadable != false)
                    {
                        isChanged = true;
                        textureImporter.isReadable = false;
                    }
                    if (textureImporter.textureType != TextureImporterType.GUI)
                    {
                        isChanged = true;
                        textureImporter.textureType = TextureImporterType.GUI;
                    }
                    if (textureImporter.mipmapEnabled != false)
                    {
                        isChanged = true;
                        textureImporter.mipmapEnabled = false;
                    }
                    if (textureImporter.alphaSource != TextureImporterAlphaSource.FromInput)
                    {
                        isChanged = true;
                        textureImporter.alphaSource = TextureImporterAlphaSource.FromInput;
                    }
                    if (textureImporter.alphaIsTransparency != true)
                    {
                        isChanged = true;
                        textureImporter.alphaIsTransparency = true;
                    }
                    if (textureImporter.npotScale != TextureImporterNPOTScale.None)
                    {
                        isChanged = true;
                        textureImporter.npotScale = TextureImporterNPOTScale.None;
                    }
                    if (textureImporter.maxTextureSize != 1024)
                    {
                        isChanged = true;
                        textureImporter.maxTextureSize = 1024;
                    }
                    if (textureImporter.textureCompression != TextureImporterCompression.Uncompressed)
                    {
                        isChanged = true;
                        textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
                    }
                }
                else
                {
                    TextureImporter textureImporter = (TextureImporter)ai;
                    if (textureImporter.isReadable != false)
                    {
                        isChanged = true;
                        textureImporter.isReadable = false;
                    }
                    if (textureImporter.textureType != TextureImporterType.GUI)
                    {
                        isChanged = true;
                        textureImporter.textureType = TextureImporterType.GUI;
                    }
                    if (textureImporter.mipmapEnabled != false)
                    {
                        isChanged = true;
                        textureImporter.mipmapEnabled = false;
                    }
                    if (textureImporter.alphaSource != TextureImporterAlphaSource.FromInput)
                    {
                        isChanged = true;
                        textureImporter.alphaSource = TextureImporterAlphaSource.FromInput;
                    }
                    if (textureImporter.alphaIsTransparency != true)
                    {
                        isChanged = true;
                        textureImporter.alphaIsTransparency = true;
                    }
                    if (textureImporter.npotScale != TextureImporterNPOTScale.ToNearest)
                    {
                        isChanged = true;
                        textureImporter.npotScale = TextureImporterNPOTScale.ToNearest;
                    }
                    if (textureImporter.maxTextureSize != 1024)
                    {
                        isChanged = true;
                        textureImporter.maxTextureSize = 1024;
                    }
                    if (textureImporter.textureCompression != TextureImporterCompression.Compressed)
                    {
                        isChanged = true;
                        textureImporter.textureCompression = TextureImporterCompression.Compressed;
                    }
                }
                if (isChanged)
                {
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                }
            }
            return isChanged;
        }
    }
}