using Microsoft.Win32;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.WebSocket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
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.Navigation;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Views.Infos
{
    /// <summary>
    /// 状态变化查询
    /// </summary>
    public partial class StateChange : UserControl
    {

        public WindturbineInfo WindturbineInfo { get; internal set; }
        private WEBHelper _WEBHelper;
        private UrlManager _UrlManager;
        private string _Url;
        private List<StatusTimeInfo> _CurrentData;

        public StateChange()
        {
            InitializeComponent();
            _WEBHelper = App.ServiceProvider.GetService(typeof(WEBHelper)) as WEBHelper;
            _UrlManager = App.ServiceProvider.GetService(typeof(UrlManager)) as UrlManager;
            _Url = _UrlManager.ServicePath;
            Init();
        }

        private void Init()
        {
            var st = DateTime.Now.AddDays(-1);
            _tpstart.SelectedDateTime = st.AddSeconds(-st.Second);
        }

        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 dialog = new SaveFileDialog
            {
                Title = "保存csv文件",
                Filter = "csv文件(*.csv) |*.csv |所有文件(*.*) |*.*",
                FilterIndex = 1
            };
            var v = dialog.ShowDialog();
            if (v != true) return;
            var path = dialog.FileName;

            Task.Run(output);

            void output()
            {
                try
                {
                    _IBMain.Inof("导出数据...");
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
                    {
                        sw.WriteLine("风机,状态,开始时间,结束时间,持续时间（小时）");

                        foreach (var dt in _CurrentData)
                        {
                            sw.WriteLine(string.Format("{0},{1},{2},{3},{4}", dt.Code, dt.StatusName, dt.StartTime, dt.EndTime, dt.Duration));
                        }
                    }
                    _IBMain.Success();
                    Dispatcher.Invoke(() => MessageWindow.ShowMessage("数据导出成功！"));
                }
                catch (Exception ex)
                {
                    _IBMain.Warning($"导出数据出现错误：{ex.Message}");
                }
            }
        }

        private void Search()
        {
            var ur = $"{_Url}/api/windturbine/status-nopage?startTs={_tpstart.SelectedDateTime.GetTimeSpan()}&endTs={_tpend.SelectedDateTime.GetTimeSpan()}&windturbineId={this.WindturbineInfo.WindturbineId}";
            

            Task.Run(search);

            void search()
            {
                try
                {
                    _IBMain.Inof("查询数据...");
                    var sts = _WEBHelper.HttpGetJSON<List<StatusTimeInfo>>(ur);

                    Dispatcher.Invoke(() =>
                    {
                        _DGMain.ItemsSource = sts;
                        _si.ItemsSource = sts;
                        _CurrentData = sts;
                    });
                    _IBMain.Success();
                }
                catch (Exception ex)
                {
                    _IBMain.Warning($"查询数据出现错误：{ex.Message}");
                }
            }
        }

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