using LiveCharts;
using LiveCharts.Configurations;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Service.WebSocket;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Windows
{
    /// <summary>
    /// 历史曲线
    /// </summary>
    public partial class HistoryDataWindow : Window
    {
        private string lineName;
        public string LineName { get => lineName; set { lineName = value; _LSLine.Title = value; } }
        public string LineTag { get; set; }
        public string UniformCode { get; set; }
        public double Multiplier { get; set; } = 1;
        public string ThingType { get; set; }
        public string ThingId { get; set; }
        private double startTime;
        public double StartTime { get => startTime; private set { startTime = value; _TBStart.Text = DateTime.Now.AddHours(-value).ToString("yyyy-MM-dd HH:mm:ss"); } }

        /// <summary>
        /// 有功设定数据（历史）
        /// </summary>
        private ChartValues<TsData> _CVLine { get; set; } = new ChartValues<TsData>();
        /// <summary>
        /// 数据路径
        /// </summary>
        private string _Url;
        private WEBHelper _WEBHelper;
        private UrlManager _UrlManager;
        private List<TsData> _CurrentDatas;

        private int _Interval = 5;// 快照间隔
        public HistoryDataWindow(WEBHelper web, UrlManager um)
        {
            InitializeComponent();
            _WEBHelper = web;
            _TBStart.Text = DateTime.Now.AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss");
            _TBEnd.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _LSLine.Values = _CVLine;
            _LSLine.Configuration = Mappers.Xy<TsData>().X(d => d == null ? 0 : d.Ts).Y(d => d == null ? 0 : Math.Round(d.Value, 2));
            _ChartAxisX.LabelFormatter = x => TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddMilliseconds(x).ToShortTimeString();
            _UrlManager = um;
            _Url = um.DataServicePath;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            switch (((Control)sender).Tag)
            {
                case "output":
                    Output();
                    break;
                case "search":
                    Search();
                    break;
                default: return;
            }
        }

        private void Search()
        {

            bool b1 = DateTime.TryParse(_TBStart.Text, out DateTime ds);
            bool b2 = DateTime.TryParse(_TBEnd.Text, out DateTime de);
            if (!b1 || !b2)
            {
                MessageWindow.ShowMessage("时间格式错误！");
                return;
            }
            Task.Run(toSearchData);



            void toSearchData()
            {
                try
                {
                    var dts = ds.GetTimeSpan();
                    var dte = de.GetTimeSpan();

                    var url = GetSearchUrl(dts, dte);
                    List<TsData> vs = null;
                    if (string.IsNullOrWhiteSpace(url)) return;
                    vs = _WEBHelper.HttpGetJSON<List<TsData>>(url);
                    if (Multiplier != 1)
                    {
                        foreach (var v in vs)
                        {
                            v.Value = v.Value * Multiplier;
                        }
                    }
                    _CurrentDatas = vs;
                    Dispatcher.Invoke(() =>
                    {
                        _CVLine.Clear();
                        _CVLine.AddRange(vs);
                    });

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        private string GetSearchUrl(long dts, long dte)
        {
            if (_Interval > 0)
            {
                var url = $"{_Url}/ts/history/snap?interval={_Interval * 60}";

                if (UniformCode != null)
                {
                    return $"{url}&thingType={ThingType}&thingId={ThingId}&uniformCode={UniformCode}&startTs={dts}&endTs={dte}";
                }
                else if (LineTag != null)
                {
                    return $"{url}&tagName={LineTag}&startTs={dts}&endTs={dte}";
                }
            }

            if (UniformCode != null)
            {
                return $"{_Url}/ts/history/raw?&thingType={ThingType}&thingId={ThingId}&uniformCode={UniformCode}&startTs={dts}&endTs={dte}";
            }
            else if (LineTag != null)
            {
                return $"{_Url}/ts/history/raw?tagName={LineTag}&startTs={dts}&endTs={dte}";
            }
            return "";
        }

        private void Output()
        {
            string path = SelectPath();
            if (string.IsNullOrWhiteSpace(path)) return;
            try
            {
                string filePathOne = System.IO.Path.Combine(path, this.LineName + ".csv");
                ExportToCSV(filePathOne, _CurrentDatas);

                MessageWindow.ShowMessage("导出成功");
            }
            catch (Exception e)
            {
                MessageWindow.ShowMessage("导出失败：" + e.Message);
            }
        }
        private string SelectPath() //弹出一个选择目录的对话框
        {
            System.Windows.Forms.FolderBrowserDialog path = new System.Windows.Forms.FolderBrowserDialog();
            if (path.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return path.SelectedPath;
            }
            return null;
        }

        private void ExportToCSV(string filePathOne, IList<TsData> dataList)  //filePath为保存到本地磁盘的位置
        {
            FileStream fs = System.IO.File.Create(filePathOne);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

            string col_txt = "";
            string row_txt = "";

            col_txt = this.LineName + ",时间戳";

            sw.WriteLine(col_txt);//写入更改

            for (int i = 0; i < dataList.Count; i++)
            {
                row_txt = "";//容易漏写，造成数据的重复写入

                DateTime dt = ConvertIntDateTime(dataList[i].Ts);
                row_txt = row_txt + dataList[i].Value + "," + dt.ToString("yyyy-MM-dd HH:mm:ss");

                sw.WriteLine(row_txt);//写入更改
            }
            sw.Flush();   //此处必须有此操作
        }

        public static DateTime ConvertIntDateTime(long utc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            startTime = startTime.AddMilliseconds(utc);
            //startTime = startTime.AddHours(8);
            return startTime;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Search();
        }

        /// <summary>
        /// 显示历史曲线
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="tag">测点</param>
        /// <param name="multiplier">倍率</param>
        public static void ShowWindow(string name, string tag, double multiplier)
        {
            HistoryDataWindow hdw = App.ServiceProvider.GetService(typeof(HistoryDataWindow)) as HistoryDataWindow; ;
            hdw.Owner = Application.Current.MainWindow;
            hdw.LineTag = tag;
            hdw.LineName = name;
            hdw.Multiplier = multiplier;
            hdw.ShowDialog();
        }

        /// <summary>
        /// 显示历史曲线
        /// </summary>
        /// <param name="pointName">名称</param>
        /// <param name="uniformcode">统一识别码</param>
        /// <param name="thingType">设备类型</param>
        /// <param name="thingId">设备ID</param>
        /// <param name="ratio">倍率</param>
        internal static void ShowWindow(string pointName, string uniformcode, string thingType, string thingId, double ratio)
        {
            HistoryDataWindow hdw = App.ServiceProvider.GetService(typeof(HistoryDataWindow)) as HistoryDataWindow; ;
            hdw.Owner = Application.Current.MainWindow;
            hdw.ThingType = thingType;
            hdw.ThingId = thingId;
            hdw.UniformCode = uniformcode;
            hdw.LineName = pointName;
            hdw.Multiplier = ratio;
            hdw.ShowDialog();
        }

        /// <summary>
        /// 显示历史曲线
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="uniformcode">统一识别码</param>
        /// <param name="thingType">设备类型</param>
        /// <param name="thingId">设备ID</param>
        /// <param name="ratio">倍率</param>
        /// <param name="hour">开始时间</param>
        internal static void ShowWindow(string name, string uniformcode, string thingType, string thingId, double ratio, double hour)
        {
            HistoryDataWindow hdw = App.ServiceProvider.GetService(typeof(HistoryDataWindow)) as HistoryDataWindow; ;
            hdw.Owner = Application.Current.MainWindow;
            hdw.ThingType = thingType;
            hdw.ThingId = thingId;
            hdw.UniformCode = uniformcode;
            hdw.LineName = name;
            hdw.Multiplier = ratio;
            hdw.StartTime = hour;
            hdw.ShowDialog();
        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            Search();
        }

        private void RadioButton_Click(object sender, RoutedEventArgs e)
        {
            int.TryParse(((RadioButton)sender).Tag as string, out int i);
            _Interval = i;
            Search();
        }
    }
}
