using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using CRVM.Entity;

namespace CRVM.CIDExcuter
{
    public class IViewHelper
    {

        private List<List<float>> _originDataList;
        public List<List<float>> originDataList
        {
            get { return _originDataList; }
        }

        private List<List<double>> _originSpeedList;
        public List<List<double>> originSpeedList
        {
            get { return _originSpeedList; }
        }

        private List<double> _originDistanceList;
        public List<double> originDistanceList
        {
            get { return _originDistanceList; }
        }


        private double[,] _energyData;
        public double[,] energyData
        {
            get { return _energyData; }
        }

        private Dictionary<string, int> indColmun;

        private int _signalLengthOrigin;
        public int signalLengthOrigin
        {
            get { return _signalLengthOrigin; }
        }

        private int _signalLengthEnergy;
        public int signalLengthEnergy
        {
            get { return _signalLengthEnergy; }
        }

        public IViewHelper(string path)
        {
            ReadFile(path);
        }

        public void ReadFile(string path)
        {
            if (path.Contains(".txt"))
            {
                if (path.Contains("original"))
                {
                    readOk = readTxtOrigData(path);
                }
                else
                {
                    readOk = readEnergyData(path);
                }
            }
            else if (path.Contains(".dat"))
            {
                readOk = readOrigData(path);
            }
            else
            {
                readOk = false;
            }
        }

        public int IndexChannel(string keys)
        {
            if (indColmun.ContainsKey(keys))
                return indColmun[keys];
            else
                return -1;
        }

        private bool readOk = true;
        private string[] _channel;

        public bool FileOk
        {
            get { return readOk; }
        }

        private bool readEnergyData(string path)
        {
            //Stream myStream = new FileStream(_path, FileMode.Open);
            FileStream file = File.OpenRead(path);
            StreamReader myread = new StreamReader(file);

            int colum = 0;
            string tempstr = myread.ReadLine();
            if (tempstr.Substring(tempstr.Length - 4, 4) == "能量数据")
            {
                string content1 = tempstr.Substring(0, tempstr.Length - 4);
                string[] split1;
                split1 = content1.Split('，');
                _channel = new string[split1.GetLength(0)];
                Array.Copy(split1, 0, _channel, 0, split1.GetLength(0));
                for (int i = 0; i < _channel.Length; i++)
                {
                    string str = (i + 1) + "#机架";
                    if (_channel[i] == str)
                    {
                        colum += 8;
                    }
                }
                string XXX = myread.ReadLine();
                string[] x1 = new string[1];
                string[] xx1 = new string[1];
                string[] xx2 = new string[1];
                x1 = XXX.Split('；');
                xx1 = x1[0].Split('：');
                xx2 = x1[1].Split('：');
                myread.ReadLine();
                if (SysParam.Instance.reSampleFre == 0 || SysParam.Instance.reSamplePoint == 0)
                {
                    SysParam.Instance.reSamplePoint = Convert.ToInt32(xx1[1]);
                    SysParam.Instance.reSampleFre = Convert.ToInt32(xx2[1]);
                }
                //SysParam.Instance.time_1 = Convert.ToSingle(xx1[1]) / Convert.ToSingle(xx2[1]);
                string line = myread.ReadToEnd();
                string[] line1 = line.Replace("\r\n", "@").Split('@');
                _signalLengthEnergy = line1.Length - 1;
                _energyData = new double[colum, _signalLengthEnergy];
                string[] line2;
                for (int i = 0; i < _signalLengthEnergy; i++)
                {
                    line2 = line1[i].Replace("\t", "@").Split('@');
                    for (int j = 0; j < colum; j++)
                    {
                        _energyData[j, i] = Convert.ToDouble(line2[j]);
                    }
                }
            }
            else
            {
                myread.Close();
                file.Close();
                return false;
            }
            myread.Close();
            file.Close();
            return true;
        }

        private bool readTxtOrigData(string path)
        {
            FileStream file = File.OpenRead(path);
            StreamReader myread = new StreamReader(file);

            string tempStr = myread.ReadLine();
            try
            {
                if (tempStr == "原始数据")
                {
                    tempStr = myread.ReadLine();
                    string[] split1;
                    split1 = tempStr.Split('\t');
                    string[] channel = new string[split1.Length - 1];
                    Array.Copy(split1, 0, channel, 0, split1.GetLength(0) - 1);
                    indColmun = new Dictionary<string, int>();
                    for (int i = 0; i < channel.Length; i++)
                    {
                        indColmun.Add(channel[i], i);
                    }
                    SysParam.Instance.reSampleFre = Convert.ToInt32(myread.ReadLine());
                    SysParam.Instance.reSamplePoint = Convert.ToInt32(myread.ReadLine());
                    _originDataList = new List<List<float>>();////存放通道数据
                    for (int i = 0; i < channel.Length; i++)
                    {
                        List<float> listm = new List<float>();
                        _originDataList.Add(listm);
                    }

                    _originSpeedList = new List<List<double>>();//存放速度和轧制距离 
                    for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                    {
                        List<double> listm = new List<double>();
                        _originSpeedList.Add(listm);
                    }

                    _originDistanceList = new List<double>();

                    while (!myread.EndOfStream)
                    {
                        for (int i = 0; i < SysParam.Instance.samplePoint; i++)
                        {
                            string line = myread.ReadLine();
                            string[] line1 = line.Split('\t');
                            for (int j = 0; j < channel.Length; j++)
                            {
                                _originDataList[j].Add(Convert.ToSingle(line1[j]));
                            }
                        }
                        string disSpeed = myread.ReadLine();
                        string[] disspeed = disSpeed.Split('\t');
                        for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)//速度信息
                        {
                            _originSpeedList[i].Add(Convert.ToDouble(disspeed[i]));
                        }
                        _originDistanceList.Add(Convert.ToDouble(disspeed[5]));
                    }

                    _signalLengthOrigin = _originDataList[0].Count;

                    myread.Close();
                    file.Close();
                    return true;
                }
                else
                {
                    myread.Close();
                    file.Close();
                    return false;
                }

            }
            catch (Exception)
            {
                myread.Close();
                file.Close();
                return false;
            }

        }

