using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace FrmMonitor
{
    public partial class Monitor : Form
    {
        public Monitor()
        {
            InitializeComponent();
        }

        private string oldFtpTruNo = "";//FTP图片上传用到，防止重复执行上传操作
        private PerformanceCounter p2 = null;
        private bool boolClose = false;//false检查终端程序是否存在，如果不存在，那么重新启动

        //ImageControl imageControl = new ImageControl(); //图片控制器含图片压缩及上传sftp
        private int count = 0;//终端CPU占用率超时时长

        private bool restartProcess = true; //在特定的时间段内重启程序

        private void Monitor_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            p2 = new PerformanceCounter("Process", "% Processor Time", "CarMeterSystem");

            //2021年3月7日将图片上传的线程挪动到此处；2021年3月8日不用挪了，还放回去
            //imageControl.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                //this.Hide();
                Process[] myprocess = Process.GetProcessesByName("CarMeterSystem");
                if (myprocess.Length <= 0)
                {//终端程序不存在，那么进行重启操作
                    //intFlag = 1;
                    Process.Start("CarMeterSystem.exe");
                    WriteLog("终端进程（CarMeterSystem）已经重新启动");
                    return;
                }
                try
                {
                    decimal dcmCpu_ = Math.Round(Convert.ToDecimal(p2.NextValue() / Environment.ProcessorCount));//终端进程CPU占用率
                    WriteLog("终端进程（CarMeterSystem）CPU占用率：" + dcmCpu_.ToString());
                    if (dcmCpu_ > 20 && myprocess.Length > 0)
                    {
                        //2021年3月16日，杨秀东新增；5s一次，连续5次，若截图失败等原因造成采集卡死，则重启终端
                        count++;
                        if (count > 4)
                        {
                            count = 0;
                            foreach (Process process in myprocess)
                            {
                                if (process.ProcessName == "CarMeterSystem")
                                {
                                    //process.Kill();
                                    //WriteLog("终端进程（CarMeterSystem）已经被kill：" + dcmCpu_.ToString());

                                    //Process.Start("CarMeterSystem.exe");
                                    //WriteLog("终端进程（CarMeterSystem）已经重新启动");
                                }
                            }
                        }
                    }
                    //2021年6月5日：每天晚上11点自动重启
                    TimeSpan nowDt = DateTime.Now.TimeOfDay;
                    TimeSpan workStartDT = DateTime.Parse("23:45").TimeOfDay;
                    TimeSpan workEndDT = DateTime.Parse("23:50").TimeOfDay;
                    if (nowDt > workStartDT && nowDt < workEndDT)
                    {
                        if (restartProcess)
                        {
                            foreach (Process process in myprocess)
                            {
                                if (process.ProcessName == "CarMeterSystem")
                                {
                                    process.Kill();
                                    WriteLog("终端进程（CarMeterSystem）已经被kill：" + DateTime.Now.TimeOfDay);

                                    Process.Start("CarMeterSystem.exe");
                                    WriteLog("终端进程（CarMeterSystem）已经重新启动：" + DateTime.Now.TimeOfDay);
                                }
                                restartProcess = false;
                            }
                        } 
                    }
                    else
                    {
                        restartProcess = true;
                    }
                }
                catch (Exception exp)
                {
                    WriteLog("CPU使用率监控异常！" + exp.Message);
                }
            }
            catch (Exception exp)
            {
                WriteLog("timer1_Tick异常：" + exp.Message);
            }
        }

        public void WriteLog(string str)
        {
            string m_szRunPath;
            m_szRunPath = System.Environment.CurrentDirectory;
            if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
            {
                System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
            }
            string strDate = System.DateTime.Now.ToString("yyyyMMdd");
            string strPathFile = m_szRunPath + "\\log\\" + strDate;
            if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(strPathFile);
            }
            System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\监控程序运行_" + strDate + ".log", true);

            tw.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            tw.WriteLine(str);
            tw.WriteLine("\r\n");

            tw.Close();
        }

        private void Monitor_Shown(object sender, EventArgs e)
        {
            //2021年12月24日 取消隐藏
            //this.Visible = false;
            try
            {
                //imageControl.Stop();
            }
            catch { }
        }
    }
}