using System;
using Fort23.Core;
using UnityEngine;
using UnityEngine.UI;

namespace Fort23.Mono
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class UIPanel : UIBase
    {
        public bool IsClose;
        public string uiName;
        public TimerEntity DestroyTimerEntity;


        public int DelayDestroyTime = 5000;

        public Graphic minDepth
        {
            get
            {
                if (GObjectPoolInterface == null)
                {
                    return null;
                }

                if (_graphic == null)
                {
                    _graphic = GetGraphic(GObjectPoolInterface.transform);
                    // int count = GObjectPoolInterface.transform.childCount;
                    // for (int i = 0; i < count; i++)
                    // {
                    //     Transform t = GObjectPoolInterface.transform.GetChild(i);
                    //     if (!t.gameObject.activeSelf)
                    //     {
                    //         continue;
                    //     }
                    //
                    //     _graphic = t.GetComponent<Graphic>();
                    //     break;
                    // }
                }

                if (_graphic != null)
                {
                    return _graphic;
                }

                return null;
            }
        }

        private Graphic GetGraphic(Transform transform)
        {
            int count = transform.childCount;
            for (int i = 0; i < count; i++)
            {
                Transform t = transform.GetChild(i);
                if (!t.gameObject.activeSelf)
                {
                    continue;
                }

                _graphic = t.GetComponent<Graphic>();
                if (_graphic != null)
                {
                    return _graphic;
                }
                else if (t.childCount > 0)
                {
                    return GetGraphic(t);
                }

                break;
            }

            return null;
        }

        protected Graphic _graphic;

        /// <summary>
        /// 是否需要显示背景
        /// </summary>
        public bool IsShowCustomBGPanel = false;

        public bool isFocus;
        public bool isFullUI;

        /// <summary>
        /// 是否显示导航栏 当他为false 就可以被close 否则进入只能被hide
        /// </summary>
        public bool IsBreadcrumbBarPanel = false;

        /// <summary>
        /// 面板名字
        /// </summary>
        public string PanelName;

        /// <summary>
        /// 是否显示导航栏
        /// </summary>
        public bool IsShowAppBar = true;

        public override async CTask SetUIGameObject(GameObject gObjectPoolInterface)
        {
            await base.SetUIGameObject(gObjectPoolInterface);

            if (isFocus)
            {
                GObjectPoolInterface.GetComponent<RectTransform>().offsetMax = Vector2.zero;
                GObjectPoolInterface.GetComponent<RectTransform>().offsetMin = Vector2.zero;
            }


            // transform.sizeDelta = UIManager.Instance.UIRootTransform.sizeDelta;
            transform.sizeDelta = UIManager.Instance.sizeDelta;
        }


        /// <summary>
        /// 1.打开界面 只有通过UIManager API 打开 并触发
        /// </summary>
        public override async CTask Open()
        {
            await ProOpen();
            await base.Open();

            DelEvent();
            IsClose = false;
            AddEvent();
        }

        protected virtual async CTask ProOpen()
        {
        }


      
        protected override void OnDestroy()
        {
            DelEvent();
        }

        public override void ShowAnimator()
        {
            showcCTask = CTask.Create();
            TimerComponent.Instance.Remove(openTimerEntity);
            if (Animator != null && isActiveAnima)
            {
                if (_openAnimationTimeCount > 0)
                {
                    UIManager.Instance.SetEventSystemEnable(false);
                    Animator.Play("open");
                    Animator.Update(0.01f);
                    openTimerEntity = TimerComponent.Instance.AddTimer(_openAnimationTimeCount, delegate
                    {
                        UIManager.Instance.SetEventSystemEnable(true);
                        showcCTask.SetResult();
                    });
                }
                else
                {
                    showcCTask.SetResult();
                }
            }
            else
            {
                showcCTask.SetResult();
            }
        }

        /// <summary>
        /// 展示这个界面 只做了显示和焦点获取 每次显示和隐藏会调用
        /// </summary>
        public override async CTask Show()
        {
            base.Show();

            DelEvent();
            IsClose = false;
            AddEvent();


            GObjectPoolInterface.transform.SetAsLastSibling();
            await GetFocus();
        }

        /// <summary>
        /// 添加EventManager事件（不在处理gameObject相关的操作，不然有会出现对象丢失的情况）
        /// </summary>
        protected abstract void AddEvent();

        /// <summary>
        /// 添加EventManager事件（不在处理gameObject相关的操作，不然有会出现对象丢失的情况）
        /// </summary>
        protected abstract void DelEvent();

        /// <summary>
        /// 点击背景面板时的回调
        /// </summary>
        public virtual void BackgroundCallBack()
        {
        }

        public virtual bool IsHindBackground()
        {
            return true;
        }


        //public CTask CloseAwaitTask;
        /// <summary>
        /// 关闭界面
        /// </summary>
        public virtual async void Close()
        {
            if (IsClose)
            {
                return;
            }

            _closedCallback?.Invoke();
            _closedCallback = null;
            Hide();
            IsClose = true;
            GObjectPoolInterface?.transform.SetSiblingIndex(0); //关闭界面的时候将他放在底部
            // if (IsShowCustomBGPanel)
            //     UIManager.Instance.SetBackgroundPanel(this);


            if (this == UIManager.Instance.currOpenPanel)
            {
                UIManager.Instance.currOpenPanel = null; //如果关闭的界面是最TOP 就把最Top设置为null
            }

            _closedTask?.SetResult();
            _closedTask = null;
        }


        /// <summary>
        /// 隐藏界面
        /// </summary>
        public override async void Hide()
        {
            base.Hide();

            DelEvent();
            await LoseFocus(); //关闭界面默认失去焦点
        }

        private CTask _closedTask;
        private Action _closedCallback;

        /// <summary>
        /// 增加的一个可等待的UI关闭任务,可以等待一个界面完全关闭后处理后面的事情
        /// </summary>
        /// <returns></returns>
        public async CTask UIClosed(Action action = null)
        {
            _closedTask = CTask.Create(false);
            _closedCallback += action;
            await _closedTask;
        }


        /// <summary>
        /// 获得焦点（当前显示再最 上层）
        /// </summary>
        public virtual async CTask GetFocus()
        {
            if (isFocus)
            {
                UIManager.Instance.currOpenPanel = this;
                // if (UIManager.Instance.lastOpenPropSourcePanel == this)
                // {
                //     UIManager.Instance.GetComponent<PropSourcePanel>().Show();
                // }
            }
        }

        /// <summary>
        /// 失去焦点（被其他UI所遮挡）
        /// </summary>
        public virtual async CTask LoseFocus()
        {
        }

        public void AddDelayDestroy()
        {
            RemoveDestroyTimerEntity();

            DestroyTimerEntity = TimerComponent.Instance.AddTimer(DelayDestroyTime, delegate
            {
                DestroyTimerEntity = null;
                UIManager.Instance.DestroyUIPanel(this);
            });
        }

        public void RemoveDestroyTimerEntity()
        {
            if (DestroyTimerEntity != null)
            {
                TimerComponent.Instance.Remove(DestroyTimerEntity.ID);
            }
        }

        // public virtual void GetBack()
        // {
        //     UIPanel uiPanel = UIManager.Instance.CloseTopUI();
        //
        //     UIManager.Instance.OpenTopUI();
        //     if (UIManager.Instance.GetComponent<AppBarPanel>() != null)
        //     {
        //         UIManager.Instance.GetComponent<AppBarPanel>().UpdateAssociatedUIPanelChangeData(this);
        //     }
        // }
    }
}