using System;
using CRVM.Entity;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using ICService;
using System.Collections.Generic;
using CRVM.Utility;
using System.Timers;
//using CRVM.Driver;

namespace CRVM.CIDExcuter
{

    public class OrginalCollectDataEventArgs : EventArgs { }

    public delegate void ComeNewDataHandle(OrginalCollectDataEventArgs e);
    public class DataProcessCenter
    {
        //调试
        System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
        public event ComeNewDataHandle DataChanged;
        private Machine mac;
        private IDataHelper dataHelper;

        private bool isAlarmingNow;
        private bool isAlarmingLast;
        private bool lowRing, midRing, highRing;
        private bool isDefect;
        private bool[,] ringflag = new bool[SysParam.Instance.SpeedChannelCount, 3];//报警范围内使用，记录报警范围内哪个机架哪个频段发生报警
        private bool[,] defectflag = new bool[SysParam.Instance.SpeedChannelCount, 3];//报警范围内使用，记录报警范围内哪个机架哪个频段发生报警
        private double[] alarm_MaxEnergy = new double[SysParam.Instance.SpeedChannelCount];//报警范围内使用，记录五个机架报警范围内产生的最大能量值
        private int[] alarm_Position = new int[SysParam.Instance.SpeedChannelCount];


        private AlarmRing alarmRing;
        public List<string> alarmInfoNow = new List<string>();
        public List<string> alarmInfoNowMG = new List<string>();
        public string[] alarmInfoLast;

        private double[] lineSpdFactor = { 1.0, 1.0, 1.0, 1.0, 1.0 };

        int isCoilHasDefect = 0;
        private Dictionary<int, int> defectData = new Dictionary<int, int>();//记录当次的缺陷报警记录
        private Dictionary<int, int> allDefectData = new Dictionary<int, int>();//记录所有的缺陷报警信息
        private Dictionary<int, double> maxDefectEnergy = new Dictionary<int, double>();//发生缺陷时的最大能量值
        private double maxDefectEnergyValue = 0.0d;//记录最大能量值

        private bool isDefectNow = false;//记录此次采集是否超越缺陷报警线
        private bool isDefectLast = false;//记录上次采集是否超越缺陷报警线
        private bool isDefectFirstPiont = false;//是否第一个点超越报警线
        private int defectStartPos = -1;
        private Dictionary<int, int> defectPos = new Dictionary<int, int>();//记录所有的缺陷报警信息
        private Dictionary<int, double> defectMaxEnergy = new Dictionary<int, double>();//发生缺陷时的最大能量值

        bool before = false;
        bool now = false;
        //private ZDSate zdState;
        private bool[] zdStateData;
        int i = 0;

        double coilenMax = 0.0d;
        int nextCoilCounter = 0;

        private System.Timers.Timer alarmParamUpdate = new System.Timers.Timer();

