using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using CRVM.CIDExcuter;
using CRVM.Entity;
using System.IO;
using ICService;
using System.ServiceModel;
using System.Threading.Tasks;
using CRVM.Utility;
using System.Threading;

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Drawing;
using System.ComponentModel;

namespace CRVM
{
    struct FileReview
    {
        public string fileType;
        public string filePath;
        public bool readOK;
    }
    public partial class IClientMainForm : Form
    {
        [DllImport("kernel32.dll")]
        static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);

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

        Callback back;
        InstanceContext instanceContext;
        DuplexChannelFactory<IPushMessage> channelFactory;
        IPushMessage proxy;
        string uid;

        private DateTime ConnectLastTime;
        MessageShowForm nodata_form;
        bool nodata_rcv = true;

        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;

        public delegate void Shda();

        private DateTime stoptime;
        private DateTime starttime;
        private bool firsttime = true;
        //测试
        private DateTime St1;
        private int st1Times = 0;

        AlarmShowForm alarmForm;//报警弹窗 显示报警机架

        public IClientMainForm()
        {
            InitializeComponent();
        }

        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;

            InitialSetting();
            DbHelper.GetInstance("").autoUpdateAlarmParam();//数据库报警参数更新
        }

        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;

            this.btnAlarmVisual.Image = global::client.Properties.Resources.不可见;
            tableLayoutPanel4.Visible = false;
            tableLayoutPanel2.ColumnStyles[2].Width = 0;
            tableLayoutPanel2.ColumnStyles[2].SizeType = SizeType.Absolute;

        }

        #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.off)
            {
                //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


        void dpc_DataChanged(OrginalCollectDataEventArgs e)
        {

        }

        void back_MacDataChanged(object sender, MacDataEventArgs e)
        {
            st1Times++;
            ConnectLastTime = DateTime.Now;
            nodata_rcv = false;
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                for (int j = 0; j < SysParam.Instance.samplePoint; j++)
                {
                    mac.Stand[i].vib[j] = e.data.vibData[i * SysParam.Instance.samplePoint + j];
                }
            }
            for (int i = 0; i < e.data.standSpeed.Length; i++)
            {
                mac.Stand[i].speed = e.data.standSpeed[i];
            }
            mac.lengthSpeed = e.data.lenthSpeed;
            mac.cutted = e.data.cutState;
            mac.stripLength = e.data.stripLength;
            if (dpc == null)
            {
                return;
            }
            dpc.DataProcess();
            //Console.WriteLine("start time: "+St1.ToString("HH:mm:ss fff") + $",times:{st1Times}"+$" diff time:{(ConnectLastTime-St1).TotalMilliseconds/200}");
            if (mac.cutted)
            {
                DevelopLog.DeBug.WriteLogFile("back_MacDataChanged", "start time: " + St1.ToString("HH:mm:ss fff") + String.Format(",times:{0}", st1Times) + String.Format(" diff time:{0}", (ConnectLastTime - St1).TotalMilliseconds / 200));
            }


        }

        private void start_Click(object sender, EventArgs e)
        {
            //测试
            St1 = DateTime.Now;
            st1Times = 0;

            needRing = false;
            isRollInfoRead = false;

            bool isCanConnect = false;
            ConnectLastTime = DateTime.Now;
            Timer_Graph.Interval = 200;
            starttime = DateTime.Now;
            if ((starttime - stoptime).Seconds < 5 && firsttime == false)
            {
                MessageShowForm form = new MessageShowForm("警告", "操作太过频繁，请稍后！");
                form.ShowDialog();
                return;
            }

            new Task(() => DeleteFile()).Start();

            try
            {
                back = new Callback();
                back.MacDataChanged += new MacDataHandle(back_MacDataChanged);
                instanceContext = new InstanceContext(back);
                channelFactory = new DuplexChannelFactory<IPushMessage>(instanceContext, "services");
                proxy = channelFactory.CreateChannel();
                uid = Guid.NewGuid().ToString();
                proxy.Login(uid);

                isCanConnect = true;

                //if (backgroundWorker_ConnectTest.IsBusy)
                //{
                //    MessageShowForm form = new MessageShowForm("警告", "操作太过频繁，请稍后！");
                //    form.ShowDialog();
                //    return;
                //}
                //else
                //{
                //    backgroundWorker_ConnectTest.RunWorkerAsync();
                //}
                recordLog("打开数据采集");
            }
            catch (Exception)
            {
                DialogResult dr = MessageBox.Show("与服务端建立连接失败！点击确定退出，点击取消可继续使用回放历史数据功能。", "问题提示", MessageBoxButtons.OKCancel);
                recordLog("与服务端建立连接失败！");
                if (dr == DialogResult.OK)
                {
                    this.Close();
                }
            }

            if (!isCanConnect)
            {
                return;
            }

            sysStatus = SystemStatus.start;
            mainFormRefresh();

            mac = new Machine(SysParam.Instance.channelCount, SysParam.Instance.samplePoint, SysParam.Instance.timePoints, SysParam.Instance.energyPoints);
            mac.lenCountStart = 0;

            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);
            dpc.DataChanged += new ComeNewDataHandle(dpc_DataChanged);


            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();
            firsttime = false;
        }

        private void stop_Click(object sender, EventArgs e)
        {
            needRing = false;

            stoptime = DateTime.Now;

            DialogResult dir = MessageBox.Show("确定停止采集数据吗?", "信息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (dir == DialogResult.OK)
            {
                try
                {
                    if (proxy != null)
                    {
                        proxy.Leave(uid);
                    }
                }
                catch (Exception ex)
                {
                    //throw;
                    DevelopLog.DeBug.WriteLogFile("stop_Click", ex.Message);
                }
                sysStatus = SystemStatus.stop;
                Timer_Graph.Interval = 200;
                //if (backgroundWorker_ConnectTest.IsBusy)
                //{
                //    backgroundWorker.CancelAsync();
                //}
                SysParam.Instance.onlineList.Clear();

                mainFormRefresh();
                if (dpc != null)
                {
                    dpc.Stop();
                }
                Timer_Graph.Stop();
                Timer_Graph_Tick(sender, e);

                recordLog("关闭数据采集");

                timer1.Stop();
                dpc = null;
            }
            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)
        {
            int timeElapsed = (DateTime.Now - ConnectLastTime).Seconds;

            if (timeElapsed > 15)
            {
                if (nodata_form == null || nodata_form.IsDisposed)
                {
                    //DevelopLog.DeBug.WriteLogFile("Timer:", ConnectLastTime.ToString());
                    recordLog("未接收到服务器发送的任何数据，请查看服务端是否开启！");

                    nodata_form = new MessageShowForm("警告", "未接收到服务器发送的任何数据，请查看服务端是否开启！");
                    nodata_form.Show();
                }
                else
                {
                    nodata_form.Activate();
                    nodata_form.WindowState = FormWindowState.Normal;
                }
                Timer_Graph.Interval = 10000;
            }
            else
            {
                Timer_Graph.Interval = 200;
            }

            if (timeElapsed > 1)//与服务器数据断开超过1秒
            {
                DevelopLog.DeBug.WriteLogFile("Timer_Graph_Tick", String.Format("与服务端断开链接超过1s，超时时间{0}s", timeElapsed));
                proxy = channelFactory.CreateChannel();
                //uid = Guid.NewGuid().ToString();//不要改变uid，此处该行注释
                proxy.Login(uid);
            }
            //if (timeElapsed > 1)//与服务器数据断开超过1秒
            //{
            //    DevelopLog.DeBug.WriteLogFile("Timer_Graph_Tick", $"与服务端断开链接超过1s，超时时间{timeElapsed}s");
            //    try
            //    {
            //        if (proxy != null)
            //        {
            //            proxy.Leave(uid);
            //        }
            //        proxy = channelFactory.CreateChannel();
            //        uid = Guid.NewGuid().ToString();
            //        proxy.Login(uid);
            //        //recordLog("数据采集与服务端重连");
            //    }
            //    catch (Exception ex)
            //    {
            //        //throw;
            //        DevelopLog.DeBug.WriteLogFile("Timer_Graph_Tick", ex.Message);
            //        //recordLog("数据采集与服务端重连");
            //    }
            //}

            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.alarmInfoNowChanged)
            {
                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;
                }*/

                //Console.WriteLine($"dpc.alarmInfoNowMG.Count:{dpc.alarmInfoNowMG.Count},mac.cutted:{mac.cutted}");
                if (dpc.alarmInfoNowMG.Count == 0)
                {
                    return;
                }
                string alarmText = "";
                for (int i = 0; i < dpc.alarmInfoNowMG.Count; i++)
                {
                    alarmText += dpc.alarmInfoNowMG[i] + "\r\n\r\n";
                }
                alarmShowText.Text = alarmText;
                panel6.BackColor = System.Drawing.Color.Red;

                if (alarmForm == null)
                {
                    alarmForm = new AlarmShowForm(this);

                    int x = this.Location.X + this.Width / 2 - alarmForm.Width / 2;
                    Point point = new Point(x, 0);
                    alarmForm.Location = point;
                    alarmForm.StartPosition = FormStartPosition.Manual;
                    alarmForm.ShowDialog();
                }
                else
                {
                    if (alarmForm.IsDisposed)
                    {
                        alarmForm = new AlarmShowForm(this);

                        int x = this.Location.X + this.Width / 2 - alarmForm.Width / 2;
                        Point point = new Point(x, 0);
                        alarmForm.Location = point;
                        alarmForm.StartPosition = FormStartPosition.Manual;
                        alarmForm.ShowDialog();
                    }
                }


                if (AlarmDataChangEvent != null)
                {
                    AlarmDataChangEvent.Invoke(new Alarmdata(dpc.alarmInfoNowMG));
                }
            }

            if (dpc.alarmInfoNowMG.Count == 0)
            {
                panel6.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            }

            if (dpc.alarmInfoLastChanged)
            {
                dpc.alarmInfoLastChanged = false;
                if (dpc.alarmInfoLast != null)
                {
                    /*comBoxAlarmLast.Items.Clear();
                    comBoxAlarmLast.Items.AddRange(dpc.alarmInfoLast);
                    comBoxAlarmLast.SelectedIndex = comBoxAlarmLast.Items.Count - 1;*/
                }
            }

            //if (SysParam.Instance.alarmingType == 0)
            //{
            //    if (alarmForm != null)
            //    {
            //        alarmForm.Visible = false;
            //    }
            //}
            //else if (SysParam.Instance.alarmingType == 1)
            //{
            //    if (alarmForm != null)
            //    {
            //        alarmForm.Visible = false;
            //    }
            //}
            //else if (SysParam.Instance.alarmingType == 2)
            ////报警时
            //{
            //    if (alarmForm == null)
            //    {
            //        alarmForm = new AlarmShowForm(this);

            //        int x = this.Location.X + this.Width / 2 - alarmForm.Width / 2;
            //        Point point = new Point(x, 0);
            //        alarmForm.Location = point;
            //        alarmForm.StartPosition = FormStartPosition.Manual;
            //        alarmForm.ShowDialog();
            //    }
            //    else
            //    {
            //        alarmForm.Visible = true;
            //    }

            //    if (AlarmDataChangEvent != null)
            //    {
            //        AlarmDataChangEvent.Invoke(null);
            //    }
            /*else
            {
                if (alarmForm.IsDisposed)
                {
                    alarmForm = new AlarmShowForm(this);

                    int x = this.Location.X + this.Width / 2 - alarmForm.Width / 2;
                    Point point = new Point(x, 0);
                    alarmForm.Location = point;
                    alarmForm.StartPosition = FormStartPosition.Manual;
                    alarmForm.ShowDialog();
                }
            }*/
            //}
        }

        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 btnViewOut_Click(object sender, EventArgs e)
        {
            isReview = false;
            mainFormRefresh();
            CloseDocumnet("PlottingReview");
            CloseDocumnet("Plot_energy");
            if (sysStatus != SystemStatus.off)
            {
                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 FileExistsCheck(object sender, string filePath)
        {
            if (File.Exists(filePath))
            {
                //DataRead(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 DataReviewEnergy()
        {
            CloseDocumnet("PlottingReview");
            CloseDocumnet("Plotting");
            CloseDocumnet("Plot_energy");
            reviewPlot_Energy = new Plot_energy(fileHelper, macReview);
            reviewPlot_Energy.Show(this.dockPanel1, DockState.Document);
        }
        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();
                }
                //DbHelper.GetInstance("").RollDataInfo(macReview);
            }
            else
            {
                MessageBox.Show("文件已损坏！");
            }
        }

        private void DataReview()
        {
            CloseDocumnet("PlottingReview");
            CloseDocumnet("Plotting");
            CloseDocumnet("Plot_energy");
            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 = client.Properties.Resources.Pause_64;
                        btPause.Text = "暂停";
                    }
                    else
                    {
                        btStop.Enabled = false;
                        btPause.Image = client.Properties.Resources.Refresh_64;
                        btPause.Text = "继续";
                    }
                    btstart.Enabled = false;
                    btPause.Enabled = true;

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

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

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

                    btSetAlarm.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 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 setpassword_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            if (log.DialogResult == DialogResult.OK)
            {
                SetPasswordForm newForm = new SetPasswordForm();
                newForm.ShowDialog();
            }
        }

        private void help_Click(object sender, EventArgs e)
        {
            //HelpForm help = new HelpForm();
            //help.Show();
            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 rollInfo_Click(object sender, EventArgs e)
        {
            if (isReview)
            {
                OriginRollForm form = new OriginRollForm(macReview);
                form.StartPosition = FormStartPosition.CenterScreen;
                form.ShowDialog();
            }
            else
            {
                OnlineRollForm form = new OnlineRollForm();
                form.StartPosition = FormStartPosition.CenterScreen;
                form.ShowDialog();
            }
        }

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

        private void database_Click(object sender, EventArgs e)
        {
            login log = new login();
            log.ShowDialog();
            if (log.DialogResult == DialogResult.OK)
            {
                DataAccessForm newForm = new DataAccessForm(dbHelper);
                newForm.ShowDialog();
                if (newForm.DialogResult == DialogResult.OK)
                {
                    Timer_CoilInfo.Start();
                    this.Timer_CoilInfo.Interval = DbHelper.GetInstance("").Freq * 1000;
                }
                if (newForm.DialogResult == DialogResult.No)
                {
                    Timer_CoilInfo.Stop();
                }
            }
        }

        private void IClientMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            /*needRing = false;

            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);

                recordLog("退出客户端");
            }
            else
            {
                e.Cancel = true;
            }*/
            needRing = false;

            stoptime = DateTime.Now;

            DialogResult dir = MessageBox.Show("确定停止采集数据吗?", "信息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (dir == DialogResult.OK)
            {
                try
                {
                    if (proxy != null)
                    {
                        proxy.Leave(uid);
                    }
                }
                catch
                {
                    //throw;
                }
                sysStatus = SystemStatus.stop;
                Timer_Graph.Interval = 200;
                //if (backgroundWorker_ConnectTest.IsBusy)
                //{
                //    backgroundWorker.CancelAsync();
                //}
                SysParam.Instance.onlineList.Clear();

                //mainFormRefresh();
                if (dpc != null)
                {
                    dpc.Stop();
                }
                Timer_Graph.Stop();
                //Timer_Graph_Tick(sender, e);
                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 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 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)
                {
                    if (Directory.Exists(dirList[0].FullName))
                    {
                        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))
                {
                    if (Directory.Exists(dirStr))
                    {
                        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 backgroundWorker_ConnectTest_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    proxy.Update(uid);
                }
                catch (Exception)
                {
                    try
                    {
                        proxy = channelFactory.CreateChannel();
                        proxy.Login(uid);
                    }
                    catch (Exception)
                    {
                        backgroundWorker_ConnectTest.ReportProgress(0, "reconnect failed");
                        break;
                    }
                }
                if (sysStatus == SystemStatus.stop)
                {
                    try
                    {
                        proxy.Leave(uid);
                    }
                    catch (Exception)
                    {

                    }
                    break;
                }
            }
        }

        private void backgroundWorker_ConnectTest_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            MessageShowForm form = new MessageShowForm("警告", e.UserState.ToString());
            form.ShowDialog();
        }

        private void timer_RollInfo_Tick(object sender, EventArgs e)
        {
            if (dbHelper != null && mac != null)
            {
                if (isRollInfoRead == false || mac.lengthSpeed < 50)
                {
                    DataTable rolldata = dbHelper.GetL2OnlineRollInfo();
                    if (rolldata.Rows.Count == 0)
                    {
                        return;
                    }
                    dbHelper.RollDataInfo(mac, rolldata);
                    isRollInfoRead = true;
                }
            }
        }

        public delegate void AlarmDataHandle(Alarmdata data);
        public event AlarmDataHandle AlarmDataChangEvent;

        public class Alarmdata : EventArgs
        {
            public List<string> alarmInfo;

            public Alarmdata(List<string> alarmInfo)
            {
                this.alarmInfo = new List<string>();
                for (int i = 0; i < alarmInfo.Count; i++)
                {
                    this.alarmInfo.Add(alarmInfo[i]);
                }
            }
        }


        //设置实时报警信息兰的显示/隐藏
        private void btnAlarmVisual_Click(object sender, EventArgs e)
        {
            //if (!isReview)
            {
                if (tableLayoutPanel4.Visible == true)
                {
                    tableLayoutPanel4.Visible = false;
                    tableLayoutPanel2.ColumnStyles[2].Width = 0;
                    tableLayoutPanel2.ColumnStyles[2].SizeType = SizeType.Absolute;
                    this.btnAlarmVisual.Image = global::client.Properties.Resources.不可见;
                }
                else
                {
                    tableLayoutPanel4.Visible = true;
                    tableLayoutPanel2.ColumnStyles[2].Width = 241;
                    tableLayoutPanel2.ColumnStyles[2].SizeType = SizeType.Absolute;
                    this.btnAlarmVisual.Image = global::client.Properties.Resources.可见;
                }
            }

        }

        private void alarmRing_Click(object sender, EventArgs e)
        {
            SetAlarmRingForm ringForm = new SetAlarmRingForm();
            ringForm.ShowDialog();
        }

        AlarmRing ring = new AlarmRing();
        private void timer1_Tick(object sender, EventArgs e)
        {
            ring.Ring();
        }


        bool needRing = false;
        bool needVoice = false;
        private void timer2_Tick(object sender, EventArgs e)
        {
            needRing = false;
            needVoice = false;


            if ((SysParam.Instance.alarming1 && SysParam.Instance.isStand1Ring) || (SysParam.Instance.alarming2 && SysParam.Instance.isStand2Ring) ||
                 (SysParam.Instance.alarming3 && SysParam.Instance.isStand3Ring) || (SysParam.Instance.alarming4 && SysParam.Instance.isStand4Ring) ||
                 (SysParam.Instance.alarming5 && SysParam.Instance.isStand5Ring) || SysParam.Instance.alarming6 && SysParam.Instance.isStand6Ring)
            //if (SysParam.Instance.alarmingType == 2)
            {
                //需要播放报警铃声
                needRing = true;
            }

            /*for (int i = 5; i >= 1; i--)
            {
                for (int j = 3; j >= 1; j--)
                {
                    if (SysParam.Instance.ringflag[i - 1, j - 1])
                    {
                        needVoice = true;
                    }
                }
            }*/

            //needVoice = true;
            if (needRing)
            {
                if (timer1.Enabled == false)
                {
                    ring.Ring();
                }
                timer1.Enabled = true;
                timer1.Interval = 200;
                timer1.Start();
            }
            else
            {
                timer1.Enabled = false;
                timer1.Stop();
            }

        }

        private void btn_logInfo_Click(object sender, EventArgs e)
        {
            LogForm form = new LogForm();
            form.ShowDialog();
        }

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

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

    }

}