using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fort23.Core;
using Fort23.Mono;
using Fort23.UTool;
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
#endif
using UnityEngine.Experimental.Rendering;
using UnityEngine.Serialization;
using UnityEngine.U2D;
using UnityEngine.UI.PackgTool;
namespace UnityEngine.UI
{
    /// 
    /// Image is a textured element in the UI hierarchy.
    /// 
    [RequireComponent(typeof(CanvasRenderer))]
    [AddComponentMenu("GameObject/UI/MyImage", 12)]
    /// 
    ///   Displays a Sprite inside the UI System.
    /// 
    public class MyImage : Image
    {
        public string icon_name
        {
            get { return _icon_name; }
            set
            {
                _icon_name = value;
                ReashUI();
            }
        }
#if UNITY_EDITOR
        [MenuItem("GameObject/UI/图集UI", false, 1)]
        static public void AddImage(MenuCommand menuCommand)
        {
            GameObject parent = menuCommand.context as GameObject;
            if (parent == null)
            {
                return;
            }
            GameObject go = new GameObject("myImage");
            go.AddComponent();
            go.transform.SetParent(parent.transform);
            Selection.activeGameObject = go;
        }
#endif
        // private Sprite _packSprite;
        //
        // public Sprite GetPackSprite
        // {
        //     get { return _packSprite; }
        // }
        [SerializeField] private string _icon_name;
        [SerializeField] public bool isNotLoadDeftIcon;
        [SerializeField] public SpriteAtlas CurrSpriteAtlas;
#if UNITY_EDITOR
        [SerializeField] public PackInfo packInfo;
#endif
        private UILoadSpriteHand _uiLoadSpriteHand;
        public float imageH;
        public System.Action onSpriteAlter;
        protected override void Awake()
        {
            if (Application.isPlaying && isNotLoadDeftIcon)
            {
                return;
            }
            if (!string.IsNullOrEmpty(_icon_name))
            {
                icon_name = _icon_name;
            }
        }
     
      
        protected override void OnDestroy()
        {
            if (_uiLoadSpriteHand != null)
            {
                _uiLoadSpriteHand.ReleaseUI();
                _uiLoadSpriteHand = null;
            }
            base.OnDestroy();
        }
        public void ReashUI()
        {
            if (CurrSpriteAtlas != null && !string.IsNullOrEmpty(_icon_name))
            {
                Sprite loadSprite = CurrSpriteAtlas.GetSprite(_icon_name);
                if (loadSprite == null)
                {
                    if (Application.isPlaying)
                    {
                        SpriteAtlas spriteAtlas = UGUIPackManager.Instance.GetSpriteAtlas(_icon_name);
                        if (spriteAtlas != null)
                        {
                            loadSprite = spriteAtlas.GetSprite(_icon_name);
                        }
                        if (loadSprite == null)
                        {
                            enabled = false;
                            UGUIIamgeTool.Load(_icon_name, delegate(UILoadSpriteHand sprite1)
                            {
                                enabled = true;
                                if (Application.isPlaying)
                                {
                                    if (_uiLoadSpriteHand != null)
                                    {
                                        _uiLoadSpriteHand.ReleaseUI();
                                    }
                                }
                                _uiLoadSpriteHand = sprite1;
                                if (sprite1 == null)
                                {
                                    SetSprite(null);
                                }
                                else
                                {
                                    SetSprite(sprite1.GetSprite());
                                }
                            });
                        }
                        else
                        {
                            SetSprite(loadSprite);
                        }
                    }
                }
                else
                {
                    SetSprite(loadSprite);
                }
            }
            else if (!string.IsNullOrEmpty(_icon_name) && sprite == null)
            {
                if (Application.isPlaying)
                {
                    enabled = false;
                    UGUIIamgeTool.Load(_icon_name, delegate(UILoadSpriteHand sprite1)
                    {
                        enabled = true;
                        if (_uiLoadSpriteHand != null)
                        {
                            _uiLoadSpriteHand.ReleaseUI();
                        }
                        _uiLoadSpriteHand = sprite1;
                        if (sprite1 == null)
                        {
                            SetSprite(null);
                        }
                        else
                        {
                            SetSprite(sprite1.GetSprite());
                        }
                    });
                }
            }
            else if (!string.IsNullOrEmpty(_icon_name))
            {
                if (Application.isPlaying)
                {
                    enabled = false;
                    UGUIIamgeTool.Load(_icon_name, delegate(UILoadSpriteHand sprite1)
                    {
                        enabled = true;
                        if (sprite1 != null)
                        {
                            Sprite sp = sprite1.GetSprite();
                            if (sp != null)
                            {
                                if (!sp.name.Equals(_icon_name))
                                {
                                    sprite1.ReleaseUI();
                                    return;
                                }
                            }
                        }
                        if (_uiLoadSpriteHand != null)
                        {
                            _uiLoadSpriteHand.ReleaseUI();
                        }
                        _uiLoadSpriteHand = sprite1;
                        if (sprite1 == null)
                        {
                            SetSprite(null);
                        }
                        else
                        {
                            SetSprite(sprite1.GetSprite());
                        }
                    });
                }
            }
        }
        private void SetSprite(Sprite sprite)
        {
            this.sprite = sprite;
            if (sprite != null)
            {
                onSpriteAlter?.Invoke();
            }
        }
        /// 
        /// 是否置灰
        /// 
        public bool IsGray
        {
            get { return _isGray; }
            set
            {
                if (!_isGray.Equals(value))
                {
                    _isGray = value;
                    if (_isGray)
                    {
                        base.material = UIManager.Instance.uiGray;
                    }
                    else
                    {
                        if (base.material != null)
                        {
                            base.material = null;
                        }
                        base.material = defaultMaterial;
                    }
                }
            }
        }
        private bool _isGray;
        public override void GraphicUpdateComplete()
        {
            SetPack();
        }
#if UNITY_EDITOR
        [ContextMenu("重新设置图片")]
        public void SetPackEditor()
        {
            if (packInfo != null && CurrSpriteAtlas != null)
            {
                string assetName = icon_name;
                if (string.IsNullOrEmpty(icon_name) && sprite != null)
                {
                    assetName = sprite.name;
                }
                var loadSprite = CurrSpriteAtlas.GetSprite(assetName);
                bool isoK = loadSprite != null;
                if (isoK)
                {
                    SetSprite(loadSprite);
                }
            }
        }
        [ContextMenu("自动匹配图集")]
        public void CompareSpritesInAtlas()
        {
            if (sprite == null)
                return;
            string targetPath = AssetDatabase.GetAssetPath(sprite);
            if (string.IsNullOrEmpty(targetPath))
            {
                LogTool.Error("无法获取目标 Sprite 的源文件路径");
                return;
            }
            string relativePath = targetPath.Substring("Assets/".Length);
            string absolutePath = Path.Combine(Application.dataPath, relativePath);
            string targetMD5 = MD5Helper.FileMD5(absolutePath);
            foreach (var allPackgInfo in UGUICacheInfo.uguiPackDB.allPackgInfos)
            {
                string path = Application.dataPath + allPackgInfo.PackageJsonPath;
                string jsonPath = File.ReadAllText(path);
                TextrueJson textrueJson = JsonUtility.FromJson(jsonPath);
                for (int i = 0; i < textrueJson.newTextureJson.Count; i++)
                {
                    string texturePath = "Art/UIAssets" + textrueJson.newTextureJson[i].filePath;
                    texturePath = Path.Combine(Application.dataPath, texturePath);
                    string spriteMD5 = MD5Helper.FileMD5(texturePath);
                    if (spriteMD5 == targetMD5)
                    {
                        LogTool.Log(
                            $"找到匹配的 Sprite: {textrueJson.newTextureJson[i].textrueName},所在图集: {allPackgInfo.packName},源文件: {targetPath}");
                        packInfo = allPackgInfo;
                        CurrSpriteAtlas = UGUICacheInfo.GetSpriteAtlas(allPackgInfo.packName);
                        icon_name = textrueJson.newTextureJson[i].textrueName;
                        ReashUI();
                        return;
                    }
                }
            }
            LogTool.Log("未找到任何匹配的 Sprite");
        }
#endif
        private void SetPack()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                bool isoK = false;
                if (packInfo != null && CurrSpriteAtlas != null)
                {
                    string assetName = icon_name;
                    if (string.IsNullOrEmpty(icon_name) && sprite != null)
                    {
                        assetName = sprite.name;
                    }
                    isoK = CurrSpriteAtlas.GetSprite(assetName) != null;
                    if (!isoK) //没在在图集里面找到图片了,需要去其他地方查找(删除图集)
                    {
                        SpriteAtlas newAtlas = UGUICacheInfo.GetSpriteAtlas(assetName);
                        if (newAtlas != null)
                        {
                            CurrSpriteAtlas = newAtlas;
                            icon_name = assetName;
                        }
                        else
                        {
                            sprite = null;
                        }
                    }
                    else if (string.IsNullOrEmpty(icon_name) || sprite == null)
                    {
                        icon_name = assetName;
                    }
                }
                else if (CurrSpriteAtlas == null && packInfo != null && !string.IsNullOrEmpty(packInfo.packgJsonPath) &&
                         sprite != null) //没有图集 但是由功能管理器添加的UI (添加图集)
                {
                    string name = sprite.name;
                    SpriteAtlas newAtlas = UGUICacheInfo.GetSpriteAtlas(name);
                    if (newAtlas != null)
                    {
                        CurrSpriteAtlas = newAtlas;
                        icon_name = _icon_name;
                    }
                }
            }
#endif
        }
        public enum GradientDirection
        {
            Vertical,
            Horizontal
        }
        [SerializeField] private bool useGradient = false;
        [SerializeField] private Color topOrLeftColor = Color.white;
        [SerializeField] private Color bottomOrRightColor = Color.black;
        [SerializeField] private GradientDirection direction = GradientDirection.Vertical;
        public bool UseGradient
        {
            get => useGradient;
            set
            {
                useGradient = value;
                SetVerticesDirty();
            }
        }
        public Color TopOrLeftColor
        {
            get => topOrLeftColor;
            set
            {
                topOrLeftColor = value;
                SetVerticesDirty();
            }
        }
        public Color BottomOrRightColor
        {
            get => bottomOrRightColor;
            set
            {
                bottomOrRightColor = value;
                SetVerticesDirty();
            }
        }
        public GradientDirection Direction
        {
            get => direction;
            set
            {
                direction = value;
                SetVerticesDirty();
            }
        }
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            base.OnPopulateMesh(vh);
            List verts = new List();
            vh.GetUIVertexStream(verts);
            if (imageH <= 0)
            {
                float minY = 11111;
                float maxY = -111111;
             
                for (int i = 0; i < verts.Count; i++)
                {
                    UIVertex vertex = verts[i];
                    float y = vertex.position.y;
                    if (y < minY)
                    {
                        minY = y;
                    }
                    if (y > maxY)
                    {
                        maxY = y;
                    }
                }
                imageH = maxY - minY;
            }
            if (!useGradient || vh.currentVertCount == 0)
                return;
            
            for (int i = 0; i < verts.Count; i += 6)
            {
                ApplyGradientToQuad(verts, i);
            }
            vh.Clear();
            vh.AddUIVertexTriangleStream(verts);
        }
        private void ApplyGradientToQuad(List verts, int startIndex)
        {
            if (startIndex + 5 >= verts.Count)
                return;
            float top = verts[startIndex].position.y;
            float bottom = verts[startIndex].position.y;
            float left = verts[startIndex].position.x;
            float right = verts[startIndex].position.x;
            for (int i = 1; i < 6; i++)
            {
                var pos = verts[startIndex + i].position;
                top = Mathf.Max(top, pos.y);
                bottom = Mathf.Min(bottom, pos.y);
                left = Mathf.Min(left, pos.x);
                right = Mathf.Max(right, pos.x);
            }
            for (int i = 0; i < 6; i++)
            {
                var vert = verts[startIndex + i];
                var pos = vert.position;
                float t = direction == GradientDirection.Vertical
                    ? Mathf.InverseLerp(bottom, top, pos.y)
                    : Mathf.InverseLerp(left, right, pos.x);
                Color gradientColor = Color.Lerp(bottomOrRightColor, topOrLeftColor, t);
                gradientColor.r *= color.r;
                gradientColor.g *= color.g;
                gradientColor.b *= color.b;
                gradientColor.a *= color.a;
                vert.color = gradientColor;
                verts[startIndex + i] = vert;
            }
        }
    }
}