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

/// <summary>
/// 透明脚本
/// </summary>
public class TransparentGlow : MonoBehaviour
{
    public bool isTransparentGlow = false;

    private List<MeshRenderer> meshRenderers;
    /// <summary>
    /// 自身的
    /// </summary>
    private List<Material> materials;
    /// <summary>
    /// 复制出来的
    /// </summary>
    public List<Material> empty = new List<Material>();

    public Shader TransparentGlow_Shader;

    public List<MeshRenderer> MeshRenderers
    {
        get
        {
            if (meshRenderers == null)
                meshRenderers = GetComponentsInChildren<MeshRenderer>().ToList();
            return meshRenderers;
        }
    }

    public List<Material> Materials
    {
        get
        {
            if (materials == null)
            {
                materials = new List<Material>();
                MeshRenderers.ForEach(render =>
                {
                    Array.ForEach(render.materials, (_mat) =>
                    {
                        if (!materials.Contains(_mat))
                        {
                            materials.Add(_mat);
                            Material _emp = new Material(_mat);
                            empty.Add(_emp);
                        }
                    });
                });
            }
            return materials;
        }
    }


    // Start is called before the first frame update
    void Start()
    {
        if (TransparentGlow_Shader == null)
            TransparentGlow_Shader = Resources.Load<Shader>("TransparentGlow");
    }

    // Update is called once per frame
    void Update()
    {

    }

    /// <summary>
    /// 透明
    /// </summary>
    [ContextMenu("透明")]
    public void F1()
    {
        for (int i = 0; i < Materials.Count; i++)
        {
            Materials[i].shader = TransparentGlow_Shader;
        }
    }

    /// <summary>
    /// 恢复原材质
    /// </summary>
    [ContextMenu("恢复原材质")]
    public void F2()
    {
        for (int i = 0; i < Materials.Count; i++)
        {
            Materials[i].shader = empty[i].shader;
        }
    }

    [ContextMenu("添加点击组件")]
    public void F3()
    {
        TransparentGlow[] components = FindObjectsOfType<TransparentGlow>(false);

        foreach (var item in components)
        {
            ClickEvent clickEvent = item.GetComponent<ClickEvent>();
            BoxCollider boxCollider = item.GetComponent<BoxCollider>();
            if (item.gameObject.activeSelf)
            {
                if (!clickEvent) item.gameObject.AddComponent<ClickEvent>();
                if (!boxCollider)
                {
                    var a = item.gameObject.AddComponent<BoxCollider>();
                    a.isTrigger = true;
                }
            }
        }
    }
}
