//#define debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using GcDevicePc.GCBuffer;
using System.Diagnostics;

namespace GcDevicePc.ProThread
{
    class CKvocUpdata
    {
        ManualResetEvent datamre = new ManualResetEvent(false);
        Thread t_DataSave;
        int isstart = 0;

       
        //批量更新 
        //用于更新记录数据
        private void Monitor_DataList()
        {
            try
            {
                double time = 0;
                double value = 0;

                //float dtime = 0.0f;
                //float dvalue = 0.0f;
                List<double[]> listPoint = new List<double[]>();//临时数据区
                List<double[]> listRaw = new List<double[]>();//原始数据
                List<double[]> listRawTem = new List<double[]>();//原始数据缓存
                bool drbool = false;
                uint NowTimeOld=0;//上一周期开始
               
                while (!datamre.WaitOne(500))
                {

                    drbool = false;
                    listPoint.Clear();
                    listRaw.Clear();
                    if ((globaldata.m_hmibuffer.gcinfo.methodstatus == 4 || globaldata.m_hmibuffer.gcinfo.methodstatus == 5) || globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)  //判断HMI工作模式     0-空闲 1-2 准备  3准备就绪  4-5 运行（分保持和程升） 6-7结束后处理
                   // if(true)
                    {
#if(debug)
                        Stopwatch st = new Stopwatch();  //计时
                        st.Reset();  //清零
#endif

                        lock (globaldata.m_signalbuffer.Draw_Port)
                        {

                            if (globaldata.m_signalbuffer.Draw_Port.Count > 1)
                            {

                                if (globaldata.startclear)
                                {
                                    CurveDisPlay.curdisp.cleardata();
                                    globaldata.starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[0]).ctimer;


                                    time = 0;
                                    globaldata.startclear = false;
                                }

                             
                                else
                                {

                                    if (globaldata.startimerIsSet)
                                    {
                                        CurveDisPlay.curdisp.cleardata();
                                        globaldata.starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[0]).ctimer;
                                        time = 0;
                                        globaldata.startimerIsSet = false;
                                    }
                                
                                    ushort timeend = globaldata.m_dpbuffer.ShowList.showtime.alltime;
                                    timeend -= 5;
                                    if (globaldata.starttimer == 0)
                                        globaldata.starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[0]).ctimer;
#if(debug)
                                    st.Start(); //计时开始
#endif
                                    for (int i = 0; i < globaldata.m_signalbuffer.Draw_Port.Count; i++)
                                    {
                                        if (globaldata.MethodRun_Statue == 4 || globaldata.MethodRun_Statue == 5)
                                      //  if (true)
                                        {
                                           
                                            if ((globaldata.m_hmibuffer.gcinfo.NowStartTime <= ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[0]).ctimer) && isstart == 0 && (NowTimeOld != globaldata.m_hmibuffer.gcinfo.NowStartTime))
                                            {
                                            
                                                if (CKVocAnalyzer.GlobalCKV.debugwork == 5)
                                                {
                                                    CKVocAnalyzer.GlobalCKV.debugwork = 4;
                                                    isstart = 2;
                                                    time = 0;
                                                    drbool = false;
                                                    globaldata.starttimer = globaldata.m_hmibuffer.gcinfo.NowStartTime;
                                                    NowTimeOld = globaldata.m_hmibuffer.gcinfo.NowStartTime;
                                                    CurveDisPlay.curdisp.cleardata();
                                                 
                                                
                                                }
                                                else
                                                {
                                                    isstart = 2;
                                               
                                                    CurveDisPlay.curdisp.SetAxisX((double)globaldata.m_dpbuffer.ShowList.showtime.alltime / 60.0);
                                                    time = 0;
                                                    drbool = false;
                                                    globaldata.starttimer = globaldata.m_hmibuffer.gcinfo.NowStartTime;
                                                    NowTimeOld = globaldata.m_hmibuffer.gcinfo.NowStartTime;
                                                    CurveDisPlay.curdisp.cleardata();
                                                
                                                   // Trace.WriteLine("周期开始"+globaldata.m_hmibuffer.gcinfo.NowStartTime.ToString(), "sys");
                                            
                                                }
                                                CKVocAnalyzer.GlobalCKV.dataFtime.FTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                listPoint.Clear();  //清除记录
                                                listRaw.Clear();


                                            }
                                        }

                                        //数据回填
                                        if (isstart == 0)  //方法结束，缓存原始数据
                                        {
                                            if (listRawTem.Count < 3000)
                                            {
                                                listRawTem.Add(new double[] { ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer, Math.Round((((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).cdata * 1000.0f), 6) });
                                            }
                                            else
                                            {
                                                listRawTem.Clear();//缓存3000点，大于3000，重新开始
                                            }

                                            //TCP数据回传
                                          
                                            lock (globaldata.m_signalbuffer.TCP_Port)
                                            {
                                                if(globaldata.m_signalbuffer.TCP_Port.Count>0)
                                                {
                                                   // Trace.WriteLine("TCP数据回传","sys");
                                                    List<double[]> tcpraw = new List<double[]>();
                                                    for (int tcpi = 0; tcpi < globaldata.m_signalbuffer.TCP_Port.Count;tcpi++ )
                                                    {
                                                        tcpraw.Add(new double[] { ((SignalBuffer.TCP_Channel)globaldata.m_signalbuffer.TCP_Port[tcpi]).dettimer, Math.Round(((SignalBuffer.TCP_Channel)globaldata.m_signalbuffer.TCP_Port[tcpi]).detdata1*1000.0f,6) });
                                                    }
                                                    if (tcpraw.Count > 0)
                                                    {
                                                        CurveDisPlay.curdisp.WriteTcp(tcpraw);
                                                    }
                                                }
                                                globaldata.m_signalbuffer.TCP_Port.Clear();
                                                
                                            }
                                           

                                        }
                                        if (isstart == 2 && listRawTem.Count > 0)  //回填数据
                                        {
                                            int rami = listRawTem.FindIndex(s => s[0] == globaldata.starttimer);
                                            if(rami>-1) //有需要回填数据
                                            {
                                                for (; rami < listRawTem.Count;rami++ )
                                                {
                                                    time += (((UInt32)listRawTem[rami][0] - globaldata.starttimer) / 1000.0f / 60.0f);

                                                    globaldata.starttimer = (UInt32)listRawTem[rami][0];
                                                    value = listRawTem[rami][1];
                                                    listPoint.Add(new double[] { Math.Round(time, 4), Math.Round(value, 6) });
                                                    listRaw.Add(new double[] { listRawTem[rami][0], Math.Round(value, 6) });

                                                }
                                            }
                                            listRawTem.Clear();
                                        }
                                     
                                        if (globaldata.starttimer <= ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer && (((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer - globaldata.starttimer) >0)
                                        {
                                           
                                            time += ((((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer - globaldata.starttimer) / 1000.0f / 60.0f);
                                            //time += 0.00083;
                                            globaldata.starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer;
                                            value = (((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).cdata * 1000.0f);

                                            if (time < 600)
                                            {
                                                listPoint.Add(new double[] { Math.Round(time, 4), Math.Round(value, 6) });
                                                listRaw.Add(new double[] {((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer, Math.Round(value, 6) });
                                               
                                           
                                               
                                            }


                                            drbool = false;
                                            //时间判断终点
                                          //  if ((globaldata.MethodRun_Statue == 4 || globaldata.MethodRun_Statue == 5))
                                            if (globaldata.m_hmibuffer.gcinfo.methodstatus <4 || globaldata.m_hmibuffer.gcinfo.methodstatus > 5)
                                           {
                                            
                                                if ((globaldata.m_hmibuffer.gcinfo.NowStartTime<=globaldata.m_hmibuffer.gcinfo.NowEndTime)&&(globaldata.m_hmibuffer.gcinfo.NowEndTime <= ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer)&&isstart==2)
                                                {
                                                  
                                                    drbool = true;
                                                 
                                                    isstart = 0;
                                                   // Trace.WriteLine("周期结束" + globaldata.m_hmibuffer.gcinfo.NowEndTime.ToString(), "sys");
                                                  
                                                    break;
                                                }
                                            }
                                          

                                        }
                                        else
                                            globaldata.starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Draw_Port[i]).ctimer;
                 
                                    }

                                    //读取数据完毕
                                    globaldata.m_signalbuffer.Draw_Port.Clear();
                                  

                                }
                            }
                        }
#if(debug)
                        st.Stop(); //计时终止
                        Trace.WriteLine("后处理更新时间：" + st.Elapsed.ToString(), "sys");
#endif
                        CurveDisPlay.curdisp.addDataRaw(listRaw); //记录原始数据
                            CurveDisPlay.curdisp.addPoint(listPoint, drbool);   //更新绘画区域
                        //绘制完，重新画图
                         if (drbool)
                        {
                            time = 0;
                            CurveDisPlay.curdisp.cleardata();

                        }
                            
                       

                        // Console.WriteLine(string.Format("【{0}】读取个数结束  {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), globaldata.m_signalbuffer.Draw_Port.Count));

                    }

                    if (globaldata.cancelflag)
                    {

                        globaldata.cancelflag = false;
                    }

                    //  Thread.Sleep(500);
                }

                //  Trace.WriteLine("绘图线程退出！","sys");
            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }
        }

        public void CKvocUpdataStart()
        {
            if (datamre != null)
            {
                datamre.Reset();
            }
           // t_DataSave = new Thread(Monitor_Data);
            t_DataSave = new Thread(Monitor_DataList);
            t_DataSave.IsBackground = true;
            t_DataSave.Start();
        }

        public void CKvocUpdataStop()
        {
            datamre.Set();
        }

    }
}
