using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public abstract class BasePanel : MonoBehaviour
{
    private Dictionary<string, List<UIBehaviour>> controlsdic = new Dictionary<string, List<UIBehaviour>>();
    private Dictionary<string, SpriteRenderer> spritesdic = new Dictionary<string, SpriteRenderer>();
    protected virtual void Awake()
    {
        GetAllControls<Button>();
        GetAllControls<Text>();
        GetAllControls<Image>();
        GetAllControls<Toggle>();
        GetAllControls<Slider>();
        GetAllControls<ScrollRect>();
        GetAllControls<GridLayoutGroup>();
        GetAllControls<ToggleGroup>();
        GetAllSprites();
    }

    private void GetAllControls<T>() where T:UIBehaviour
    {
        T[] controls = GetComponentsInChildren<T>();

        for (int i = 0; i < controls.Length; i++)
        {
            if (controlsdic.ContainsKey(controls[i].gameObject.name))
            {
                controlsdic[controls[i].gameObject.name].Add(controls[i]);
            }
            else
            {
                controlsdic.Add(controls[i].gameObject.name, new List<UIBehaviour>() { controls[i] });
            }
        }
    }

    public T GetControl<T>(string name) where T : UIBehaviour 
    {
        if (controlsdic.ContainsKey(name))
        {
            for (int i = 0; i < controlsdic[name].Count; i++)
            {
                if (controlsdic[name][i] is T)
                {
                    return controlsdic[name][i] as T;
                }
            }
        }
        Debug.LogError("没有找到" + name +"的"+typeof(T).ToString()+"组件");
        return null;
    }

    private void GetAllSprites() 
    {
        SpriteRenderer[] sprites = GetComponentsInChildren<SpriteRenderer>();
        for (int i = 0; i < sprites.Length; i++)
        {
            spritesdic.Add(sprites[i].gameObject.name, sprites[i]);
        }
    }

    public SpriteRenderer GetSpriteRender(string name) 
    {
        if (spritesdic.ContainsKey(name))
        {
            return spritesdic[name];
        }
        else
        {
            Debug.LogError("没有找到" + name + "的SpriteRenderer组件");
            return null;
        }
    }

    public abstract void OnInit(object data = null);

    public abstract void OnRefresh(object data = null);

    public abstract void OnHide(object data = null);
   
}
