using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using CRVM.Entity;
using CRVM.SIDExcuter;
using System.ServiceModel;
using System.IO;
using ICService;
using System.Threading.Tasks;
using CRVM.Utility;
using RestApi;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace CRVM
{
    struct FileReview
    {
        public string fileType;
        public string filePath;
        public bool readOK;
    }

    public partial class IServerMainForm : Form
    {
        //private NotifyIcon notifyIcon;


        [DllImport("kernel32.dll")]
        static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);

        private bool isReview = false;
        private bool isRollInfoRead = false;
        private enum SystemStatus { unstart = 0, start = 1, stop = 2, pause = 3 }
        private SystemStatus sysStatus = SystemStatus.unstart;

        private ServiceHost host;
        private Machine mac;
        private Machine macReview;
        private DataProcessCenter dpc;
        private Plotting onlinePlot;
        private PlottingReview reviewPlot;
        private Plot_energy reviewPlot_Energy;
        private IViewHelper fileHelper;
        private DbHelper dbHelper;

        private ToolStripLabel labelAlarmNow;
        private ToolStripComboBox comBoxAlarmNow;
        private ToolStripLabel labelAlarmLast;
        private ToolStripComboBox comBoxAlarmLast;

        // 页面 刷新的数据 ---2025-01-09 新增
        public BoxData[] roll_mill_data_array { set; get; }
        public AlarmInfo alarmInfo;
        public RollMillData rollMillData { set; get; }
        public RollMillEnergyTrend rollMillET { set; get; }
        public CZState cZState { set; get; }
        public RMVibData[] standRmVibData { set; get; }
        public delegate void Shda();

        //private void RestoreWindow()
        //{
        //    this.WindowState = FormWindowState.Normal;
        //    this.ShowInTaskbar = true;
        //    this.Activate();
        //    notifyIcon.Visible = false;
        //}

        //private void MainForm_Resize(object sender, EventArgs e)
        //{
        //    if (this.WindowState == FormWindowState.Minimized)
        //    {
        //        this.ShowInTaskbar = false;
        //        notifyIcon.Visible = true;
        //    }
        //}

        public IServerMainForm()
        {

            //// 初始化托盘图标
            //notifyIcon = new NotifyIcon();
            //notifyIcon.Icon = new System.Drawing.Icon("Resources\\VibrationTest.ico");
            //notifyIcon.Text = "轧机振动监测系统";
            //notifyIcon.Visible = true;

            //// 双击托盘恢复窗口
            //notifyIcon.DoubleClick += (s, e) => RestoreWindow();

            //// 添加右键菜单
            //var menu = new ContextMenuStrip();
            //menu.Items.Add("退出", null, (s, e) => Application.Exit());
            //notifyIcon.ContextMenuStrip = menu;

            //// 窗体事件绑定
            //this.Resize += MainForm_Resize;
            //this.FormClosing += (s, e) => notifyIcon.Dispose();


            InitializeComponent();
            // 页面 刷新的数据 ---2025-01-09 新增
            roll_mill_data_array = new BoxData[6];
            standRmVibData = new RMVibData[6] { new RMVibData(), new RMVibData(), new RMVibData(), new RMVibData(), new RMVibData(), new RMVibData() };
            alarmInfo = new AlarmInfo();
            cZState = new CZState();
            RollMillGetService dh = new RollMillGetService();

            rollMillET = new RollMillEnergyTrend();
            for (int i = 0; i < 6; i++)
            {
                this.roll_mill_data_array[i] = dh.Roll_mill_data.F1.copy();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            backgroundWorker_fileRead.DoWork += backgroundWorker_fileRead_DoWork;
            backgroundWorker_fileRead.RunWorkerCompleted += backgroundWorker_fileRead_RunWorkerCompleted;

            SysParam.Instance.searchStartTime = DateTime.Now.AddDays(-1);
            SysParam.Instance.searchEndTime = DateTime.Now;
            SysParam.Instance.appPath = Application.StartupPath;
            ConfigHelper.GetInstance(SysParam.Instance.appPath + "\\AppSetting.config");
            ConfigHelper.GetInstance("").InitialData();


            dbHelper = DbHelper.GetInstance(SysParam.Instance.appPath);
            if (!dbHelper.LoadConfigData(dbHelper))
            {
                MessageBox.Show("数据库配置文件丢失或损坏！");
            }
            dbHelper.SetL2Connect();
            dbHelper.SetLocalConnect();
            dbHelper.isStart = true;

            try
            {
                host = new ServiceHost(typeof(PushMessage));
                host.Open();
            }
            catch (Exception ex)
            {
                recordLog("无法向客户端发送数据");
                MessageBox.Show("无法向客户端发送数据：" + ex.ToString());
            }

            InitialSetting();
            DbHelper.GetInstance("").autoUpdateAlarmParam();//数据库报警参数更新
           // Utility.VibSimulation.UpdateOnlineData(false);//模拟数据
        }

        private void InitialSetting()
        {
            //标签控件初始化
            ServerStartView();

            if (comBoxAlarmNow == null && labelAlarmNow == null)
            {
                Alarm_Info_show();
            }

            btStop.Enabled = false;
            btPause.Enabled = false;

            connectStatusStrip.Text = "                               ";
            connectStatusStrip.BackColor = System.Drawing.Color.RoyalBlue;
        }

        #region 图表选择框加载及面板隐藏控制
        private void ServerStartView()
        {
            titileSet titile0 = new titileSet();
            titile0.change += new titileSet.Change(titile0_change);
            titile0.labelText = "通道选择          ∨";
            tableLayoutPanel3.Controls.Add(titile0, 0, 0);
            titile0 = new titileSet();
            titile0.change += new titileSet.Change(titile1_change);
            titile0.labelText = "瞬时波形          ∨";
            tableLayoutPanel3.Controls.Add(titile0, 0, 2);
            titile0 = new titileSet();
            titile0.change += new titileSet.Change(titile2_change);
            titile0.labelText = "趋势波形          ∨";
            tableLayoutPanel3.Controls.Add(titile0, 0, 4);
            titile0 = new titileSet();
            titile0.change += new titileSet.Change(titile3_change);
            titile0.labelText = "显示方式          ∨";
            tableLayoutPanel3.Controls.Add(titile0, 0, 6);

            if (sysStatus == SystemStatus.unstart)
            {
                //online 
                panel1.Controls.Clear();
                panel2.Controls.Clear();
                panel3.Controls.Clear();
                panel4.Controls.Clear();
                ChannelSelect cs = new ChannelSelect();
                cs.Dock = DockStyle.Fill;
                panel1.Controls.Add(cs);
                GraCheckedTime gct = new GraCheckedTime();
                gct.Dock = DockStyle.Fill;
                panel2.Height = 256;
                panel2.Controls.Add(gct);
                GraCheckedEnergy gce = new GraCheckedEnergy();
                gce.Dock = DockStyle.Fill;
                panel3.Controls.Add(gce);
                GraphOrder go = new GraphOrder();
                go.Dock = DockStyle.Fill;
                panel4.Controls.Add(go);
            }
        }
        private void titile3_change(bool opend)
        {
            changeVisible(panel4, opend);
        }
        private void titile2_change(bool opend)
        {
            changeVisible(panel3, opend);
        }
        private void titile1_change(bool opend)
        {
            changeVisible(panel2, opend);
        }
        private void titile0_change(bool opend)
        {
            changeVisible(panel1, opend);
        }
        private void changeVisible(Panel panel, bool opened)
        {
            if (opened)
            {
                panel.Visible = true;
            }
            else
            {
                panel.Visible = false;
            }
        }
        #endregion

        private void start_Click(object sender, EventArgs e)
        {
            //new Task(() => DeleteFile()).Start();   
            try
            {
                sysStatus = SystemStatus.start;
                mainFormRefresh();
                mac = new Machine(SysParam.Instance.channelCount, SysParam.Instance.samplePoint, SysParam.Instance.timePoints, SysParam.Instance.energyPoints);

                //报警参数设置
                for (int i = 0; i < SysParam.Instance.channelCount; i++)
                {
                    mac.Stand[i].alarm_L_Times_ck = SysParam.Instance.channel[i].alarmTimes_l;
                    mac.Stand[i].alarm_M_Times_ck = SysParam.Instance.channel[i].alarmTimes_m;
                    mac.Stand[i].alarm_H_Times_ck = SysParam.Instance.channel[i].alarmTimes_h;
                    mac.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].alarmConfig);
                }

                dpc = new DataProcessCenter(mac);
                //---2025-01-09 新增
                dpc.roll_mill_data_array = this.roll_mill_data_array;
                rollMillData = new RollMillData(this.roll_mill_data_array);
                rollMillData.AF = this.alarmInfo;
                dpc.alarmInfo = this.alarmInfo;
               // dpc.cZState = this.cZState;

                dpc.rollMillData = this.rollMillData;
                for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                {
                    standRmVibData[i].vib_data = mac.Stand[i].vib;
                }
                dpc.standRmVibData = new StandRMVibData(standRmVibData);

                CloseDocumnet("Plotting");
                IDockContent dock = IsExistDocumnet("Plotting");
                if (dock == null)
                {
                    onlinePlot = new Plotting(mac);
                    onlinePlot.Show(dockPanel1, DockState.Document);
                }

                Timer_Graph.Start();
                SysParam.Instance.onlineList.Clear();
                isRollInfoRead = false;//重读棍子信息
                recordLog("开始采集数据");
            }
            catch (Exception ex)
            {
                throw ex;
                //Console.WriteLine(ex.StackTrace);
            }

        }

        private void stop_Click(object sender, EventArgs e)
        {
            DialogResult dir = MessageBox.Show("确定停止采集数据吗?", "信息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (dir == DialogResult.OK)
            {
                sysStatus = SystemStatus.stop;
                mainFormRefresh();
                if (dpc != null)
                {
                    dpc.Stop();
                }
                Timer_Graph.Stop();
                Timer_Graph_Tick(sender, e);
                backgroundWorker.CancelAsync();
                CloseDocumnet("Plotting");

                distance_Strip.Text = "轧制距离： 0000.0m ";
                cutLenSpeedStrip.Text = "出口速度： 0000m/min";
                SysParam.Instance.onlineList.Clear();

                recordLog("停止采集数据");
            }
            else
            {
                return;
            }

        }

        private void pause_Click(object sender, EventArgs e)
        {
            if (sysStatus == SystemStatus.start)
            {
                sysStatus = SystemStatus.pause;
                Timer_Graph.Stop();
                //提取轧制距离列表用于后续数据点显示
                mac.distance_Pause = mac.distance_Running.ToArray();
                onlinePlot.IsShowMenuStrip(true);
            }
            else if (sysStatus == SystemStatus.pause)
            {
                sysStatus = SystemStatus.start;
                Timer_Graph.Start();
                onlinePlot.IsShowMenuStrip(false);
            }
            mainFormRefresh();
        }

        private IDockContent IsExistDocumnet(string name)
        {
            IDockContent b = null;
            foreach (IDockContent content in dockPanel1.Documents)
            {
                if (content.DockHandler.TabText == name)
                {
                    b = content;
                    break;
                }
            }
            return b;
        }

        private void CloseDocumnet(string name)
        {
            foreach (IDockContent content in dockPanel1.Documents)
            {
                if (content.DockHandler.TabText == name)
                {
                    content.DockHandler.Dispose();
                    content.DockHandler.Close();
                    break;
                }
            }
        }

        private void Timer_Graph_Tick(object sender, EventArgs e)
        {
            //DevelopLog.DeBug.WriteLogFile("cutData", "----------");
            if (onlinePlot != null)
            {
                //图表刷新
                if (onlinePlot.InvokeRequired)
                    onlinePlot.Invoke(new Shda(onlinePlot.GraRefresh));
                else
                    onlinePlot.GraRefresh();
            }

            if (!isReview)
            {
                distance_Strip.Text = "轧制距离： " + mac.stripLength.ToString("00000.0") + "m ";
                cutLenSpeedStrip.Text = "出口速度： " + mac.lengthSpeed.ToString("0000") + "m/min";
            }
            if (dpc == null)
            {
                return;
            }
            if (dpc.alarmInfoNowChanged && dpc.alarmInfoNow != null)
            {
                dpc.alarmInfoNowChanged = false;
                comBoxAlarmNow.Items.Clear();
                comBoxAlarmNow.Text = "";
                comBoxAlarmNow.Items.AddRange(dpc.alarmInfoNow.ToArray());
                if (comBoxAlarmNow.Items.Count > 0)
                {
                    comBoxAlarmNow.SelectedIndex = comBoxAlarmNow.Items.Count - 1;
                }
            }
            if (dpc.alarmInfoLastChanged)
            {
                dpc.alarmInfoLastChanged = false;
                if (dpc.alarmInfoLast != null)
                {
                    comBoxAlarmLast.Items.Clear();
                    comBoxAlarmLast.Items.AddRange(dpc.alarmInfoLast);
                    comBoxAlarmLast.SelectedIndex = comBoxAlarmLast.Items.Count - 1;
                }
            }

        }

        private void Timer_CoilInfo_Tick(object sender, EventArgs e)
        {
            /*this.Timer_CoilInfo.Interval = DbHelper.GetInstance("").Freq * 1000;
            if (!backgroundWorker.IsBusy && dbHelper.isStart)
            {
                backgroundWorker.RunWorkerAsync();
            }
            if (dbHelper.isStart == false)
            {
                connectStatusStrip.BackColor = System.Drawing.Color.Red;
                connectStatusStrip.Text = "系统与L2的数据连接尚未开启......";
            }*/
        }

        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            /*string msg = "00";
            bool ischange = false;
            try
            {
                //获取钢卷信息
                DbHelper.GetInstance("").UpdateLocalCoilInfo();
                msg = "10";

                //获取在线轧辊信息
                DataTable onlineRollData = dbHelper.GetL2OnlineRollInfo();
                for (int i = 0; i < onlineRollData.Rows.Count; i++)
                {
                    string rollno = onlineRollData.Rows[i]["rollno"].ToString().Trim();
                    if (!SysParam.Instance.onlineList.Contains(rollno))
                    {
                        ischange = true;
                        break;
                    }
                }
                if (ischange && sysStatus == SystemStatus.start)
                {
                    dbHelper.RollDataInfo(mac, onlineRollData);
                    dbHelper.UpdateLocalRollData(onlineRollData);
                    SysParam.Instance.onlineList = new List<string>();
                    for (int i = 0; i < onlineRollData.Rows.Count; i++)
                    {
                        string rollno = onlineRollData.Rows[i]["rollno"].ToString().Trim();
                        SysParam.Instance.onlineList.Add(rollno);
                    }
                    ischange = false;
                }
                msg = "11";
            }
            catch (Exception ex)
            {

            }
            backgroundWorker.ReportProgress(0, msg);
            */
        }

        private void backgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            /*if (e.UserState.ToString() == "00")
            {
                connectStatusStrip.Text = "获取L2钢卷信息异常，请查看本系统与L2数据库的连接......";
                connectStatusStrip.BackColor = System.Drawing.Color.Red;
            }
            else if (e.UserState.ToString() == "10")
            {
                connectStatusStrip.Text = "获取L2在线轧辊信息异常，请查看本系统与L2数据库的连接......";
                connectStatusStrip.BackColor = System.Drawing.Color.Red;
            }
            else if (e.UserState.ToString() == "11")
            {
                connectStatusStrip.Text = "获取L2在线轧辊信息正常...获取L2钢卷信息正常......";
                connectStatusStrip.BackColor = System.Drawing.Color.RoyalBlue;
            }*/
        }


        private void btnViewOut_Click(object sender, EventArgs e)
        {
            isReview = false;
            mainFormRefresh();
            CloseDocumnet("PlottingReview");
            CloseDocumnet("Plot_energy");
            if (sysStatus != SystemStatus.unstart)
            {
                IDockContent dock = IsExistDocumnet("Plotting");
                if (dock == null)
                {
                    onlinePlot = new Plotting(mac);
                    onlinePlot.Show(dockPanel1, DockState.Document);
                }
            }
        }

        private void btnViewIn_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog1.FileName;
                //DataRead(filePath);//打开文件
                if (File.Exists(filePath))
                {
                    isReview = true;
                    mainFormRefresh();

                    if (backgroundWorker_fileRead.IsBusy)
                    {
                        MessageBox.Show("正在读取文件....");
                    }
                    else
                    {
                        backgroundWorker_fileRead.RunWorkerAsync(filePath);
                    }
                }
            }
        }

        void OpenFile(object sender, string filePath)
        {
            if (File.Exists(filePath))
            {
                isReview = true;
                mainFormRefresh();
                //DataRead(filePath);

                if (backgroundWorker_fileRead.IsBusy)
                {
                    MessageBox.Show("正在读取文件....");
                }
                else
                {
                    backgroundWorker_fileRead.RunWorkerAsync(filePath);
                }

            }
            else
            {
                MessageBox.Show("查找的文件不存在");
            }
        }

        void backgroundWorker_fileRead_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            FileReview fileStruct = new FileReview();
            fileStruct = (FileReview)e.Result;
            if (fileStruct.readOK)
            {
                if (fileStruct.fileType == "0")
                {
                    DataReview();//检查能量文件是否存在后再回放
                    new Task(() => GetFileCoilInfo(fileStruct.filePath, true)).Start();
                }
                else
                {
                    DataReviewEnergy();//能量数据回放
                    new Task(() => GetFileCoilInfo(fileStruct.filePath, false)).Start();
                }
            }

        }

        void backgroundWorker_fileRead_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            string filePath = e.Argument.ToString();

            FileReview fileStruct = new FileReview();
            fileStruct.filePath = filePath;

            if (fileHelper == null)
                fileHelper = new IViewHelper(filePath);
            else
                fileHelper.ReadFile(filePath);
            if (fileHelper.FileOk)
            {
                string alarmFilePath = fileHelper.selectAlarmFile(filePath);
                ConfigHelper.GetOrigInstance(alarmFilePath);

                if (filePath.Contains(".txt"))
                {
                    if (filePath.Contains("original"))
                    {
                        string fileName = filePath.Replace("original", "energy");///////////读取能量信息 20151112
                        if (File.Exists(fileName))
                        {
                            fileHelper.ReadFile(fileName);
                        }
                        else
                        {
                            MessageBox.Show("能量数据文件不存在");
                        }
                        macReview = new Machine(SysParam.Instance.channelCount, 1, 1, 1);
                        for (int i = 0; i < SysParam.Instance.channelCount; i++)
                        {
                            macReview.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].reAlarmConfig);
                        }
                        fileStruct.fileType = "0";
                        fileStruct.readOK = true;
                        //DataReview();//检查能量文件是否存在后再回放
                        //new Task(() => GetFileCoilInfo(filePath, true)).Start();
                    }
                    else
                    {

                        if (File.Exists(filePath))
                        {
                            fileHelper.ReadFile(filePath);
                        }
                        else
                        {
                            MessageBox.Show("能量数据文件不存在");
                        }
                        macReview = new Machine(SysParam.Instance.channelCount, 1, 1, 1);
                        for (int i = 0; i < SysParam.Instance.channelCount; i++)
                        {
                            macReview.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].reAlarmConfig);
                        }

                        fileStruct.fileType = "1";
                        fileStruct.readOK = true;
                        //DataReviewEnergy();//能量数据回放
                        //new Task(() => GetFileCoilInfo(filePath, false)).Start();
                    }
                }
                else if (filePath.Contains(".dat"))
                {
                    string fileName1 = filePath.Replace("original", "energy");
                    string fileName = fileName1.Replace(".dat", ".txt");
                    if (File.Exists(fileName))
                    {
                        fileHelper.ReadFile(fileName);
                    }
                    else
                    {
                        MessageBox.Show("能量数据文件不存在");
                    }
                    macReview = new Machine(SysParam.Instance.channelCount, 1, 1, 1);
                    for (int i = 0; i < SysParam.Instance.channelCount; i++)
                    {
                        macReview.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].reAlarmConfig);
                    }
                    fileStruct.fileType = "0";
                    fileStruct.readOK = true;
                }

            }
            else
            {
                fileStruct.readOK = false;
                MessageBox.Show("文件已损坏！");
            }

            e.Result = fileStruct;
        }

        private void DataRead(string filePath)
        {
            if (fileHelper == null)
                fileHelper = new IViewHelper(filePath);
            else
                fileHelper.ReadFile(filePath);
            if (fileHelper.FileOk)
            {
                isReview = true;
                mainFormRefresh();
                string alarmFilePath = fileHelper.selectAlarmFile(filePath);
                ConfigHelper.GetOrigInstance(alarmFilePath);

                if (filePath.Contains(".txt"))
                {
                    if (filePath.Contains("original"))
                    {
                        string fileName = filePath.Replace("original", "energy");///////////读取能量信息 20151112
                        if (File.Exists(fileName))
                        {
                            fileHelper.ReadFile(fileName);
                        }
                        else
                        {
                            MessageBox.Show("能量数据文件不存在");
                        }
                        macReview = new Machine(SysParam.Instance.channelCount, 1, 1, 1);
                        for (int i = 0; i < SysParam.Instance.channelCount; i++)
                        {
                            macReview.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].reAlarmConfig);
                        }
                        DataReview();//检查能量文件是否存在后再回放
                        new Task(() => GetFileCoilInfo(filePath, true)).Start();
                    }
                    else
                    {
                        DataReviewEnergy();//能量数据回放
                        new Task(() => GetFileCoilInfo(filePath, false)).Start();
                    }
                }
                else if (filePath.Contains(".dat"))
                {
                    string fileName1 = filePath.Replace("original", "energy");
                    string fileName = fileName1.Replace(".dat", ".txt");
                    if (File.Exists(fileName))
                    {
                        fileHelper.ReadFile(fileName);
                    }
                    else
                    {
                        MessageBox.Show("能量数据文件不存在");
                    }
                    macReview = new Machine(SysParam.Instance.channelCount, 1, 1, 1);
                    for (int i = 0; i < SysParam.Instance.channelCount; i++)
                    {
                        macReview.Stand[i].SetAlarmFred(SysParam.Instance.channel[i].reAlarmConfig);
                    }
                    DataReview();//检查能量文件是否存在后再回放
                    new Task(() => GetFileCoilInfo(filePath, true)).Start();
                }
            }
            else
            {
                MessageBox.Show("文件已损坏！");
            }
        }

        private void DataReviewEnergy()
        {
            CloseDocumnet("Plotting");
            CloseDocumnet("Plot_energy");
            CloseDocumnet("PlottingReview");
            reviewPlot_Energy = new Plot_energy(fileHelper, macReview);
            reviewPlot_Energy.Show(this.dockPanel1, DockState.Document);
        }

        private void DataReview()
        {
            CloseDocumnet("Plotting");
            CloseDocumnet("Plot_energy");
            CloseDocumnet("PlottingReview");
            reviewPlot = new PlottingReview(fileHelper, macReview);
            reviewPlot.Show(dockPanel1, DockState.Document);
        }

        private void mainFormRefresh()
        {
            if (isReview)
            {
                Timer_Graph.Stop();
                btReviewExit.Visible = true;
                btstart.Enabled = false;
                btPause.Enabled = false;
                btStop.Enabled = false;

                //btrollInfo.Enabled = true;

                if (labelAlarmNow != null)
                {
                    labelAlarmNow.Visible = false;
                    comBoxAlarmNow.Visible = false;
                    labelAlarmLast.Visible = false;
                    comBoxAlarmLast.Visible = false;
                }

                connectStatusStrip.Visible = false;
                filename_Strip.Visible = true;
                distance_Strip.Visible = false;
                cutLenSpeedStrip.Visible = false;

                if (panel2.Height != 287)
                {
                    panel2.Controls.Clear();
                    GraCheckedTimeRe gctr = new GraCheckedTimeRe();
                    gctr.Dock = DockStyle.Fill;
                    panel2.Height = 287;
                    panel2.Controls.Add(gctr);
                }
            }
            else
            {
                btReviewExit.Visible = false;

                if (labelAlarmNow != null)
                {
                    labelAlarmNow.Visible = true;
                    comBoxAlarmNow.Visible = true;
                    labelAlarmLast.Visible = true;
                    comBoxAlarmLast.Visible = true;
                }

                connectStatusStrip.Visible = true;
                filename_Strip.Visible = false;
                distance_Strip.Visible = true;
                cutLenSpeedStrip.Visible = true;

                if (panel2.Height != 256)
                {
                    panel2.Controls.Clear();
                    GraCheckedTime gct = new GraCheckedTime();
                    gct.Dock = DockStyle.Fill;
                    panel2.Height = 256;
                    panel2.Controls.Add(gct);
                }

                if (sysStatus == SystemStatus.start || sysStatus == SystemStatus.pause)
                {
                    if (sysStatus == SystemStatus.start)
                    {
                        Timer_Graph.Start();
                        btStop.Enabled = true;
                        btPause.Image = Host.Properties.Resources.Pause_64;
                        btPause.Text = "暂停";
                    }
                    else
                    {
                        btStop.Enabled = false;
                        btPause.Image = Host.Properties.Resources.Refresh_64;
                        btPause.Text = "继续";
                    }
                    btstart.Enabled = false;
                    btPause.Enabled = true;

                    btSetSensor.Enabled = false;
                    //btSetAlarm.Enabled = false;
                    btSetSampling.Enabled = false;
                    btSetStore.Enabled = false;
                    btSetPassword.Enabled = false;

                    btdatabase.Enabled = false;
                    //btrollInfo.Enabled = false;
                }

                if (sysStatus == SystemStatus.stop || sysStatus == SystemStatus.unstart)
                {
                    btstart.Enabled = true;
                    btPause.Enabled = false;
                    btPause.Image = Host.Properties.Resources.Pause_64;
                    btPause.Text = "暂停";
                    btStop.Enabled = false;

                    btSetSensor.Enabled = true;
                    btSetAlarm.Enabled = true;
                    btSetSampling.Enabled = true;
                    btSetStore.Enabled = true;
                    btSetPassword.Enabled = true;

                    btdatabase.Enabled = true;
                    //btrollInfo.Enabled = true;
                }
            }
        }
        //显示打开文件的钢卷信息
        private void GetFileCoilInfo(string fileNameStr, bool isOrigData)
        {
            //查询该钢卷信息
            DataTable dt = new DataTable();
            macReview.review_coldcoilno = "";
            macReview.review_extThick = "";
            macReview.review_alloyCode = "";
            macReview.review_steelGrade = "";
            macReview.review_width = "";

            filename_Strip.Text = "文件名：" + fileNameStr.Substring(fileNameStr.Length - 18, 18);

            if (isOrigData)
            {
                dt = DbHelper.GetInstance("").GetCoilInfoByOriginPath(fileNameStr, macReview);
            }
            else
            {
                dt = DbHelper.GetInstance("").GetCoilInfoByEnergyPath(fileNameStr, macReview);
            }

            if (macReview.review_coldcoilno != "")
            {
                filename_Strip.Text = "文件名：" + fileNameStr.Substring(fileNameStr.Length - 18, 18) + " | 冷卷号：" + macReview.review_coldcoilno + " | 出钢记号：" + macReview.review_alloyCode + " | 宽度：" + macReview.review_width + "mm | 出口厚度：" + macReview.review_extThick + "mm"; ;
            }
            /*else
            {
                filename_Strip.Text = "文件名：" + fileNameStr.Substring(fileNameStr.Length - 18, 18);
            }*/
        }

        private void Alarm_Info_show()
        {
            labelAlarmNow = new ToolStripLabel();
            comBoxAlarmNow = new ToolStripComboBox();
            comBoxAlarmNow.Alignment = ToolStripItemAlignment.Right;
            comBoxAlarmNow.Width = 400;
            comBoxAlarmNow.DropDownHeight = 150;
            comBoxAlarmNow.DropDownWidth = 400;
            toolStrip1.Items.Add(comBoxAlarmNow);
            toolStrip1.Items.Add(labelAlarmNow);
            labelAlarmNow.Text = "当前报警信息：";
            labelAlarmNow.Alignment = ToolStripItemAlignment.Right;

            labelAlarmLast = new ToolStripLabel();
            comBoxAlarmLast = new ToolStripComboBox();
            comBoxAlarmLast.Alignment = ToolStripItemAlignment.Right;
            comBoxAlarmLast.Width = 400;
            comBoxAlarmLast.DropDownHeight = 150;
            comBoxAlarmLast.DropDownWidth = 400;
            toolStrip1.Items.Add(comBoxAlarmLast);
            toolStrip1.Items.Add(labelAlarmLast);
            labelAlarmLast.Text = "上次报警信息：";
            labelAlarmLast.Alignment = ToolStripItemAlignment.Right;
        }

        private void sysconfig_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            //if (log.DialogResult == DialogResult.OK)
            {
                SetDataStorageForm newForm = new SetDataStorageForm();
                newForm.ShowDialog();
            }
        }

        private void setsensitivity_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            //if (log.DialogResult == DialogResult.OK)
            {
                SetSenserForm newForm = new SetSenserForm();
                newForm.ShowDialog();
            }
        }

        private void setdisplay_Click(object sender, EventArgs e)
        {
            SetDisplayForm disForm = new SetDisplayForm();
            disForm.ShowDialog();
        }

        private void setalarm_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            if (log.DialogResult == DialogResult.OK)
            {
                DbHelper.GetInstance("").autoUpdateAlarmParam();
                SetAlarmForm newForm = new SetAlarmForm();
                newForm.ShowDialog();
            }
        }

        private void btsetsample_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            //if (log.DialogResult == DialogResult.OK)
            {
                SetSampleForm newForm = new SetSampleForm();
                newForm.ShowDialog();
            }
        }

        private void btsetpassword_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            //if (log.DialogResult == DialogResult.OK)
            {
                SetPasswordForm newForm = new SetPasswordForm();
                newForm.ShowDialog();
            }
        }

        private void bthelp_Click(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string url = path + "用户使用手册.pdf"; // 
            try
            {
                // 使用应用打开
                Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
            }
            catch (Win32Exception ex) // 捕获无浏览器异常
            {
                if (ex.ErrorCode == -2147467259)
                    MessageBox.Show(String.Format("打开\"{0}\"失败：{1}", url, ex.Message));
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("打开\"{0}\"失败：{1}", url, ex.Message));
            }
        }

        private void btrollInfo_Click(object sender, EventArgs e)
        {
            if (isReview)
            {
                OriginRollForm form = new OriginRollForm(macReview);
                form.StartPosition = FormStartPosition.CenterScreen;
                form.ShowDialog();
            }
            else
            {
                if (dbHelper.isStart)
                {
                    OnlineRollForm form = new OnlineRollForm();
                    form.StartPosition = FormStartPosition.CenterScreen;
                    form.ShowDialog();
                }
                else
                {
                    MessageShowForm form = new MessageShowForm("提示", "未启动数据连接，无法获取在线轧辊信息！");
                    form.ShowDialog();
                }
            }
        }

        private void btdataSearch_Click(object sender, EventArgs e)
        {
            DataSearchForm data = new DataSearchForm();
            data.showdata += new ShowGridData(OpenFile);
            data.ShowDialog();
        }

        private void btdatabase_Click(object sender, EventArgs e)
        {
            //login log = new login();
            //log.ShowDialog();
            //if (log.DialogResult == DialogResult.OK)
            {
                DataAccessForm newForm = new DataAccessForm(dbHelper);
                newForm.ShowDialog();
            }
        }

        private void IServerMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dir = MessageBox.Show("确定退出本系统吗？", "信息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dir == DialogResult.OK)
            {
                try
                {
                    if (dpc != null)
                    {
                        dpc.Stop();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                ConfigHelper.GetInstance("").SaveConfig(Application.StartupPath);//保存文件

                dbHelper.SaveAlarmParam(ConfigHelper.GetInstance("").GetAlarmParam());//保存数据库

                recordLog("退出本系统");
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            tableLayoutPanel3.Visible = tableLayoutPanel3.Visible ? false : true;
        }

        private void timer_delFile_Tick(object sender, EventArgs e)
        {
            new Task(() => DeleteFile()).Start();
        }

        private void DeleteFile()
        {
            string driveStr = SysParam.Instance.savePath.Substring(0, 2);
            System.IO.DriveInfo drive = new System.IO.DriveInfo(driveStr);
            long availabelfreespace = drive.AvailableFreeSpace / 1024 / 1024 / 1024;//剩余空间转换为G
            long needFreespace = availabelfreespace - 20;//至少预留20个G的空间
            if (needFreespace <= 0)
            {
                DirectoryInfo savedir = new DirectoryInfo(SysParam.Instance.savePath + "\\");
                FileComparer fc = new FileComparer();
                DirectoryInfo[] dirList = savedir.GetDirectories();
                Array.Sort(dirList, fc);//根据时间排序

                if (dirList.Length > 0)
                {
                    Directory.Delete(dirList[0].FullName, true);
                }
            }

            //删除创建日期早于一定天数的文件夹
            foreach (string dirStr in Directory.GetDirectories(SysParam.Instance.savePath))
            {
                DirectoryInfo dir = new DirectoryInfo(dirStr);
                if (dir.CreationTime < DateTime.Now.AddDays(-SysParam.Instance.saveDaysAlarm))
                {
                    Directory.Delete(dirStr, true);
                }
            }
            DataTable noalarmdata = dbHelper.GetCoilInfoByDate(false, DateTime.Now.AddDays(-360), DateTime.Now.AddDays(-SysParam.Instance.saveDaysNoAlarm));
            DataTable alarmdata = dbHelper.GetCoilInfoByDate(true, DateTime.Now.AddDays(-360), DateTime.Now.AddDays(-SysParam.Instance.saveDaysAlarm));
            for (int i = 0; i < noalarmdata.Rows.Count; i++)
            {
                if (File.Exists(noalarmdata.Rows[i]["origpath"].ToString().Trim()))
                {
                    File.Delete(noalarmdata.Rows[i]["origpath"].ToString().Trim());
                }

                if (File.Exists(noalarmdata.Rows[i]["energypath"].ToString().Trim()))
                {
                    File.Delete(noalarmdata.Rows[i]["energypath"].ToString().Trim());
                }
            }
            for (int i = 0; i < alarmdata.Rows.Count; i++)
            {
                if (File.Exists(alarmdata.Rows[i]["origpath"].ToString().Trim()))
                {
                    File.Delete(alarmdata.Rows[i]["origpath"].ToString().Trim());
                }

                if (File.Exists(alarmdata.Rows[i]["energypath"].ToString().Trim()))
                {
                    File.Delete(alarmdata.Rows[i]["energypath"].ToString().Trim());
                }
            }
        }

        private void timer_RollInfo_Tick(object sender, EventArgs e)
        {
            //Console.WriteLine($"|{DateTime.Now.ToString("F")}|---Test---dbHelper is null?{dbHelper == null},mac is null?{mac == null}");
            if (dbHelper != null && mac != null)
            {
                if (isRollInfoRead == false || mac.lengthSpeed < 50)
                {
                    DataTable rolldata = dbHelper.GetL2OnlineRollInfo();
                    if (rolldata == null || rolldata.Rows.Count == 0)
                    {
                        return;
                    }
                    dbHelper.RollDataInfo(mac, rolldata);
                    isRollInfoRead = true;
                }
            }
        }

        private void recordLog(string logInfo)
        {
            if (dbHelper != null)
            {
                dbHelper.recordLogInfo("SERVER", logInfo);
            }
        }

        private void IServerMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Process curProcess = Process.GetCurrentProcess();
            IntPtr handle = curProcess.Handle;
            TerminateProcess(handle, 0);
        }

        private void btSysSetting_Click(object sender, EventArgs e)
        {

        }
    }

}