        public DataProcessCenter(Machine mac)
        {
            this.mac = mac;
            dataHelper = new IDataHelper(mac);
            alarmRing = new AlarmRing();
            mac.startTime = DateTime.Now;

            //zdState = new ZDSate();
            //zdStateData = new bool[zdState.linesCount];

            /* ---------------------定时从数据库更新报警参数任务--------------------*/
            alarmParamUpdate.Interval = 5 * 60 * 1000; //执行间隔时间,单位为毫秒, 5 minutes; 
            alarmParamUpdate.Elapsed += new System.Timers.ElapsedEventHandler(AlarmParamUpdate);
            alarmParamUpdate.Enabled = true;
            alarmParamUpdate.Start();
        }
        /// <summary>
        /// 定时从数据库更新报警参数
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void AlarmParamUpdate(object source, ElapsedEventArgs e)
        {
            DbHelper.GetInstance("").autoUpdateAlarmParam();
        }
        public void DataProcess()    //数据处理
        {
            //for (int i = 0; i < zdStateData.Length; i++)
            //{
            //    zdStateData[i] = false;
            //}
            //DevelopLog.DeBug.WriteLogFile("DataProcess()", $"threadid:{Thread.CurrentThread.ManagedThreadId.ToString()},stackTrace:{stackTrace.GetFrame(1).GetMethod().ToString()}");
            //Console.WriteLine($"nowTime:{DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss:FFF")}, DataProcess() --threadid:{Thread.CurrentThread.ManagedThreadId.ToString()}," +
            //    $"stackTrace:{stackTrace.GetFrame(1).GetMethod().ToString()}");
            isAlarmingNow = false;//初始化报警状态
            isDefectNow = false;
            lowRing = false;
            midRing = false;
            highRing = false;

            for (int i = 0; i < SysParam.Instance.channelCount; i++)//全部通道
            {
                //消除直流偏置
                DCBias(mac.Stand[i].vib);
                //根据当前速度设定各机架报警系数
                GetAlarmParam(mac.Stand[i].speed, mac.Stand[i]);
                //分频滤波
                mac.Stand[i].vibLow = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_L1, mac.Stand[i].band_Fre_L2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                mac.Stand[i].vibMid = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_M1, mac.Stand[i].band_Fre_M2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                mac.Stand[i].vibHig = SysParam.Instance.filterAlgor(mac.Stand[i].vib, mac.Stand[i].band_Fre_H1, mac.Stand[i].band_Fre_H2, SysParam.Instance.samplePoint, 100, SysParam.Instance.sampleFre);
                //各通道、各频段能量值计算
                mac.Stand[i].energy_All = GetRMS(mac.Stand[i].vib);
                mac.Stand[i].energy_L = GetRMS(mac.Stand[i].vibLow);
                mac.Stand[i].energy_M = GetRMS(mac.Stand[i].vibMid);
                mac.Stand[i].energy_H = GetRMS(mac.Stand[i].vibHig);
            }

            for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)//仅针对有速度的通道进行报警判断
            {
                //轧机振动报警判断
                AlarmJudge(mac.Stand[i], i);
            }
            //alarmingProcess();//20240312
            //DevelopLog.DeBug.WriteLogFile("alarming", SysParam.Instance.alarming1.ToString() + "|" + SysParam.Instance.alarming2.ToString() + "|"
            //+ SysParam.Instance.alarming3.ToString() + "|" + SysParam.Instance.alarming4.ToString() + "|" + SysParam.Instance.alarming5.ToString() + "|"
            //+ SysParam.Instance.alarmingType.ToString());

            //向L1 tdc发送轧机振动状态信息
            //zdState.WriteData(zdStateData);

            //播放报警铃声        
            //alarmRing.Ring(lowRing, midRing, highRing);
            //如报警结束，播放语音报告报警机架
            if (isAlarmingLast && !isAlarmingNow)
            {
                bool[,] tempAlarmFlag = (bool[,])ringflag.Clone();
                SysParam.Instance.ringflag = (bool[,])ringflag.Clone();

                //ringflag.Initialize();
                ringflag = new bool[SysParam.Instance.SpeedChannelCount, 3];
                if (isDefect)
                {
                    isDefect = false;
                    bool[,] tempDefectFlag = (bool[,])defectflag.Clone();
                    defectflag.Initialize();
                    alarmRing.DefectVoice(tempDefectFlag, tempAlarmFlag);
                }
                else
                {
                    alarmRing.AlarmVoice(tempAlarmFlag);
                }
            }

            nextCoilCounter++;
            if (coilenMax <= mac.stripLength && nextCoilCounter > 20)
            {
                coilenMax = mac.stripLength;
            }

            //存储数据        
            if (!SysParam.Instance.fileCreated)
            {
                dataHelper.CreateFileHead();
            }
            dataHelper.writeNew(SysParam.Instance.samplePoint);
            //更新报警信息
            if (isAlarmingNow)
            {
                for (int k = 0; k < SysParam.Instance.SpeedChannelCount; k++)
                {
                    UpdateAlarmInfo(mac.Stand[k], k); ;//更新报警信息   
                }
            }
            //来了剪切信号
            if (mac.cutted)
            {
                Dictionary<int, int> tempDefectPos = new Dictionary<int, int>();
                foreach (KeyValuePair<int, int> item in defectPos)
                {
                    tempDefectPos.Add(item.Key, item.Value);
                }

                Dictionary<int, double> tempDefectMaxEnergy = new Dictionary<int, double>();
                foreach (KeyValuePair<int, double> item in defectMaxEnergy)
                {
                    tempDefectMaxEnergy.Add(item.Key, item.Value);
                }
                int dislen = Convert.ToInt32(coilenMax);

                //dataHelper.CloseFile(1, alarmInfoNow, Convert.ToInt32(mac.stripLength), isCoilHasDefect, tempDefectPos, tempDefectMaxEnergy);
                dataHelper.CloseFile(1, alarmInfoNow, Convert.ToInt32(dislen), isCoilHasDefect, tempDefectPos, tempDefectMaxEnergy);

                //dataHelper.CloseFile(1, alarmInfoNow, Convert.ToInt32(mac.stripLength), isCoilHasDefect, allDefectData, maxDefectEnergy);
                stateRefresh();

                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录start
                isCoilHasDefect = 0;
                defectData.Clear();
                allDefectData.Clear();
                maxDefectEnergy.Clear();
                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录end

                isDefectNow = false;//记录此次采集是否超越缺陷报警线
                isDefectLast = false;//记录上次采集是否超越缺陷报警线
                isDefectFirstPiont = false;//是否第一个点超越报警线
                defectStartPos = -1;
                defectPos.Clear();//记录所有的缺陷报警信息
                defectMaxEnergy.Clear();//发生缺陷时的最大能量值
                maxDefectEnergyValue = 0.0d;

                coilenMax = 0.0d;
                nextCoilCounter = 0;
                mac.stripLength = 0;
            }
            //累计采集时间超过半小时，文件强制关闭
            if ((DateTime.Now - mac.startTime).TotalMinutes > 30)
            //if ((DateTime.Now - mac.startTime).TotalMinutes > 10)

