using Aspose.Cells;
using EWS.FocalMechanism.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace Txgy.Microseismic.BaseLib
{
    public static class PublicConfig
    {
        /// <summary>
        /// 设备整体灵敏度
        /// </summary>
        public const double KW = 833760427.0;
        /// <summary>
        /// 波形截取长度(点数)
        /// </summary>
        public const int WaveCutLen = 1000;
        public static string timeFormatStr = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFF";
        public static ProjectConfigModel ProjectConfig { get; set; }
        public static FmGrid fmGrid { get; set; }
        public static int StationCount;
        public static void ReadConfig()
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = timeFormatStr;
            IFormatProvider ifp = new CultureInfo("zh-CN", true);
            string jsonText;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\resources\\config.json"))
            {
                jsonText = sr.ReadToEnd();
            }
            //string jsonText=new System.IO.StreamReader("config.json").ReadToEnd();

            ProjectConfig = JsonConvert.DeserializeObject<ProjectConfigModel>(jsonText);
            SetConfig();
            ProjectConfig.StationDic = CreateStationFromCSV(AppDomain.CurrentDomain.BaseDirectory + "\\resources\\" + ProjectConfig.StationFile);
            StationCount = ProjectConfig.StationDic.Count;

            fmGrid = CreateFMGrid(ProjectConfig);


            //string[] sds= ProjectConfig.Stations.Split(',');
            //ProjectConfig.StationDic = new Dictionary<string, StationModel>();
            //foreach (var item in sds)
            //{
            //    StationModel sm=new StationModel();
            //    sm.Name = item.ToString();
            //    ProjectConfig.StationDic.Add(item,sm);
            //}
            //foreach (var item in ProjectConfig.StationDic)
            //{
            //    Console.WriteLine(item.Key);
            //}

            //Console.WriteLine(ProjectConfig.Stations);
            //Console.WriteLine(ProjectConfig.WorkArea.WorkAreaName);
            //Console.WriteLine(ProjectConfig.StartTime.ToString());
            //Console.WriteLine(ProjectConfig.MseedFilePath);
        }
        public static void SetConfig()
        {
            if (!Directory.Exists(ProjectConfig.MseedFilePath))
            {
                Directory.CreateDirectory(ProjectConfig.MseedFilePath);
            }

            if (File.Exists(ProjectConfig.TxtFilePath))
            {
                // Console.WriteLine(File.GetAttributes(ProjectConfig.CacheFilePath).ToString());
                File.SetAttributes(ProjectConfig.TxtFilePath, FileAttributes.Hidden);
            }
            else
            {
                Directory.CreateDirectory(ProjectConfig.TxtFilePath);
                File.SetAttributes(ProjectConfig.TxtFilePath, FileAttributes.Hidden);
            }
        }
        public static void SaveConfig()
        {

        }
        public static Dictionary<string, StationModel> CreateStationFromCSV(string fn)
        {
            Dictionary<string, StationModel> stations = new Dictionary<string, StationModel>();
            Aspose.Cells.TxtLoadOptions lo = new TxtLoadOptions();
            lo.Encoding = Encoding.Default;//设置编码方式
            Workbook workbook = new Workbook(fn, lo);

            //配置读取文件的类型（CSV）
            workbook.FileFormat = FileFormatType.CSV;//可在此配置Excel文件类型
            Worksheet worksheet = workbook.Worksheets[0];//默认第一个Sheet页

            Cells cells = worksheet.Cells;

            //读取到DataTable中            
            DataTable dt = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1, true);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                StationModel model = new StationModel();
                model.Name = row[1].ToString();
                model.E = double.Parse(row[2].ToString());
                model.N = double.Parse(row[3].ToString());
                model.Z = double.Parse(row[4].ToString());
                model.Sens = double.Parse(row[5].ToString());
                model.BeginUseTime = DateTime.Parse(row[6].ToString());
                model.StopUseTime = DateTime.Parse(row[7].ToString());
                stations.Add(model.Name, model);
            }
            //释放资源         
            workbook = null;
            worksheet = null;
            return stations;
        }

        public static FmGrid CreateFMGrid(ProjectConfigModel projectConfigModel)
        {
            FmGrid fg = new FmGrid();
            fg.xmax = projectConfigModel.WorkArea.EMax - projectConfigModel.WorkArea.EMin;
            fg.ymax = projectConfigModel.WorkArea.NMax - projectConfigModel.WorkArea.NMin;
            fg.xmin = 0;
            fg.ymin = 0;
            fg.StationCount = projectConfigModel.StationDic.Count;
            fg.StationList = new List<FMStation>();
            int sc = 0;
            foreach (var item in projectConfigModel.StationDic)
            {
                fg.StationList.Add(new FMStation(sc, item.Key, item.Value.E - projectConfigModel.WorkArea.EMin,
                    item.Value.N - projectConfigModel.WorkArea.NMin));
                sc++;
            }
            fg.initZeroCenter();
            fg.computeDistance();
            return fg;
        }

        public static void MSeed2Asc(string filePath, string savePath)
        {
            using (Process compiler = new Process())
            {
                compiler.StartInfo.FileName = "mseed2ascii.exe";
                compiler.StartInfo.Arguments = filePath + " -o " + savePath;
                compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                compiler.Start();
                compiler.WaitForExit();
            }
        }
        public static List<WaveDataModel> CreateWaveModelFromText(string fn)
        {
            List<WaveDataModel> waveDataModelRows = new List<WaveDataModel>();
            string[] allRows;
            using (StreamReader sr = new StreamReader(fn))
            {
                allRows = sr.ReadToEnd().Trim().Split(new char[] { '\n' });
            }
            WaveHeader wh = new WaveHeader(allRows[0]);
            int rk = 0;
            string curRow = allRows[0];
            while (rk < allRows.Length)
            {
                curRow = allRows[rk];
                if (curRow.Contains("TIME"))
                {
                    WaveDataModel waveModel = new WaveDataModel();
                    waveModel.waveHeader = new WaveHeader(curRow);
                    waveModel.Points = new List<int>();
                    rk++;
                    int nk = 0;
                    for (int i = 0; i < wh.Samples; i++)
                    {
                        if ((rk + i) >= allRows.Length)
                        {
                            break;
                        }
                        if (allRows[rk + i].Contains("TIME"))
                        {
                            rk = rk + i;
                            break;
                        }
                        int cd = int.Parse(allRows[rk + i].Trim());
                        waveModel.Points.Add(cd);
                        nk++;
                        //rk++;
                    }
                    int cz = wh.Samples - waveModel.Points.Count;
                    if (cz > 0)
                    {
                        for (int jk = 0; jk < cz; jk++)
                        {
                            waveModel.Points.Add(waveModel.Points.Count - 1);
                        }
                        waveDataModelRows.Add(waveModel);
                    }
                    else
                    {
                        waveDataModelRows.Add(waveModel);
                        rk += nk;
                    }

                }
                else
                {
                    rk++;
                }

            }
            return waveDataModelRows;
        }
        public static int GetWaveMaxAmpIndex(WaveDataModel wdm, DateTime eventTime)
        {
            int startPoint = (int)(eventTime - wdm.waveHeader.StartTime).TotalMilliseconds / 2;
            int readLen = WaveCutLen;
            if (startPoint + WaveCutLen > wdm.Points.Count)
            {
                readLen = wdm.Points.Count - startPoint;
            }
            int[] tmpArr = new int[readLen];
            Array.ConstrainedCopy(wdm.Points.ToArray(), startPoint, tmpArr, 0, readLen);
            int maxValue = 0;
            int maxIndex = 0;
            for (int t = 0; t < tmpArr.Length; t++)
            {
                if (Math.Abs(tmpArr[t]) > maxValue)
                {
                    maxValue = Math.Abs(tmpArr[t]);
                    maxIndex = t;
                }
            }
            return maxIndex + startPoint;
        }

        public static double PointsAngleTool(PointF p1, PointF p2)
        {
            //int positionInfo = 0;
            double angleOfLine = Math.Atan2((p2.Y - p1.Y), (p2.X - p1.X)) * 180 / Math.PI;//计算两点的正切值并获取角度
            //if (angleOfLine > -45 && angleOfLine < 45)//右
            //{
            //    positionInfo = 1;
            //}
            //else if (angleOfLine > 135 && angleOfLine < -135)//左
            //{
            //    positionInfo = 2;
            //}
            //else if (angleOfLine > 45 && angleOfLine < 135)//上
            //{
            //    positionInfo = 3;
            //}
            //else if (angleOfLine > -135 && angleOfLine < -45)//下
            //{
            //    positionInfo = 4;
            //}
            return angleOfLine;
        }

    }
}
