using System;
using System.Collections.Generic;
using System.IO;
using CRVM.Entity;
using System.Threading;
using System.Threading.Tasks;
using System.Data;
using CRVM.Utility;

namespace CRVM.SIDExcuter
{
    public class IDataHelper
    {
        protected Machine mac;
        protected StreamWriter fileTxtOriginalWriter, fileTxtEnergyWriter;
        protected BinaryWriter fileBitOriginalWriter;
        private string saveFileName;
        private string savePathOrigin;
        private string savePathEnergy;
        private string savePathAlarm;

        public IDataHelper(Machine mac)
        {
            this.mac = mac;
        }
       
        //创建文件
        public void CreateFileHead()
        {
            string temppath = SysParam.Instance.savePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
            savePathAlarm = temppath + "AlarmInfo" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            saveFileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            if (!Directory.Exists(temppath))
            {
                Directory.CreateDirectory(temppath + "original data\\");
                Directory.CreateDirectory(temppath + "energy data\\");
            }
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  CreateFileHead  0");
            if (SysParam.Instance.checkTXT)
            {
                savePathOrigin = temppath + "original data\\" + saveFileName + ".txt";
                fileTxtOriginalWriter = new StreamWriter(new FileStream(savePathOrigin, FileMode.OpenOrCreate));

                fileTxtOriginalWriter.WriteLine("原始数据");
                for (int i = 0; i < SysParam.Instance.channelCount; i++)
                {
                    fileTxtOriginalWriter.Write((i + 1) + "#机架振动" + "\t");
                }
                fileTxtOriginalWriter.WriteLine();
                fileTxtOriginalWriter.WriteLine(SysParam.Instance.sampleFre);
                fileTxtOriginalWriter.WriteLine(SysParam.Instance.samplePoint);
            }
            else if (SysParam.Instance.checkBIT)
            {
                savePathOrigin = temppath + "original data\\" + saveFileName + ".dat";
                fileBitOriginalWriter = new BinaryWriter(new FileStream(savePathOrigin, FileMode.OpenOrCreate));

                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  CreateFileHead  1");
                fileBitOriginalWriter.Write("原始数据");
                for (int i = 0; i < SysParam.Instance.channelCount; i++)
                {
                    fileBitOriginalWriter.Write((i + 1) + "#机架振动");
                }
                fileBitOriginalWriter.Write("/r/n");
                fileBitOriginalWriter.Write(Convert.ToSingle(SysParam.Instance.sampleFre));
                fileBitOriginalWriter.Write(Convert.ToSingle(SysParam.Instance.samplePoint));
            }
            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  CreateFileHead  2");
            savePathEnergy = temppath + "energy data\\" + saveFileName + ".txt";
            fileTxtEnergyWriter = new StreamWriter(new FileStream(savePathEnergy, FileMode.OpenOrCreate));

            //能量数据
            string tempStr = "";
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                tempStr = tempStr + (i + 1) + "#机架，";
            }
            tempStr = tempStr.Substring(0, tempStr.Length - 1) + "能量数据\r\n";

            tempStr = tempStr + "采样点数：" + SysParam.Instance.samplePoint + "；采样频率（Hz)：" + SysParam.Instance.sampleFre + "\r\n";

            int istandno = 0;
            for (int i = 0; i < SysParam.Instance.channelCount; i++)
            {
                istandno++;
                tempStr = tempStr + istandno + "#机架轧制速度" + "\t" + istandno + "#机架全局" + "\t" + istandno + "#机架低频" + "\t" + istandno + "#机架中频" + "\t" +
                    istandno + "#机架高频" + "\t" + istandno + "#机架低频报警值" + "\t" + istandno + "#机架中频报警值" + "\t" + istandno + "#机架高频报警值" + "\t";
            }
            fileTxtEnergyWriter.WriteLine(tempStr);

            Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  CreateFileHead  3");
            SysParam.Instance.fileCreated = true;
        }
        
        //采集数据写入文件
        public virtual void writeNew(int dataCount)
        {
            //Console.WriteLine(DateTime.Now.ToString("HH:mm:ss fff") + "  " + Thread.CurrentThread.ManagedThreadId + "  " + Thread.CurrentThread.IsThreadPoolThread);
            //原始数据
            //int dataCount = data.GetLength(1);
            if (SysParam.Instance.checkBIT)
            {
                fileBitOriginalWriter.Write(Convert.ToSingle(1111));
                for (int i = 0; i < dataCount; i++)
                {
                    for (int k = 0; k < SysParam.Instance.channelCount; k++)
                    {
                        fileBitOriginalWriter.Write(Convert.ToSingle(mac.Stand[k].vib[i]));
                    }
                }
                for (int k = 0; k < SysParam.Instance.SpeedChannelCount; k++)
                {
                    fileBitOriginalWriter.Write(Convert.ToSingle(mac.Stand[k].speed));
                }
                fileBitOriginalWriter.Write(Convert.ToSingle(mac.stripLength));

            }
            else if (SysParam.Instance.checkTXT)
            {
                for (int i = 0; i < dataCount; i++)
                {
                    for (int k = 0; k < SysParam.Instance.channelCount; k++)
                    {
                        fileTxtOriginalWriter.Write((mac.Stand[k].vib[i]).ToString("e6") + "\t");
                    }
                    fileTxtOriginalWriter.WriteLine(); //new line of data (start next scan);
                }
                for (int k = 0; k < 5; k++)
                {
                    fileTxtOriginalWriter.Write(mac.Stand[k].speed.ToString("e6") + "\t");
                }
                fileTxtOriginalWriter.WriteLine(mac.stripLength.ToString("e6"));
            }

            for (int k = 0; k < SysParam.Instance.channelCount; k++)
            {
                fileTxtEnergyWriter.Write(mac.Stand[k].speed.ToString("e6") + "\t" + mac.Stand[k].energy_All.ToString("e6") + "\t" + mac.Stand[k].energy_L.ToString("e6") + "\t" +
                         mac.Stand[k].energy_M.ToString("e6") + "\t" + mac.Stand[k].energy_H.ToString("e6") + "\t" + mac.Stand[k].alarm_L_Value_ck.ToString("e6") + "\t" +
                         mac.Stand[k].alarm_M_Value_ck.ToString("e6") + "\t" + mac.Stand[k].alarm_H_Value_ck.ToString("e6") + "\t");
            }
            fileTxtEnergyWriter.WriteLine();


        }