            {
                mac.cutted = true;
                Dictionary<int, int> tempDefectPos = new Dictionary<int, int>();
                foreach (KeyValuePair<int, int> item in defectPos)
                {
                    tempDefectPos.Add(item.Key, item.Value);
                }

                Dictionary<int, double> tempDefectMaxEnergy = new Dictionary<int, double>();
                foreach (KeyValuePair<int, double> item in defectMaxEnergy)
                {
                    tempDefectMaxEnergy.Add(item.Key, item.Value);
                }

                dataHelper.CloseFile(0, alarmInfoNow, Convert.ToInt32(mac.stripLength), isCoilHasDefect, tempDefectPos, tempDefectMaxEnergy);
                stateRefresh();

                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录start
                isCoilHasDefect = 0;
                defectData.Clear();
                allDefectData.Clear();
                maxDefectEnergy.Clear();
                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录end

                isDefectNow = false;//记录此次采集是否超越缺陷报警线
                isDefectLast = false;//记录上次采集是否超越缺陷报警线
                isDefectFirstPiont = false;//是否第一个点超越报警线
                defectStartPos = -1;
                defectPos.Clear();//记录所有的缺陷报警信息
                defectMaxEnergy.Clear();//发生缺陷时的最大能量值
                maxDefectEnergyValue = 0.0d;
            }
            //Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  8 FileStore");
            double temptime = DateTime.Now.ToOADate();
            //更新绘图所需数据
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                ArrayMove(mac.Stand[i].tVib, mac.Stand[i].vib);


                mac.Stand[i].list_Energy_All.Add(mac.Stand[i].energy_All);
                mac.Stand[i].list_Energy_L.Add(mac.Stand[i].energy_L);
                mac.Stand[i].list_Energy_M.Add(mac.Stand[i].energy_M);
                mac.Stand[i].list_Energy_H.Add(mac.Stand[i].energy_H);

                mac.Stand[i].list_Alarm_L.Add(mac.Stand[i].alarm_L_Value_ck);
                mac.Stand[i].list_Alarm_M.Add(mac.Stand[i].alarm_M_Value_ck);
                mac.Stand[i].list_Alarm_H.Add(mac.Stand[i].alarm_H_Value_ck);

                mac.Stand[i].list_Defect_L.Add(mac.Stand[i].defect_L_Value_ck);
                mac.Stand[i].list_Defect_M.Add(mac.Stand[i].defect_M_Value_ck);
                mac.Stand[i].list_Defect_H.Add(mac.Stand[i].defect_H_Value_ck);

                mac.Stand[i].list_Energy_Speed.Add(mac.Stand[i].speed);
            }
            mac.xAxisEnergy.Add(temptime);
            mac.distance_Running.Add(mac.stripLength);
            if (mac.cutted)
            {
                mac.list_CutTime.Add(temptime);
            }
            if (mac.list_CutTime.Count > 0 && mac.list_CutTime[0] < mac.xAxisEnergy.Head)
            {
                mac.list_CutTime.RemoveAt(0);
            }

