using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

namespace GcDevicePc
{
    public partial class StartForm : Form
    {
        #region 窗口效果需要变量
        private double _mCurrentOpacity;
        private const double OpacityInterval = 0.02; //0.02
        private const double StayTime = 2000;   //5s
        System.Timers.Timer _opacityTimer;
        #endregion

        private String _appInitInfo = "系统初始化开始";
        private int _initSec;
        //private int _initStep;

        private static Thread _tPreload;
        private MainForm _mMainForm;

        #region 窗口淡入淡出效果
        private void OpacityTimerProcOpen(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (_mCurrentOpacity < 1)
            {
                ////如果当前的透明度小于1，则继续增加透明度
                _mCurrentOpacity += OpacityInterval;
                MethodInvoker mi = new MethodInvoker(UpdateFrmOpacity);
                BeginInvoke(mi);
            }
            else
            {
                //如果当前已经完全不透明，则停止timer
                _opacityTimer.Stop();
                System.Timers.Timer t = new System.Timers.Timer(StayTime); //设置时间间隔为5秒
                t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
                t.AutoReset = false; //每到指定时间Elapsed事件是触发一次（false），还是一直触发（true）
                t.Start();
            }
        }

        private void OpacityTimerProcClose(object sender, EventArgs e)
        {
            if (this._mCurrentOpacity > 0)
            {
                _tPreload.Join();   //拦截透明度下降请求

                //如果当前的透明度>0，则降低透明度
                this._mCurrentOpacity -= OpacityInterval;
                MethodInvoker mi = new MethodInvoker(UpdateFrmOpacity);
                this.BeginInvoke(mi);
            }
            else
            {
                //如果完全不透明，则关闭降低透明度timer,且关闭窗体
                this._opacityTimer.Stop();
                this._opacityTimer.Enabled = false;

                MethodInvoker mi = new MethodInvoker(MainFrmStartProc);
                this.BeginInvoke(mi);
            }
        }

        private void UpdateFrmOpacity()
        {
            this.Opacity = this._mCurrentOpacity;
        }

        private void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            _opacityTimer = new System.Timers.Timer();
            _opacityTimer.Interval = 30;
            _opacityTimer.Elapsed += new System.Timers.ElapsedEventHandler(OpacityTimerProcClose);
            _opacityTimer.Start();
        }
        #endregion


        private void bgpicture_Paint(object sender, PaintEventArgs e)
        {
            foreach (Control C in this.Controls)
            {
                if (C is Label)
                {
                    Label L = (Label)C;
                    L.Visible = false;
                    e.Graphics.DrawString(L.Text, L.Font, new
                            SolidBrush(L.ForeColor), L.Left - bgpicture.Left, L.Top - bgpicture.Top);
                }
            }
        }

        private void bgpicture_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            offlinebth.Visible = true;
            offlinebth.Enabled = true;
        }

        public StartForm()
        {
            InitializeComponent();
          
            Opacity = _mCurrentOpacity;
            _opacityTimer = new System.Timers.Timer();
            _opacityTimer.Interval = 30;
            _opacityTimer.Elapsed += new System.Timers.ElapsedEventHandler(OpacityTimerProcOpen);
            _opacityTimer.Start();
        }

        private void MainFrmStartProc()
        {
            if (_tPreload != null)
            {
                _tPreload.Join();
                _mMainForm = new MainForm();
                StartFormbgWorker.CancelAsync();
                Hide();
                _mMainForm.Show();
            }
        }
       
        /// <summary>
        /// 窗口载入函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartForm_Load(object sender, EventArgs e)
        {
             offlinebth.Enabled = false;
             offlinebth.Visible = false;
             StartFormbgWorker.RunWorkerAsync();

            //载入时开启预载线程
            _tPreload = new Thread(PreLoadingProc);
            _tPreload.IsBackground = true;
            _tPreload.Start();
        }


        /// <summary>
        /// 预载操作
        /// </summary>
        private void PreLoadingProc()
        {
           // globaldata.m_appinit.InitAppFolderGC();
            _appInitInfo = "系统初始化开始";
            _appInitInfo = "检测本地网络";
            globaldata.m_appinit.LocalNetworkCheck();
            _appInitInfo = "搜寻设备";
            globaldata.m_appinit.ConnectionIPInit();
            _appInitInfo = "检查运行环境";    
            globaldata.m_appinit.InitAppFolderGC();
            _appInitInfo = "载入方法配置";
            globaldata.m_appinit.InitAppDefaultConfig();
        }
        
        private void StartFormbgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            
            var worker = sender as BackgroundWorker;
            while (true)
            {
                if (StartFormbgWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                _initSec++;
                string tail = "";
                for (int i = 0; i < (_initSec % 4); i++)
                {
                    tail += ".";
                }
                if (worker != null)
                    worker.ReportProgress(50, _appInitInfo + tail);
                
                Thread.Sleep(500);

            }
        }

        private void StartFormbgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label2.Text = e.UserState.ToString();
            bgpicture.Invalidate();
        }

        private void offlinebth_Click(object sender, EventArgs e)
        {
            globaldata.OffLinkMode = true;
        }
    }
}
