using Microsoft.Win32;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.AGC;
using NEIntelligentControl2.Models.Datas;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Service.WebSocket;
using System;
using System.Collections.Generic;
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>
    /// AGC曲线窗口
    /// </summary>
    public partial class AGCLineWindow : Window
    {
        private AGCInfo _AGCInfo;
        private ViewModel _ViewModel;
        private UrlManager _UrlManager;
        private WEBHelper _WEBHelper;
        private string _HistoyUrl;
        public AGCLineWindow(ViewModel vm, AGCInfo info)
        {
            InitializeComponent();
            _ViewModel = vm;
            _ViewModel.AxisX.IsZoomEnabled = true;
            _ViewModel.AxisX.IsPanEnabled = true;
            _AGCInfo = info;
            _UrlManager = App.ServiceProvider.GetService(typeof(UrlManager)) as UrlManager;
            _WEBHelper = App.ServiceProvider.GetService(typeof(WEBHelper)) as WEBHelper;
            _HistoyUrl = _UrlManager.DataServicePath;
            Init();
        }

        private void Init()
        {
            this.Title = _AGCInfo.Title;
            _pv.Model = _ViewModel;

            _ViewModel.AxisX.StringFormat = "MM-dd HH:mm";

            var dt = DateTime.Now;
            _tbStart.Text = dt.AddHours(-8).ToString("yyyy-MM-dd HH:mm:ss");
            _tbEnd.Text = dt.ToString("yyyy-MM-dd HH:mm:ss");
        }

        internal static void ShowWindow(ViewModel vm, AGCInfo info)
        {
            ViewModel nvm = new ViewModel(vm.ActPower, vm.PowerSet);
            AGCLineWindow alw = new AGCLineWindow(nvm, info);
            alw.Owner = Application.Current.MainWindow;
            alw.ShowDialog();
        }

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

        /// <summary>
        /// 导出
        /// </summary>
        private void Output()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "导出AGC数据";
            sfd.Filter = "csv文件(.csv)|*.csv";
            var v = sfd.ShowDialog();
            if (v != true) return;
            var path = sfd.FileName;

            try
            {
                ExportToCSV(path);
                MessageWindow.ShowMessage("导出成功!");
            }
            catch
            {
                MessageWindow.ShowMessage("导出失败!");
            }
        }

        private void ExportToCSV(string filePathOne)
        {
            FileStream fs = System.IO.File.Create(filePathOne);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            StringBuilder row_txt = new StringBuilder();

            sw.WriteLine($"{this.Title}\n实发有功,有功设定限值,时间戳");

            for (int i = 0; i < _ViewModel.ActPower.Count; ++i)
            {
                DateTime dt = _ViewModel.ActPower[i].Ts.GetLongDateTime();
                row_txt.Append(_ViewModel.ActPower[i].Value).Append(",");
                if (i < _ViewModel.PowerSet.Count)
                {
                    row_txt.Append(_ViewModel.PowerSet[i].Value).Append(",");
                }
                row_txt.Append(dt.ToString("yyyy-MM-dd HH:mm:ss")).Append("\n");
            }
            sw.WriteLine(row_txt.ToString());//写入更改
            sw.Flush();   //此处必须有此操作
        }

        /// <summary>
        /// 搜索
        /// </summary>
        private void Search()
        {
            bool bs = DateTime.TryParse(_tbStart.Text, out DateTime ds);
            bool be = DateTime.TryParse(_tbEnd.Text, out DateTime de);
            if (!(bs && be))
            {
                MessageWindow.ShowMessage("时间格式错误!");
                return;
            }
            Task.Run(initHistoryData);

            void initHistoryData()
            {
                var psTag = _AGCInfo.AiPoints.Where(v => v.Type == TagType.PowerSet).FirstOrDefault();
                var apTag = _AGCInfo.AiPoints.Where(v => v.Type == TagType.ActualPower).FirstOrDefault();
                try
                {
                    var vps = _WEBHelper.HttpGetJSON<List<TsData>>($"{_HistoyUrl}/ts/history/snap?interval=60&tagName={psTag?.Tag}&startTs={ds.GetTimeSpan()}&endTs={de.GetTimeSpan()}");
                    var vap = _WEBHelper.HttpGetJSON<List<TsData>>($"{_HistoyUrl}/ts/history/snap?interval=60&tagName={apTag?.Tag}&startTs={ds.GetTimeSpan()}&endTs={de.GetTimeSpan()}");
                    if (vps != null)
                    {
                        _ViewModel.SetValue(psTag, vps);
                    }
                    if (vap != null)
                    {
                        _ViewModel.SetValue(apTag, vap);
                    }
                    Dispatcher.Invoke(() => {
                        _pv.Model = null;
                        _pv.Model = _ViewModel;
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    MessageWindow.ShowMessage("数据请求出现错误：" + ex.Message);
                }
            }
        }
    }
}