            //剪切信号复位
            mac.cutted = false;
            //帧数据结束
            isAlarmingLast = isAlarmingNow;
            SysParam.Instance.isDatahandlered = true;//此次采集的数据全部处理结束标记
            isDefectLast = isDefectNow;


        }

        private void alarmingProcess()
        {
            if (SysParam.Instance.alarming1 || SysParam.Instance.alarming2 || SysParam.Instance.alarming3 || SysParam.Instance.alarming4 || SysParam.Instance.alarming5)
            {
                if (SysParam.Instance.alarming5 && SysParam.Instance.alarming4)
                {
                    SysParam.Instance.alarmingType = 2;
                }
                else
                {
                    SysParam.Instance.alarmingType = 1;
                }
            }
            else
            {
                SysParam.Instance.alarmingType = 0;
            }

            if (SysParam.Instance.alarmingType == 2)//现场共振了记录报警信息
            {
                for (int k = 3; k < SysParam.Instance.SpeedChannelCount; k++)//只看4、5机架
                {
                    mac.Stand[k].alarm_M_Times++;
                    if (mac.Stand[k].alarm_M_Times == 1)//第一次报警记录开始位置
                    {
                        mac.Stand[k].tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                        ringflag[k, 1] = true;
                        mac.Stand[k].alarmMidInfo.Add(new Stand.AlarmInfo());
                        mac.Stand[k].indexMid++;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].startPos = mac.Stand[k].tempAlarmMidInfostart;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].endPos = mac.Stand[k].tempAlarmMidInfostart;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value = mac.Stand[k].energy_M;
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].time = DateTime.Now;
                        isAlarmingNow = true;
                    }

                    if (mac.Stand[k].alarm_M_Times > 1)//连续报警时，不断更新结束位置
                    {
                        if (mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value < mac.Stand[k].energy_M)
                        {
                            mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].value = mac.Stand[k].energy_M;
                        }
                        mac.Stand[k].alarmMidInfo[mac.Stand[k].indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                        isAlarmingNow = true;
                    }
                }
            }
            else
            {
                for (int k = 3; k < SysParam.Instance.SpeedChannelCount; k++)//只看4、5机架
                {
                    mac.Stand[k].alarm_M_Times = 0;
                }
            }
        }

        private void DCBias(double[] temp)////数组先求平均然后数组中的每个值减去这个平均值
        {
            double tempValue = 0;
            int length = temp.Length;
            for (int i = 0; i < length; i++)
            {
                tempValue += temp[i];
            }
            tempValue = tempValue / length;
            for (int i = 0; i < length; i++)
            {
                temp[i] -= tempValue;
            }
        }

        //查表，该机架在当前速度下的报警参数
        private void GetAlarmParam(double speed, Stand std)
        {
            int ias = std.alarm_spd.Length;
            int i_fre = std.fre_l_S1.Length - 1;
            int iIndex = std.alarm_spd[0].alarmSpeed;
            if (speed <= std.alarm_spd[0].alarmSpeed)
            {
                std.band_Fre_L1 = std.fre_l_S1[0];
                std.band_Fre_L2 = std.fre_l_S2[0];
                std.band_Fre_M1 = std.fre_m_S1[0];
                std.band_Fre_M2 = std.fre_m_S2[0];
                std.band_Fre_H1 = std.fre_h_S1[0];
                std.band_Fre_H2 = std.fre_h_S2[0];
                std.alarm_L_Value_ck = std.fre_l_V[0];
                std.alarm_M_Value_ck = std.fre_m_V[0];
                std.alarm_H_Value_ck = std.fre_h_V[0];
                std.defect_L_Value_ck = std.fre_l_D[0];
                std.defect_M_Value_ck = std.fre_m_D[0];
                std.defect_H_Value_ck = std.fre_h_D[0];
            }
            else if (speed >= std.alarm_spd[ias - 1].alarmSpeed)
            {
                std.band_Fre_L1 = std.fre_l_S1[i_fre];
                std.band_Fre_L2 = std.fre_l_S2[i_fre];
                std.band_Fre_M1 = std.fre_m_S1[i_fre];
                std.band_Fre_M2 = std.fre_m_S2[i_fre];
                std.band_Fre_H1 = std.fre_h_S1[i_fre];
                std.band_Fre_H2 = std.fre_h_S2[i_fre];
                std.alarm_L_Value_ck = std.fre_l_V[i_fre];
                std.alarm_M_Value_ck = std.fre_m_V[i_fre];
                std.alarm_H_Value_ck = std.fre_h_V[i_fre];
                std.defect_L_Value_ck = std.fre_l_D[i_fre];
                std.defect_M_Value_ck = std.fre_m_D[i_fre];
                std.defect_H_Value_ck = std.fre_h_D[i_fre];
            }
            else
            {
                std.band_Fre_L1 = std.fre_l_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_L2 = std.fre_l_S2[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_M1 = std.fre_m_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_M2 = std.fre_m_S2[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_H1 = std.fre_h_S1[Convert.ToInt32(speed - iIndex)];
                std.band_Fre_H2 = std.fre_h_S2[Convert.ToInt32(speed - iIndex)];
                std.alarm_L_Value_ck = std.fre_l_V[Convert.ToInt32(speed - iIndex)];
                std.alarm_M_Value_ck = std.fre_m_V[Convert.ToInt32(speed - iIndex)];
                std.alarm_H_Value_ck = std.fre_h_V[Convert.ToInt32(speed - iIndex)];
                std.defect_L_Value_ck = std.fre_l_D[Convert.ToInt32(speed - iIndex)];
                std.defect_M_Value_ck = std.fre_m_D[Convert.ToInt32(speed - iIndex)];
                std.defect_H_Value_ck = std.fre_h_D[Convert.ToInt32(speed - iIndex)];
            }
        }

        private double GetRMS(double[] temp)
        {
            double rms = 0;
            int length = temp.Length;
            for (int i = 0; i < length; i++)
            {
                rms += temp[i] * temp[i];
            }
            rms = Math.Sqrt(rms / length);
            return rms;
        }

        //数据递归画图用
        private void ArrayMove(double[] longArray, double[] shortArray)
        {
            int longlength = longArray.Length;
            int shortlength = shortArray.Length;
            if (longlength > shortlength)
            {
                for (int i = 0; i < longlength - shortlength; i++)
                {
                    longArray[i] = longArray[i + shortlength];
                }
                for (int i = 0; i < shortlength; i++)
                {
                    longArray[i + longlength - shortlength] = shortArray[i];
                }
            }
        }

        private void ListAdd(List<double> tempList, double value)
        {
            tempList.Add(value);
            if (tempList.Count > SysParam.Instance.energyPoints + 1)
            {
                tempList.RemoveAt(0);
            }
        }

        /// <summary>
        /// 振动报警判断 45机架
        /// </summary>
        private void AlarmJudge45(Stand std, int standNo)
        {
            bool alarmingFlag = false;

            bool flag = false;

            //低频报警信息
            if (std.energy_L >= std.alarm_L_Value_ck)
            {
                alarmingFlag = true;

                /*std.alarm_L_Times++;
                if (std.alarm_L_Times == 1)
                {
                    std.tempAlarmLowInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_L_Times == std.alarm_L_Times_ck)
                {
                    ringflag[standNo, 0] = true;
                    std.alarmLowInfo.Add(new Stand.AlarmInfo());
                    std.indexLow++;
                    std.alarmLowInfo[std.indexLow - 1].startPos = std.tempAlarmLowInfostart;
                    std.alarmLowInfo[std.indexLow - 1].time = DateTime.Now;
                }
                if (std.alarm_L_Times >= std.alarm_L_Times_ck)
                {
                    if (std.alarmLowInfo[std.indexLow - 1].value < std.energy_L)
                    {
                        std.alarmLowInfo[std.indexLow - 1].value = std.energy_L;
                    }
                    std.alarmLowInfo[std.indexLow - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    lowRing = true;

                    flag = true;
                }*/
                if (std.energy_L >= std.defect_L_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 0] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;

                    flag = true;
                }
            }
            else
            {
                //std.alarm_L_Times = 0;
            }

            //中频报警位置
            if (std.energy_M >= std.alarm_M_Value_ck)
            {
                alarmingFlag = true;

                /*std.alarm_M_Times++;
                if (std.alarm_M_Times == 1)
                {
                    std.tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_M_Times == std.alarm_M_Times_ck)
                {
                    ringflag[standNo, 1] = true;
                    std.alarmMidInfo.Add(new Stand.AlarmInfo());
                    std.indexMid++;
                    std.alarmMidInfo[std.indexMid - 1].startPos = std.tempAlarmMidInfostart;
                    std.alarmMidInfo[std.indexMid - 1].time = DateTime.Now;

                }
                if (std.alarm_M_Times >= std.alarm_M_Times_ck)
                {
                    if (std.alarmMidInfo[std.indexMid - 1].value < std.energy_M)
                    {
                        std.alarmMidInfo[std.indexMid - 1].value = std.energy_M;
                    }
                    std.alarmMidInfo[std.indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    midRing = true;

                    flag = true;

                }*/
                if (std.energy_M >= std.defect_M_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 1] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;

                    flag = true;
                }
            }
            else
            {
                //std.alarm_M_Times = 0;
            }

            //高频报警信息
            if (std.energy_H >= std.alarm_H_Value_ck)
            {
                alarmingFlag = true;

                /*std.alarm_H_Times++;
                if (std.alarm_H_Times == 1)
                {
                    std.tempAlarmHighInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_H_Times == std.alarm_H_Times_ck)
                {
                    ringflag[standNo, 2] = true;
                    std.alarmHighInfo.Add(new Stand.AlarmInfo());
                    std.indexHigh++;
                    std.alarmHighInfo[std.indexHigh - 1].startPos = std.tempAlarmHighInfostart;
                    std.alarmHighInfo[std.indexHigh - 1].time = DateTime.Now;

                }
                if (std.alarm_H_Times >= std.alarm_H_Times_ck)
                {
                    if (std.alarmHighInfo[std.indexHigh - 1].value < std.energy_H)
                    {
                        std.alarmHighInfo[std.indexHigh - 1].value = std.energy_H;
                    }
                    std.alarmHighInfo[std.indexHigh - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    highRing = true;

                    flag = true;
                }*/
                if (std.energy_H >= std.defect_H_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 2] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;

                    flag = true;
                }
            }
            else
            {
                //std.alarm_H_Times = 0;
            }

            if (isDefectNow)
            {
                if (std.energy_H > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_H;
                }
                if (std.energy_M > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_M;
                }
                if (std.energy_L > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_L;
                }
            }

            if (isDefectFirstPiont == false && isDefectNow == true)
            {
                isDefectFirstPiont = true;
            }

            if (isDefectNow && isDefectFirstPiont == true && defectStartPos == -1)
            {
                defectStartPos = Convert.ToInt32(mac.stripLength);
                if (!defectPos.ContainsKey(defectStartPos))
                {
                    defectPos.Add(defectStartPos, defectStartPos);
                }
                else
                {
                    defectPos[defectStartPos] = defectStartPos;
                }
                isDefectFirstPiont = false;
            }

            if (isDefectLast == true && isDefectNow == false && defectStartPos != -1)
            {
                defectPos[defectStartPos] = Convert.ToInt32(mac.stripLength);
                defectMaxEnergy[defectStartPos] = maxDefectEnergyValue;
                maxDefectEnergyValue = 0.0d;
                defectStartPos = -1;
            }


            if (standNo == 0)
            {
                SysParam.Instance.alarming1 = alarmingFlag ? true : false;
            }
            if (standNo == 1)
            {
                SysParam.Instance.alarming2 = alarmingFlag ? true : false;
            }
            if (standNo == 2)
            {
                SysParam.Instance.alarming3 = alarmingFlag ? true : false;
            }
            if (standNo == 3)
            {
                SysParam.Instance.alarming4 = alarmingFlag ? true : false;
            }
            if (standNo == 4)
            {
                SysParam.Instance.alarming5 = alarmingFlag ? true : false;
            }
            if (standNo == 5)
            {
                SysParam.Instance.alarming6 = alarmingFlag ? true : false;
            }


            /*if (flag)
            {
                now = true;

                zdStateData[standNo * 8 + 1] = true;
                zdStateData[standNo * 8 + 0] = false;
                before = true;
            }
            else
            {
                now = false;
                if (before == true)
                {
                    zdStateData[standNo * 8 + 1] = false;
                    zdStateData[standNo * 8 + 0] = true;
                    if (i < 11)
                    {
                        before = true;
                        i++;
                    }
                    else
                    {
                        before = false;
                        i = 0;
                    }
                }
                else
                {
                    zdStateData[standNo * 8 + 1] = false;
                    zdStateData[standNo * 8 + 0] = false;
                    before = false;
                }
            }*/
        }


        private void AlarmJudge(Stand std, int standNo)
        {
            //低频报警信息
            if (std.energy_L >= std.alarm_L_Value_ck)
            {
                std.alarm_L_Times++;
                if (std.alarm_L_Times == 1)
                {
                    std.tempAlarmLowInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_L_Times == std.alarm_L_Times_ck)
                {
                    ringflag[standNo, 0] = true;
                    std.alarmLowInfo.Add(new Stand.AlarmInfo());
                    std.indexLow++;
                    std.alarmLowInfo[std.indexLow - 1].startPos = std.tempAlarmLowInfostart;
                    std.alarmLowInfo[std.indexLow - 1].time = DateTime.Now;
                }
                if (std.alarm_L_Times >= std.alarm_L_Times_ck)
                {
                    if (std.alarmLowInfo[std.indexLow - 1].value < std.energy_L)
                    {
                        std.alarmLowInfo[std.indexLow - 1].value = std.energy_L;
                    }
                    std.alarmLowInfo[std.indexLow - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    lowRing = true;
                }
                if (std.energy_L >= std.defect_L_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 0] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;
                }
            }
            else
            {
                std.alarm_L_Times = 0;
            }

            //中频报警位置
            if (std.energy_M >= std.alarm_M_Value_ck)
            {
                std.alarm_M_Times++;
                if (std.alarm_M_Times == 1)
                {
                    std.tempAlarmMidInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_M_Times == std.alarm_M_Times_ck)
                {
                    ringflag[standNo, 1] = true;
                    std.alarmMidInfo.Add(new Stand.AlarmInfo());
                    std.indexMid++;
                    std.alarmMidInfo[std.indexMid - 1].startPos = std.tempAlarmMidInfostart;
                    std.alarmMidInfo[std.indexMid - 1].time = DateTime.Now;

                }
                if (std.alarm_M_Times >= std.alarm_M_Times_ck)
                {
                    if (std.alarmMidInfo[std.indexMid - 1].value < std.energy_M)
                    {
                        std.alarmMidInfo[std.indexMid - 1].value = std.energy_M;
                    }
                    std.alarmMidInfo[std.indexMid - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    midRing = true;
                }
                if (std.energy_M >= std.defect_M_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 1] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;
                }
            }
            else
            {
                std.alarm_M_Times = 0;
            }

            //高频报警信息
            if (std.energy_H >= std.alarm_H_Value_ck)
            {
                std.alarm_H_Times++;
                if (std.alarm_H_Times == 1)
                {
                    std.tempAlarmHighInfostart = Convert.ToInt32(mac.stripLength);
                }
                if (std.alarm_H_Times == std.alarm_H_Times_ck)
                {
                    ringflag[standNo, 2] = true;
                    std.alarmHighInfo.Add(new Stand.AlarmInfo());
                    std.indexHigh++;
                    std.alarmHighInfo[std.indexHigh - 1].startPos = std.tempAlarmHighInfostart;
                    std.alarmHighInfo[std.indexHigh - 1].time = DateTime.Now;

                }
                if (std.alarm_H_Times >= std.alarm_H_Times_ck)
                {
                    if (std.alarmHighInfo[std.indexHigh - 1].value < std.energy_H)
                    {
                        std.alarmHighInfo[std.indexHigh - 1].value = std.energy_H;
                    }
                    std.alarmHighInfo[std.indexHigh - 1].endPos = Convert.ToInt32(mac.stripLength);
                    isAlarmingNow = true;
                    highRing = true;
                }
                if (std.energy_H >= std.defect_H_Value_ck && std.speed > 300)
                {
                    defectflag[standNo, 2] = true;
                    isDefect = true;
                    isCoilHasDefect = 1;
                    isDefectNow = true;
                }
            }
            else
            {
                std.alarm_H_Times = 0;
            }

            if (isDefectNow)
            {
                if (std.energy_H > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_H;
                }
                if (std.energy_M > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_M;
                }
                if (std.energy_L > maxDefectEnergyValue)
                {
                    maxDefectEnergyValue = std.energy_L;
                }
            }

            if (isDefectFirstPiont == false && isDefectNow == true)
            {
                isDefectFirstPiont = true;
            }

            if (isDefectNow && isDefectFirstPiont == true && defectStartPos == -1)
            {
                defectStartPos = Convert.ToInt32(mac.stripLength);
                if (!defectPos.ContainsKey(defectStartPos))
                {
                    defectPos.Add(defectStartPos, defectStartPos);
                }
                else
                {
                    defectPos[defectStartPos] = defectStartPos;
                }
                isDefectFirstPiont = false;
            }

            if (isDefectLast == true && isDefectNow == false && defectStartPos != -1)
            {
                defectPos[defectStartPos] = Convert.ToInt32(mac.stripLength);
                defectMaxEnergy[defectStartPos] = maxDefectEnergyValue;
                maxDefectEnergyValue = 0.0d;
                defectStartPos = -1;
            }


            if (standNo == 0)
            {
                SysParam.Instance.alarming1 = isAlarmingNow ? true : false;
            }
            if (standNo == 1)
            {
                SysParam.Instance.alarming2 = isAlarmingNow ? true : false;
            }
            if (standNo == 2)
            {
                SysParam.Instance.alarming3 = isAlarmingNow ? true : false;
            }
            if (standNo == 3)
            {
                SysParam.Instance.alarming4 = isAlarmingNow ? true : false;
            }
            if (standNo == 4)
            {
                SysParam.Instance.alarming5 = isAlarmingNow ? true : false;
            }

            if (standNo == 5)
            {
                SysParam.Instance.alarming6 = isAlarmingNow ? true : false;
            }
        }

        private void UpdateAlarmInfo(Stand std, int stdNo)
        {
            if (std.indexLow > 0)
            {
                AlarmInfo2String(std.alarmLowInfo[std.indexLow - 1], stdNo, "低频");
            }
            if (std.indexMid > 0)
            {
                AlarmInfo2String(std.alarmMidInfo[std.indexMid - 1], stdNo, "中频");
            }
            if (std.indexHigh > 0)
            {
                AlarmInfo2String(std.alarmHighInfo[std.indexHigh - 1], stdNo, "高频");
            }
        }

        private void AlarmInfo2String(Stand.AlarmInfo alarminfo, int standNo, string alarmType)
        {
            string temp = alarminfo.time.ToString("MM/dd HH:mm:ss") + "  " + (standNo + 1) + "号机架" + alarmType + "  位置：" + alarminfo.startPos.ToString("00000") + "-" + alarminfo.endPos.ToString("00000") + "m  能量：" + alarminfo.value.ToString("0.000") + "g";
            int index = temp.IndexOf("-") - 15;//查重，从报警时间后至位置起始点
            if (alarmInfoNow.Count > 15)
            {
                for (int i = alarmInfoNow.Count - 15; i < alarmInfoNow.Count; i++)
                {
                    if (alarmInfoNow[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNow.RemoveAt(i);
                    }
                }
            }
            else
            {
                for (int i = 0; i < alarmInfoNow.Count; i++)
                {
                    if (alarmInfoNow[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNow.RemoveAt(i);
                    }
                }
            }
            alarmInfoNow.Add(temp);

            string tempMG = alarminfo.time.ToString("MM/dd HH:mm:ss") + "\r\n" + (standNo + 1) + "号机架" + alarmType + "\r\n位置：" + alarminfo.startPos.ToString("00000") + "-" + alarminfo.endPos.ToString("00000") + "m\r\n能量：" + alarminfo.value.ToString("0.000") + "g";
            int indexMG = temp.IndexOf("-") - 15;//查重，从报警时间后至位置起始点
            if (alarmInfoNowMG.Count > 15)
            {
                for (int i = alarmInfoNowMG.Count - 15; i < alarmInfoNowMG.Count; i++)
                {
                    if (alarmInfoNowMG[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNowMG.RemoveAt(i);
                    }
                }
            }
            else
            {
                for (int i = 0; i < alarmInfoNowMG.Count; i++)
                {
                    if (alarmInfoNowMG[i].Substring(15, index) == temp.Substring(15, index))
                    {
                        alarmInfoNowMG.RemoveAt(i);
                    }
                }
            }
            alarmInfoNowMG.Add(temp);

            alarmInfoNowChanged = true;
        }

        public bool alarmInfoNowChanged { set; get; }
        public bool alarmInfoLastChanged { set; get; }
        private void stateRefresh()
        {
            if (alarmInfoNow.Count > 0)
            {
                alarmInfoLastChanged = true;
                alarmInfoLast = alarmInfoNow.ToArray();
                alarmInfoNowChanged = true;
                alarmInfoNow.Clear();
            }

            if (alarmInfoNowMG.Count > 0)
            {
                alarmInfoNowMG.Clear();
            }

            mac.startTime = DateTime.Now;
            mac.lenCountStart = mac.lenCountNow;
            //报警参数复位
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                //报警次数清零
                mac.Stand[i].alarm_L_Times = 0;
                mac.Stand[i].alarm_M_Times = 0;
                mac.Stand[i].alarm_H_Times = 0;
            }
        }

        public void Stop()
        {
            Thread.Sleep(500);//等待0.5秒，以免数据未存储完毕            
            if (dataHelper != null)
            {
                Dictionary<int, int> tempDefectPos = new Dictionary<int, int>();
                foreach (KeyValuePair<int, int> item in defectPos)
                {
                    tempDefectPos.Add(item.Key, item.Value);
                }

                Dictionary<int, double> tempDefectMaxEnergy = new Dictionary<int, double>();
                foreach (KeyValuePair<int, double> item in defectMaxEnergy)
                {
                    tempDefectMaxEnergy.Add(item.Key, item.Value);
                }

                //dataHelper.CloseFile(0, alarmInfoNow, Convert.ToInt32(mac.stripLength), isCoilHasDefect, tempDefectPos, tempDefectMaxEnergy);
                dataHelper.CloseFile(2, alarmInfoNow, Convert.ToInt32(mac.stripLength), isCoilHasDefect, tempDefectPos, tempDefectMaxEnergy);//0为超时，1为正常剪切，2为主动关闭
                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录start
                isCoilHasDefect = 0;
                defectData.Clear();
                allDefectData.Clear();
                maxDefectEnergy.Clear();
                //剪切信号时，清除当前缺陷记录和上一卷所有的缺陷记录end
            }
            stateRefresh();

            //zdState.Stop();
        }
    }
}
