using FLY.Thick.Blowing.Server.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FLY.Thick.Blowing.UI.Fix.Server
{
    public class PicHistory : INotifyPropertyChanged, Misc.ISaveToXml
    {
        /// <summary>
        /// 数据能保存的天数
        /// </summary>
        public int KeepDay { get; set; } = 180;

        /// <summary>
        /// Y轴比例
        /// </summary>
        public int YRangePercent { get; set; } = 3;
        /// <summary>
        /// 曲线类型
        /// </summary>
        public CHART_TYPE ChartType { get; set; } = CHART_TYPE.Column;

        /// <summary>
        /// 保存的根路径
        /// </summary>
        public string RootPath { get; set; } = @"D:\blowingdata\pic";

        /// <summary>
        /// 使能
        /// </summary>
        public bool Enable { get; set; } = false;

        /// <summary>
        /// 自动目标值
        /// </summary>
        public bool IsAutoTarget { get; set; } = true;

        /// <summary>
        /// 当前保存的数据天数
        /// </summary>
        public int CurrDays { get; private set; }

        double Target { get; set; } = double.NaN;
        double TolerancePercent { get; set; } = double.NaN;
        string Title { get; set; }



        /// <summary>
        /// 已经保存了数据的日期,
        /// </summary>
        private List<DateTime> dateInRootPath = new List<DateTime>();

        public PicHistory()
        {
            Load();
            InitKeepDay();
        }

        string CreateCurrPath(DateTime time, bool isWarning)
        {
            //创建路径
            DateTime dt = time;
            string dirpath;
            if (isWarning)
            {
                dirpath = RootPath + @"\iswarning\" + dt.ToString(@"yyyy\\MM\\dd");
            }
            else
            {
                dirpath = RootPath + @"\all\" + dt.ToString(@"yyyy\\MM\\dd");
            }
            Directory.CreateDirectory(dirpath);
            return dirpath + @"\" + dt.ToString("HH_mm_ss");
        }

        public async Task Add(Db_Profile dB_Profile, Lc_ScanData scanData, bool isWarning)
        {
            Target = dB_Profile.Target;
            TolerancePercent = dB_Profile.TolerancePercent;
            
            
            if (double.IsNaN(Target))
                return;
            if (double.IsNaN(TolerancePercent))
                return;

            Title = $"{dB_Profile.PName}-{dB_Profile.OrderNo}-{dB_Profile.Number}";
            string title = Title + " "+scanData.Time.ToString();
            //ALL
            string path = CreateCurrPath(scanData.Time, false);

            bool ret = false;
            App.Current.MainWindow.Dispatcher.Invoke(() =>
            {
                WindowSavePic w = new WindowSavePic();

                ret = w.Paint(scanData, title, IsAutoTarget, Target, TolerancePercent,
                    path + ".jpg",
                    YRangePercent, ChartType);
            });
            if (!ret)
                return;

            await Task.Factory.StartNew(() =>
            {
                try
                {
                    if (isWarning)
                    {
                        string path_iswarning = CreateCurrPath(scanData.Time, isWarning);
                        File.Copy(path + ".jpg", path_iswarning + ".jpg", true);
                    }

                    Keep();
                }
                catch
                {
                    return;
                }
            });
        }


        #region 自动删数据
        private void InitKeepDay()
        {
            dateInRootPath.Clear();
            if (!Directory.Exists(RootPath + @"\all"))
            {
                Directory.CreateDirectory(RootPath + @"\all");
                return;
            }

            DirectoryInfo mydir = new DirectoryInfo(RootPath + @"\all");
            //年
            Regex regex_year = new Regex(@"\d{4}");
            Regex regex_month = new Regex(@"\d{2}");
            Regex regex_day = new Regex(@"\d{2}");

            var fsil_year = from fsi in mydir.GetFileSystemInfos()
                            where (fsi.Attributes == FileAttributes.Directory) && (regex_year.IsMatch(fsi.Name))
                            select fsi;

            foreach (var fsi_year in fsil_year)
            {
                var fsil_month =
                    from fsi in ((DirectoryInfo)fsi_year).GetFileSystemInfos()
                    where (fsi.Attributes == FileAttributes.Directory) && (regex_month.IsMatch(fsi.Name))
                    select fsi;

                foreach (var fsi_month in fsil_month)
                {
                    var fsil_day =
                        from fsi in ((DirectoryInfo)fsi_month).GetFileSystemInfos()
                        where (fsi.Attributes == FileAttributes.Directory) && (regex_day.IsMatch(fsi.Name))
                        select fsi;

                    foreach (var fsi_day in fsil_day)
                    {

                        DateTime dt = new DateTime(
                            int.Parse(fsi_year.Name),
                            int.Parse(fsi_month.Name),
                            int.Parse(fsi_day.Name));

                        //if (DateTime.TryParse(fsi_year.Name.ToString() + "-" + fsi_month.Name.ToString() + "-" + fsi_day.Name.ToString(), out dt)) 
                        {
                            dateInRootPath.Add(dt);
                        }
                    }
                }
            }
            dateInRootPath.Sort(new Comparison<DateTime>(
                delegate (DateTime t1, DateTime t2)
                {
                    if (t1 > t2)
                        return 1;
                    else if (t1 == t2)
                        return 0;
                    else
                        return -1;
                }));
            CurrDays = dateInRootPath.Count;
            Keep();
        }
        private void Keep()
        {
            while (dateInRootPath.Count > KeepDay)
            {
                string dirpath = RootPath + @"\all\" + dateInRootPath.First().ToString(@"yyyy\\MM\\dd");
                Directory.Delete(dirpath, true);

                dirpath = RootPath + @"\iswarning\" + dateInRootPath.First().ToString(@"yyyy\\MM\\dd");
                Directory.Delete(dirpath, true);

                dateInRootPath.RemoveAt(0);
            }
            CurrDays = dateInRootPath.Count;
        }


        #endregion

        public string[] GetSavePropertyNames()
        {
            return new string[]{
                "KeepDay",
                "YRangePercent",
                "ChartType",
                "RootPath",
                "Enable"
            };
        }

        /// <summary>
        /// 加载历史数据
        /// </summary>
        /// <returns></returns>
        public bool Load()
        {
            return Misc.SaveToXmlHepler.Load("pichistory.xml", this);
        }
        /// <summary>
        /// 保存
        /// </summary>
        public void Save()
        {
            Misc.SaveToXmlHepler.Save("pichistory.xml", this);
        }
        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }
}