using Dm.util;
using Microsoft.Win32;
using ProximaAnalizer.Helpers;
using ScottPlot;
using SqlSugar;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection.Metadata.Ecma335;
using System.Security.Claims;
using System.Text;
using System.Windows;
using System.Windows.Controls.Ribbon;

namespace ProximaAnalizer.ViewModels.Dialog;

internal partial class TraceDataListViewModel : ObservableObject, IDialogAware
{
    public DialogCloseListener RequestClose { get; set; }

    public string Title { get; set; } = "DataLog";

    [ObservableProperty]
    private ObservableDictionary<DateTime, DynamicDisplay> _DynamicDisplay = [];

    [ObservableProperty]
    private ObservableCollection<string> _Headers = [];

    public bool CanCloseDialog()
    {

        return true;
    }

    public void OnDialogClosed()
    {
    }

    public void OnDialogOpened(IDialogParameters parameters)
    {
        if (!parameters.TryGetValue("Data", out object? trace))
            return;

        if (trace is not DisplayDataHelper traceData)
            return;

        Dictionary<string, List<float>> cache = [];
        cache = cache.Concat(traceData.DataLeft).ToDictionary();
        if (traceData.DataRight is not null)
            cache = cache.Concat(traceData.DataRight).ToDictionary();
        this.Headers.Clear();
        HashSet<string> headers = new();
        for (int i = 0; i < traceData.Time.Count; i++)
        {
            DynamicDisplay dynamicDisplay = new();
            long ticks = traceData.Time[i].Ticks;
            ticks -= ticks % 10000000;
            dynamicDisplay.Time = new(ticks);
            this.DynamicDisplay[dynamicDisplay.Time] = dynamicDisplay;

            foreach (var item in cache)
            {
                PairData pairData = new()
                {
                    Name = item.Key,
                    Value = item.Value[i].ToString("0.00"),
                };
                headers.Add(item.Key);
                dynamicDisplay.Data.Add(pairData);
            }
        }

        Headers.AddRange(headers);

        if (!parameters.TryGetValue("Alarm", out object? rawAlarm))
            return;

        if (rawAlarm is not IEnumerable<EventData> alarms)
            return;

        foreach (EventData eventData in alarms)
        {
            if (string.IsNullOrEmpty(eventData.Description))
                continue;

            long ticks = eventData.Occur_Time.Ticks;
            ticks -= ticks % 10000000;

            if (!this.DynamicDisplay.TryGetValue(new(ticks), out DynamicDisplay? display) || display is null)
                continue;

            display.Alarm.Add(eventData.Description);
        }
    }

    [RelayCommand]
    private void Export()
    {
        SaveFileDialog saveFileDialog = new()
        {
            Filter = "History files |*.csv;",
            FileName = "DataLog.csv",
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
        };

        if (saveFileDialog.ShowDialog() != true)
            return;

        try
        {
            using StreamWriter sw = new(saveFileDialog.FileName);
            StringBuilder header = new();
            header.append("Time");
            header.Append(',');
            foreach (var item in Headers)
            {
                header.append(item);
                header.Append(',');
            }

            header.append("Alarm");
            sw.WriteLine(header);

            foreach (var item in this.DynamicDisplay)
            {
                StringBuilder sb = new();
                sb.Append(item.Value.Time.ToString("yyyy-MM-dd HH:mm:ss.f"));
                sb.Append(',');
                foreach (var data in item.Value.Data)
                {
                    sb.append(data.Value);
                    sb.Append(',');
                }
                StringBuilder sbAlarm = new();

                for (int i = 0; i < item.Value.Alarm.Count; i++)
                {
                    sbAlarm.Append($"{item.Value.Alarm[i].Replace("°C", string.Empty)}");
                    if (i != item.Value.Alarm.Count - 1)
                        sbAlarm.Append(Environment.NewLine);
                }

                if (item.Value.Alarm.Count != 0)
                    sb.append($"\"{sbAlarm}\"");

                sw.WriteLine(sb);
            }
            MessageBoxResult result = MessageBox.Show("文件保存成功，是否查看文件？", "Save History File", MessageBoxButton.YesNo, MessageBoxImage.Question);
            FileInfo fileInfo = new(saveFileDialog.FileName);
            if (result == MessageBoxResult.Yes && fileInfo.Directory is not null)
                System.Diagnostics.Process.Start("Explorer.exe", fileInfo.Directory.FullName);

        }
        catch
        {
            MessageBox.Show("文件保存失败！", "Save History File", MessageBoxButton.OK, MessageBoxImage.Error);
        }

    }
}

public class DynamicDisplay
{
    public DateTime Time { get; set; }


    public List<PairData> Data { get; } = [];


    public List<string> Alarm { get; } = [];
}

public class PairData
{
    public string? Name { get; set; }
    public string? Value { get; set; }
}