using Common;
using Common.vo.pb;
using MeterModelLibrary;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MeterPlugInLibrary
{
    public delegate void EventDataCollection(object o, DataCollectionArgs e);

    public class DataCollectionArgs
    {
        public string carno { get; set; }//车号
        public int weight { get; set; }//重量
        public int weightStatus { get; set; }//0稳定，1不稳定,2空磅
        public int parkStatus { get; set; }//红外对射 0未挡住，1:车头压线  2：车尾压线  3:两头压线; 记录在重量稳定后生成
        public int licType { get; set; }//0 抓拍 1 RFID
        public DateTime datetime { get; set; } //当前时间的距离1970.1.1.08:00时间的秒数

        public string vdioCarNos { get; set; }

        public string RfidNos { get; set; }
    }

    public class DataCollectionControl
    {
        public event EventDataCollection EventDataCollectionArgs;//定义事件
        private Thread CollectionThread;//采集线程
        private string strPntNo = "";//计量点编号
        private string strPntName = "";//计量点编号

        /// <summary>
        /// 开启数据采集线程
        /// </summary>
        public void Start(string strPntID, string strPntName)
        {
            PbCache.collect = new CollectModel();

            this.strPntNo = strPntID;
            this.strPntName = strPntName;
            CollectionThread = new Thread(new ThreadStart(WgtThread));
            CollectionThread.Start();
        }

        public void Stop()
        {
            if (CollectionThread != null)
            {
                CollectionThread.Abort();
                CollectionThread = null;
            }
        }

        /// <summary>
        /// 重量采集线程
        /// </summary>
        private void WgtThread()
        {

            //===========eason 2020 注释================
            int icount = 0, iOldWgt = 0, iWdCount = 0; //iWdCount稳定次数，这里判断为5次稳定即可
            MemoryTableDataSocket MemoClass = new MemoryTableDataSocket(PbCache.collect_no);//内存表

            //CarNoModfiy carNoModifyClass = new CarNoModfiy();//车号修正
            while (true)
            {
                try
                {
                    icount++;
                    Thread.Sleep(500);
                    DataCollectionArgs arg = new DataCollectionArgs();
                    //WriteThreadLog("数据采集线执行跟踪！");//2021年3月16日 杨秀东添加
                    JArray jArray = MemoClass.TrackTable(PbCache.collect_no);
                    if (jArray != null) //正常采集，若为null则重量采集线程中断了
                    {
                        //arg.carno = jArray[2].ToString();
                        arg.weight = Convert.ToInt32(jArray[3].ToString());
                        arg.weightStatus = Convert.ToInt32(jArray[4].ToString());
                        arg.parkStatus = Convert.ToInt32(jArray[5].ToString());
                        arg.datetime = Convert.ToDateTime(jArray[6].ToString().Replace("T", " ").Replace("Z", ""));
                        arg.licType = Convert.ToInt32(jArray[7].ToString());

                        if (arg.licType == 0) //摄像头的数据
                        {
                            arg.carno = jArray[2].ToString();
                        }
                        else
                        {
                            arg.carno = jArray[8].ToString();
                        }

                        arg.vdioCarNos = arg.carno; //jArray[8].ToString();
                        arg.RfidNos = jArray[9].ToString();

                        #region 判稳代码
                        /*
                        if (PbCache.range != null) 
                        {
                            if (PbCache.range.stableDiff != null)
                            {
                                if (Math.Abs(arg.weight - iOldWgt) > PbCache.range.stableDiff.Value)
                                {
                                    iOldWgt = arg.weight;
                                    iWdCount = 0;
                                }
                                else
                                {
                                    arg.weight = iOldWgt;
                                    iWdCount++;
                                }
                            }
                        }
                        if (arg.weightStatus == 2)
                        {
                            arg.weightStatus = 0; //重量稳定
                            iWdCount = 0;
                        }

                        //0.1秒采集一次，一共采集5次，若稳定则认为重量稳定
                        if (iWdCount >= 10) 
                        {
                            arg.weightStatus = 0; //重量稳定
                            iWdCount = 10;
                        }
                        //*/
                        #endregion
                    }

                    //每隔0.5秒调用一次写入到界面数据
                    //if (icount > 4)
                    {
                        icount = 0;
                        EventDataCollectionArgs(this, arg);
                    }
                }
                catch (Exception exp)
                {
                    WriteThreadLog("数据采集线程异常！" + exp.Message);
                }
            }
        }
        public void WriteLog(string str)
        {
            try
            {
                string m_szRunPath;
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\数据采集_" + strDate + ".log", true);

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

                tw.Close();
            }
            catch (Exception exp)
            {

            }
        }

        /// <summary>
        /// 写线程日志
        /// </summary>
        /// <param name="str"></param>
        public void WriteThreadLog(string str)
        {
            try
            {
                string m_szRunPath;
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\数据采集线程_" + strDate + ".log", true);

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

                tw.Close();
            }
            catch (Exception exp)
            {

            }
        }

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

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

                tw.Close();
            }
            catch (Exception exp)
            {

            }
        }
        public void WriteLogStatus(string str)
        {
            try
            {
                string m_szRunPath;
                m_szRunPath = System.Environment.CurrentDirectory;
                if (System.IO.Directory.Exists(m_szRunPath + "\\log") == false)
                {
                    System.IO.Directory.CreateDirectory(m_szRunPath + "\\log");
                }
                string strDate = System.DateTime.Now.ToString("yyyyMMdd");
                string strPathFile = m_szRunPath + "\\log\\" + strDate;
                if (!Directory.Exists(strPathFile))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(strPathFile);
                }
                System.IO.TextWriter tw = new System.IO.StreamWriter(strPathFile + "\\重量稳定判断_" + strDate + ".log", true);

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

                tw.Close();
            }
            catch (Exception exp)
            {

            }
        }

    }
}
