using System;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace Common.system
{
    /// <summary>
    /// 解决闪屏  加载等待 
    /// 创建人：赵耀
    /// 创建时间：2018年11月27日
    /// </summary>
    public class SplashScreen
    {
        private static object _obj = new object();

        private static Form _splashForm;

        private static Thread _splashThread;

        private delegate void ChangeFormTextdelegate(string s);

        public static void Show(Type splashFormType)
        {
            if (_splashThread != null)
            {
                return;
            }

            if (splashFormType == null)
            {
                throw (new Exception());
            }
            _splashThread = new Thread(
                delegate()
                {
                    CreateInstance(splashFormType);
                    Application.Run(_splashForm);
                }
            ) { IsBackground = true };
            _splashThread.SetApartmentState(ApartmentState.STA);
            _splashThread.Start();
        }

        public static void ChangeTitle(string status)
        {
            ChangeFormTextdelegate de = ChangeText;
            _splashForm.Invoke(de, status);
        }



        public static void Close()
        {
            if (_splashThread == null || _splashForm == null)
            {
                return;
            }
            try
            {
                _splashForm.Invoke(new MethodInvoker(_splashForm.Close));
            }
            catch (Exception)
            {
                // ignored
            }
            _splashThread = null;
            _splashForm = null;
        }

        private static void ChangeText(string title)
        {
            _splashForm.Text = title;
        }

        private static void CreateInstance(Type formType)
        {
            if (_splashForm == null)
            {
                lock (_obj)
                {
                    object obj = formType.InvokeMember(
                        null,
                        BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
                        null,
                        null,
                        null
                    );
                    _splashForm = obj as Form;
                    if (_splashForm != null)
                    {
                        _splashForm.TopMost = true;
                        _splashForm.ShowInTaskbar = false;
                        _splashForm.BringToFront();
                        _splashForm.StartPosition = FormStartPosition.CenterScreen;
                    }
                }
            }
        }

    }
}