        private bool readOrigData(string path)
        {
            //DevelopLog.DeBug.WriteLogFile("开始读文件","开始");
            try
            {
                Stream myStream = new FileStream(path, FileMode.Open);
                _signalLengthOrigin = 0;
                BinaryReader MyReader = new BinaryReader(myStream, Encoding.UTF8);
                string tempStr = MyReader.ReadString();
                if (tempStr == "原始数据")
                {
                    //读取头
                    tempStr = MyReader.ReadString();
                    indColmun = new Dictionary<string, int>();
                    int channelCount = 0;
                    while (tempStr != "/r/n")
                    {
                        indColmun.Add(tempStr, channelCount);
                        tempStr = MyReader.ReadString();
                        channelCount += 1;
                    }
                    SysParam.Instance.reSampleFre = Convert.ToInt32(MyReader.ReadSingle());
                    SysParam.Instance.reSamplePoint = Convert.ToInt32(MyReader.ReadSingle());
                    //建立数据结构
                    _originDataList = new List<List<float>>();
                    for (int i = 0; i < channelCount; i++)
                    {
                        //定义数据长度，避免自动扩充时溢出
                        List<float> listm = new List<float>();// 30 * 60 * SysParam.Instance.reSampleFre);
                        _originDataList.Add(listm);
                    }
                    _originSpeedList = new List<List<double>>();//存放速度和轧制距离 
                    for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                    {
                        List<double> listm = new List<double>();
                        _originSpeedList.Add(listm);
                    }
                    _originDistanceList = new List<double>();

                    //开始读取数据
                    float signaldata = 0;
                    signaldata = MyReader.ReadSingle();
                    SysParam.Instance.OrigDataNum = 0;
                    try
                    {
                        while (signaldata == Convert.ToSingle("1111"))
                        {
                            for (int i = 0; i < SysParam.Instance.reSamplePoint; i++)
                            {
                                for (int k = 0; k < channelCount; k++)
                                {
                                    _originDataList[k].Add(MyReader.ReadSingle());
                                }
                            }
                            for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                            {
                                _originSpeedList[i].Add(MyReader.ReadSingle());
                            }
                            _originDistanceList.Add(MyReader.ReadSingle());
                            signaldata = MyReader.ReadSingle();
                            SysParam.Instance.OrigDataNum++;
                            _signalLengthOrigin = SysParam.Instance.OrigDataNum * SysParam.Instance.reSamplePoint;
                        }
                    }
                    catch (Exception)
                    {
                        for (int k = 0; k < channelCount; k++)////去掉读取不正确的那帧不完整的数据，将前面正确读取的部分保留
                        {
                            for (int i = SysParam.Instance.OrigDataNum * SysParam.Instance.reSamplePoint; i < _originDataList[k].Count; i++)
                            {
                                _originDataList[k].RemoveAt(i);
                            }
                        }
                        for (int i = 0; i < SysParam.Instance.SpeedChannelCount; i++)
                        {
                            for (int j = SysParam.Instance.OrigDataNum; j < _originSpeedList[i].Count; j++)
                            {
                                _originSpeedList[i].RemoveAt(j);
                            }
                        }
                        for (int i = SysParam.Instance.OrigDataNum; i < _originDistanceList.Count; i++)
                        {
                            _originDistanceList.RemoveAt(i);
                        }
                    }

                    _signalLengthOrigin = _originDataList[0].Count;
                    MyReader.Close();
                    myStream.Close();
                    return true;

                }
                MyReader.Close();
                myStream.Close();
                return false;

            }
            catch (Exception)
            {
                return false;
            }
        }

        public string selectAlarmFile(string filePath)
        {
            //根据文件的时间选择对应时间段的报警配置文件
            if (!System.IO.Directory.Exists(SysParam.Instance.appPath + "//AlarmConfig//"))
            {
                //使用当前报警配置文件
                return SysParam.Instance.appPath + @"\AppSetting.config";
            }
            FileInfo[] fileinfos = new DirectoryInfo(SysParam.Instance.appPath + @"\AlarmConfig\").GetFiles();
            FileInfo selectFile = null;

            DateTime myfileTime = new FileInfo(filePath).LastWriteTime;
            DateTime selectFileTime = DateTime.Now;

            foreach (FileInfo thisfileinfo in fileinfos)
            {
                DateTime eachfiletime = thisfileinfo.LastWriteTime;
                if (eachfiletime > myfileTime)
                {
                    if (eachfiletime < selectFileTime)
                    {
                        selectFileTime = eachfiletime;
                        selectFile = thisfileinfo;
                    }
                }
            }
            if (selectFile != null)
            {
                return selectFile.FullName;
            }
            else
            {
                //使用当前报警配置文件
                return SysParam.Instance.appPath + @"\AppSetting.config";
            }
        }
    }

}

