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
{
///
/// 历史曲线
///
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"); } }
///
/// 有功设定数据(历史)
///
private ChartValues _CVLine { get; set; } = new ChartValues();
///
/// 数据路径
///
private string _Url;
private WEBHelper _WEBHelper;
private UrlManager _UrlManager;
private List _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().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 vs = null;
if (string.IsNullOrWhiteSpace(url)) return;
vs = _WEBHelper.HttpGetJSON>(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 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();
}
///
/// 显示历史曲线
///
/// 名称
/// 测点
/// 倍率
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();
}
///
/// 显示历史曲线
///
/// 名称
/// 统一识别码
/// 设备类型
/// 设备ID
/// 倍率
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();
}
///
/// 显示历史曲线
///
/// 名称
/// 统一识别码
/// 设备类型
/// 设备ID
/// 倍率
/// 开始时间
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();
}
}
}