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

public abstract class UICommon : MonoBehaviour {

    static Camera m_UICamera;
    public static Camera s_uiCamera
    {
        get
        {
            if (m_UICamera == null)
                m_UICamera = CreateDefaultUICamera();// CreateUICamera(defaultUIWidth, defaultUIHeight,uiCameraLayer, 1 << LayerMask.NameToLayer("UI"),"UICamera");

            return m_UICamera;
        }
        set { m_UICamera = value; }
    }
    static Camera m_uiFXCamera;
    public static Camera s_uiFXCamera
    {
        get
        {
            if (m_uiFXCamera == null)
                m_uiFXCamera = CreateDefaultUIFXCamera();// CreateUICamera(defaultUIWidth, defaultUIHeight, uiFXCameraLayer, 1 << LayerMask.NameToLayer("TransparentFX"), "UIFXCamera"); //CreateUIFXCamera(defaultUIWidth, defaultUIHeight);

            return m_uiFXCamera;
        }
        set { m_uiFXCamera = value; }
    }

    public const int defaultUIWidth = 1080;
    public const int defaultUIHeight = 1920;
    public const int uiCameraLayer = 5;
    public const int uiFXCameraLayer = 6;
    public const int secondUICameraLayer = 7;

    protected Camera uiCamera => s_uiCamera;
    public Camera secondLayerUICamera;

    protected Canvas m_Canvas;

    /// <summary>
    /// 第二层UI
    /// </summary>
    protected Canvas m_SecondCanvas;

    /// <summary>
    /// 是否显示黑色背景
    /// </summary>
    public bool showBlack = false;
    public float blackAlpha = 0.75f;

    public float fadeInTime = 0.2f;
    public float fadeOutTime = 0.4f;

    /// <summary>
    /// 是否采用默认的Alpha淡入淡出动画
    /// </summary>
    public bool UseDefaultFadeInAnim = true;

