using Microsoft.Win32;
using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Windturbine;
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.Navigation;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Views.Alarm
{
    /// <summary>
    /// 风机历史报警
    /// </summary>
    public partial class WindturbineHistoryAlarm : UserControl
    {
        private string _Url;
        private WEBHelper _WEBHelper;
        private List<AlarmInfo> _CurrentAlarmInfos;

        public WindturbineInfo WindturbineInfo { get; set; }

        /// <summary>
        /// 是否是预警
        /// </summary>
        public bool IsCustom { get; set; }
        public WindturbineHistoryAlarm()
        {
            InitializeComponent();
            _WEBHelper = App.ServiceProvider.GetService(typeof(WEBHelper)) as WEBHelper;

            _TBStartTime.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
            _TBEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            try
            {
#if (DEBUG)
                _Url = ConfigurationManager.AppSettings["AlarmPathDebug"];
#else
                _Url = ConfigurationManager.AppSettings["AlarmPath"];
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取配置文件[ServicePath]出错！", ex);
            }
        }

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

        private void Search()
        {

            DateTime.TryParse(_TBStartTime.Text, out DateTime ds);
            DateTime.TryParse(_TBEndTime.Text, out DateTime de);

            string start = ds.ToString("yyyy-MM-dd HH:mm:ss");
            string end = de.ToString("yyyy-MM-dd HH:mm:ss");

            Task.Run(() =>
            {
                _IBMain.Inof("查询数据...");
                var c1 = IsCustom ? "custom" : "windturbine";
                var ur = $"{_Url}/alarm/history/page?pagenum=1&windturbineid={WindturbineInfo.WindturbineId}&category1={c1}&pagesize=7000&stationid={WindturbineInfo.StationId}&starttime={start}&endtime={end}";
                try
                {
                    var vs = _WEBHelper.HttpGetJSON<AlarmPage>(ur);
                    if (vs == null || vs.Records == null)
                    {
                        vs.Records = new List<AlarmInfo>();
                    }
                    Dispatcher.Invoke(() =>
                    {
                        _DGMain.ItemsSource = vs.Records;
                    });
                    _CurrentAlarmInfos = vs.Records;
                    _IBMain.Success();
                }
                catch (Exception e)
                {
                    _IBMain.Warning($"查询数据出现错误：{e.Message}");
                }
            });
        }

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

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

        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;
            OutputToFile(path);
        }

        private void OutputToFile(string path)
        {
            Task.Run(() =>
            {
                try
                {
                    _IBMain.Inof("导出数据...");
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
                    {
                        sw.WriteLine("时间,设备,报警信息,级别,报警类型,停机类型,故障类型,故障原因");
                        if (_CurrentAlarmInfos == null || _CurrentAlarmInfos.Count <= 0)
                        {
                            _IBMain.Success();
                            return;
                        }

                        foreach (var v in _CurrentAlarmInfos)
                        {
                            sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", v.AlertTimeTimeString,
                                v.ObjectName, v.AlertText, v.RankString, v.Category1String, "", "", ""));
                        }
                    }
                    _IBMain.Success();
                    Dispatcher.Invoke(() => MessageWindow.ShowMessage("数据导出成功！"));
                }
                catch (Exception ex)
                {
                    _IBMain.Warning($"导出数据出现错误：{ex.Message}");
                }
            });
        }
    }
}