        /// <summary>
        /// 文件写入关闭，写报警日志并更新数据库
        /// </summary>
        /// <param name="endFlag">文件结束标志：0=超时，1=剪切，2=手动关闭</param>
        /// <param name="alarmInfo">写报警日志所需报警信息</param>
        /// <param name="cutLength">钢卷剪切长度</param>
        public virtual void CloseFile(int endFlag, List<string> alarmInfo, int cutLength)
        {
            //关闭文件流
            if (SysParam.Instance.fileCreated)////连续执行两次closefile函数会造成不能向已关闭的文件中写
            {
                if (SysParam.Instance.checkTXT)
                {
                    fileTxtOriginalWriter.Close();
                }
                else if (SysParam.Instance.checkBIT)
                {
                    fileBitOriginalWriter.Write(Convert.ToSingle(111111111));
                    fileBitOriginalWriter.Close();
                }
                fileTxtEnergyWriter.Close();
            }
            SysParam.Instance.fileCreated = false;
            string[] tempAlarmInfo = alarmInfo.ToArray();

            DevelopLog.DeBug.WriteLogFile("closefile:", mac.stripLength.ToString());

            new Task(() => WriteAlarmInfo(endFlag, tempAlarmInfo, cutLength, savePathOrigin, savePathEnergy)).Start();
        }

        private void WriteAlarmInfo(int endFlag, string[] alarmInfo, int cutLength, string savePathOrigin, string savePathEnergy)
        {
            int alarmstate = 0;//无报警
            //写报警日志
            if (alarmInfo.Length > 0)
            {
                alarmstate = 1;//有报警
                string alarmlog = "";
                for (int i = 0; i < alarmInfo.Length; i++)
                {
                    alarmlog = alarmlog + alarmInfo[i] + Environment.NewLine;
                }
                //结束时再空两行以区分不同钢卷
                alarmlog = alarmlog + Environment.NewLine + Environment.NewLine;
                File.AppendAllText(savePathAlarm, alarmlog);
            }

            //数据库写入钢卷文件信息
            DbHelper.GetInstance("").AddNewCoilInfo(alarmstate, endFlag, savePathOrigin, savePathEnergy, cutLength.ToString());
            //数据库写入报警信息
            if (alarmstate == 1)
            {
                AlarmInfoInsertDb();
            }
        }

        private void AlarmInfoInsertDb()
        {
            //报警信息合并
            List<int> start = new List<int>();
            List<int> end = new List<int>();
            List<double> value = new List<double>();
            List<int> standNo = new List<int>();
            List<int> alarmType = new List<int>();
            for (int k = 0; k < SysParam.Instance.SpeedChannelCount; k++)
            {
                for (int i = 0; i < mac.Stand[k].indexLow; i++)
                {
                    start.Add(mac.Stand[k].alarmLowInfo[i].startPos);
                    end.Add(mac.Stand[k].alarmLowInfo[i].endPos);
                    value.Add(mac.Stand[k].alarmLowInfo[i].value);
                    standNo.Add(k);
                    alarmType.Add(0);
                }
                mac.Stand[k].indexLow = 0;
                mac.Stand[k].alarmLowInfo.Clear();
                for (int i = 0; i < mac.Stand[k].indexMid; i++)
                {
                    start.Add(mac.Stand[k].alarmMidInfo[i].startPos);
                    end.Add(mac.Stand[k].alarmMidInfo[i].endPos);
                    value.Add(mac.Stand[k].alarmMidInfo[i].value);
                    standNo.Add(k);
                    alarmType.Add(1);
                }
                mac.Stand[k].indexMid = 0;
                mac.Stand[k].alarmMidInfo.Clear();
                for (int i = 0; i < mac.Stand[k].indexHigh; i++)
                {
                    start.Add(mac.Stand[k].alarmHighInfo[i].startPos);
                    end.Add(mac.Stand[k].alarmHighInfo[i].endPos);
                    value.Add(mac.Stand[k].alarmHighInfo[i].value);
                    standNo.Add(k);
                    alarmType.Add(2);
                }
                mac.Stand[k].indexHigh = 0;
                mac.Stand[k].alarmHighInfo.Clear();

            }

            DbHelper.GetInstance("").InsertAlarmInfo(start.ToArray(), end.ToArray(), standNo.ToArray(), alarmType.ToArray(), value.ToArray());
        }

    }
}