    public AnimationCurve fadeInCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);
    public AnimationCurve fadeOutCurve = AnimationCurve.EaseInOut(0, 0, 1, 1);

    protected UIAnim m_UIAnim;

    [SerializeField]
    int m_layer = 0;
    public int layer
    {
        get { return m_layer; }
        set {
            m_layer = value;
            if (m_Canvas)
                m_Canvas.sortingOrder = m_layer;
        }
    }

    /// <summary>
    /// 第二层UI，在特效之上
    /// </summary>
    public GameObject SecondLayerUI;

    // Use this for initialization
    public virtual void Awake()
    {

        if (m_UIAnim == null) m_UIAnim = GetComponent<UIAnim>();
        if (m_UIAnim == null) m_UIAnim = gameObject.AddComponent<UIAnim>();

        m_Canvas = gameObject.GetComponent<Canvas>();
        if (m_Canvas == null)
            m_Canvas = gameObject.AddComponent<Canvas>();

        InitCanvas(m_Canvas,s_uiCamera, 1080, 1920);
        // UIUtility.SetUIStretchAll(GetComponent<RectTransform>());

        if(this.SecondLayerUI != null)
        {
            //GameDebug.LogError("创建第二层UI摄像机");

            //有第二层UI则将其移到第二层的Canvas中
            secondLayerUICamera = CreateUICamera(defaultUIWidth, defaultUIHeight, secondUICameraLayer, 1 << LayerMask.NameToLayer("UI"), "SecondLayerUICamera");

            GameObject second = new GameObject("SecondLayer");
            //second.transform.SetParent(transform.parent);
            
            m_SecondCanvas = second.gameObject.AddComponent<Canvas>();
            InitCanvas(m_SecondCanvas, secondLayerUICamera, 1080, 1920);
         //   m_SecondCanvas.renderMode = RenderMode.ScreenSpaceOverlay;
            m_SecondCanvas.sortingOrder = 99;

            SecondLayerUI.transform.SetParent(m_SecondCanvas.transform);
            UIUtility.SetUIStretchAll(SecondLayerUI.GetComponent<RectTransform>());
            SecondLayerUI.transform.localScale = Vector3.one;
        }
        
        if (showBlack)
        {
            m_BlackBG = CreateBlackBG(transform,this.blackAlpha);
        }

    }

    public virtual void Start()
    {
        if (UseDefaultFadeInAnim)
        {
            var rectTransform = GetComponent<RectTransform>();
            UIAnim.GetImgTxtAlpha(rectTransform, out imgAlphas, out txtAlphas, out rawAlphas);
            FadeInAnim();
        }

        Transform secondLayerParent = transform.parent;
        if (m_Controller)
        {
            secondLayerParent = m_Controller.transform;
        }
        
//        GameDebug.LogError($"secondLayerParent:{secondLayerParent?.name}");

        if (secondLayerUICamera)
            secondLayerUICamera.transform.SetParent(secondLayerParent);
        
        if (m_SecondCanvas)
            m_SecondCanvas.transform.SetParent(secondLayerParent);
    }

    protected List<float> imgAlphas;
    protected List<float> txtAlphas;
    protected List<float> rawAlphas;
    public virtual void FadeInAnim()
    {
        var rectTransform = GetComponent<RectTransform>();
        
        if (m_UIAnim == null) m_UIAnim = gameObject.AddComponent<UIAnim>();
        
        m_UIAnim.InitCurve(fadeInCurve);
        m_UIAnim.SetImgTxtAlpha(rectTransform, 0);
        m_UIAnim.UIAlpha(rectTransform, imgAlphas, txtAlphas, rawAlphas, fadeInTime, () =>
        {
            OnFadeInAimEnd();
        }, UIAnim.EaseType.Curve);
    }

    public virtual void FadeOut()
    {
        if (this != null && GetComponent<RectTransform>() != null && m_UIAnim)
        {
            m_UIAnim.InitCurve(fadeOutCurve);
            m_UIAnim.UIAlpha(GetComponent<RectTransform>(), 0, fadeOutTime, () =>
            {
                OnFadeOutAimEnd();
            }, UIAnim.EaseType.Curve);
        }
    }

    protected void InitCanvas(Canvas canvas,Camera worldCam,int screenWidth,int screenHeight)
    {
        canvas.renderMode = RenderMode.ScreenSpaceCamera;
        canvas.gameObject.layer = LayerMask.NameToLayer("UI");

        canvas.worldCamera = worldCam;// s_uiCamera;

        CanvasScaler canvasScaler = canvas.GetComponent<CanvasScaler>();
        if (canvasScaler == null)
            canvasScaler = canvas.gameObject.AddComponent<CanvasScaler>();
        canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
        canvasScaler.referenceResolution = new Vector2(screenWidth, screenHeight);

        canvasScaler.matchWidthOrHeight = DeviceInfo.GetScalerMatch();

        GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
        if (gr == null)
            gr = canvas.gameObject.AddComponent<GraphicRaycaster>();
    }

    protected GameObject m_BlackBG;
    public static GameObject CreateBlackBG(Transform transform,float blackAlpha)
    {
        var black = new GameObject("black").AddComponent<Image>();
        black.transform.SetParent(transform);

        if (transform != null && transform.parent != null)
            black.gameObject.layer = transform.parent.gameObject.layer;
        else
            black.gameObject.layer = LayerMask.NameToLayer("UI");

        black.transform.SetAsFirstSibling();
        black.transform.localScale = Vector3.one;
        black.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
        black.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
        black.rectTransform.anchorMin = new Vector2(0, 0);
        black.rectTransform.anchorMax = new Vector2(1, 1);

        var rect = black.GetComponent<RectTransform>();
        var pos = rect.anchoredPosition3D;
        pos.z = 10;
        rect.anchoredPosition3D = pos;

        black.color = new Color(0, 0, 0, blackAlpha);

        return black.gameObject;
    }
    
    public static Camera CreateUICamera(int screenWidth, int screenHeight,int depth,int layerMask, string name)
    {
        Camera camera = new GameObject(name).AddComponent<Camera>();
        camera.orthographic = true;
        camera.orthographicSize = screenWidth;
        camera.transform.position = new Vector3(screenWidth / 2, screenHeight / 2,10);
        camera.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));
        camera.backgroundColor = Color.black;
        camera.depth = depth;
        camera.clearFlags = CameraClearFlags.Depth;
        camera.cullingMask = layerMask;// 1 << LayerMask.NameToLayer("UI");

        return camera;
    }

    public static Camera CreateDefaultUICamera()
    {
        return  CreateUICamera(defaultUIWidth, defaultUIHeight, uiCameraLayer, 1 << LayerMask.NameToLayer("UI"), "UICamera");
    }

    public static Camera CreateDefaultUIFXCamera()
    {
        return CreateUICamera(defaultUIWidth, defaultUIHeight, uiFXCameraLayer, 1 << LayerMask.NameToLayer("TransparentFX"), "UIFXCamera");
    }

    //public static Camera CreateUIFXCamera(int screenWidth,int screenHeight)
    //{
    //    Camera camera = new GameObject("UIFXCamera").AddComponent<Camera>();
    //    camera.orthographic = true;
    //    camera.orthographicSize = screenWidth;
    //    camera.clearFlags = CameraClearFlags.Depth;
    //    camera.backgroundColor = Color.black;
    //    camera.depth = 6;
    //    camera.cullingMask = 1 << LayerMask.NameToLayer("TransparentFX");
    //    camera.transform.position = new Vector3(screenWidth/2, screenHeight/2, 10);
    //    camera.transform.rotation = Quaternion.Euler(new Vector3(0, 0, 0));

    //    return camera;
    //}

    /// <summary>
    /// 淡入动画播放完
    /// </summary>
    protected virtual void OnFadeInAimEnd()
    {

    }
    /// <summary>
    /// 淡出动画播放完
    /// </summary>
    protected virtual void OnFadeOutAimEnd()
    {

    }

/// <summary>
/// 加载到界面
/// </summary>
    protected virtual void GoBackToDisplay()
    {

    }

    Text blockUI;
    /// <summary>
    /// 屏蔽点击事件
    /// </summary>
    public void BlockEvent()
    {
        if (blockUI == null)
        {
            blockUI = new GameObject("Block").AddComponent<Text>();
            blockUI.transform.SetAsLastSibling();
            UIUtility.SetUIStretchAll(blockUI.GetComponent<RectTransform>());
        }
    }
    /// <summary>
    /// 打开点击事件
    /// </summary>
    public void ReleaseEvent()
    {
        if(blockUI)
        {
            Destroy(blockUI.gameObject);
        }
    }

    public void GoBack()
    {
        GoBackToDisplay();
        //m_Controller.RemoveFromNav();
    }

    protected DisplayController m_Controller;
    public void SetController(DisplayController controller)
    {
        m_Controller = controller;
        layer = m_Controller.parentNav.GetIndex(m_Controller);
    }

    protected void OnDisable()
    {
        if (m_SecondCanvas != null)
          m_SecondCanvas.gameObject.SetActive(false);
    }

    protected virtual void OnDestroy()
    {
        if (secondLayerUICamera != null)
        {
            secondLayerUICamera.enabled = false;
            Destroy(secondLayerUICamera.gameObject);
        }
        secondLayerUICamera = null;

        if (m_SecondCanvas != null)
            Destroy(m_SecondCanvas.gameObject);

        m_SecondCanvas = null;
    }

}
