using Microsoft.Win32;
using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Station;
using NEIntelligentControl2.Service.Station;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Service.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.Shapes;

namespace NEIntelligentControl2.Windows.Alarm
{
    /// <summary>
    /// 历史报警窗口
    /// </summary>
    public partial class HistoryAlarmWindow : Window
    {
        private StationManager _StationManager;
        private WEBHelper _WEBHelper;
        private InfoManager _InfoManager;
        private UrlManager _UrlManager;
        private string _Url;

        private StationInfo _CurrentStationInfo;// 场站
        private AlarmTypeItem _ClassTypeInfo;// 级别
        private AlarmTypeItem _TypeInfo;// 类型
        private AlarmTypeItem _STypeInfo;// 子类型
        private List<AlarmInfo> _AlarmInfos;
        private AlarmTypeInfo _AlarmTypeInfo;


        private string _WindturbineId;
        public string KeyString { get; set; }
        private bool _IsWindturbineFilter;
        private bool _IsLoaded;

        private string _StartTime;
        private string _EndTime;
        private int _PageIndex;// 页索引
        private int _EachPageCount;// 每页条数

        private List<AlarmInfo> _CurrentAlarmInfos;
        public HistoryAlarmWindow(StationManager sm, WEBHelper web, InfoManager im, UrlManager um)
        {
            InitializeComponent();
            _StationManager = sm;
            _WEBHelper = web;
            _InfoManager = im;
            _UrlManager = um;
            _TBStartTime.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
            _TBEndTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            Init();
        }

        private void Init()
        {
            _Url = _UrlManager.AlarmPath;

            var ls = _StationManager.GetStationInfos().Where(i => i.Type != Models.Station.StationType.Other).ToList();
            if (ls == null) return;
            _CBStation.ItemsSource = ls;
            _AlarmTypeInfo = _InfoManager.GetAlarmTypeInfo();
            _CBClass.ItemsSource = _AlarmTypeInfo.RankInfo;
            _CBType.ItemsSource = _AlarmTypeInfo.DeviceType;
            _IBMain.OnPagination = OnPagination;
        }

        private void ContentControl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            switch (((FrameworkElement)sender).Tag)
            {
                case "close":
                    this.Close();
                    break;
                case "maximized":
                    Maximized();
                    break;
                default: return;
            }
        }

        private void Maximized()
        {
            if (this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
            }
            else
            {
                this.WindowState = WindowState.Maximized;
            }
        }

        public static void ShowWindow()
        {
            HistoryAlarmWindow haw = App.ServiceProvider.GetService(typeof(HistoryAlarmWindow)) as HistoryAlarmWindow;
            haw.Owner = Application.Current.MainWindow;
            haw.ShowDialog();
        }


        private void InitTime()
        {
            DateTime.TryParse(_TBStartTime.Text, out DateTime ds);
            DateTime.TryParse(_TBEndTime.Text, out DateTime de);
            _StartTime = ds.ToString("yyyy-MM-dd HH:mm:ss");
            _EndTime = de.ToString("yyyy-MM-dd HH:mm:ss");

            _PageIndex = _IBMain.PageIndex;
            _EachPageCount = _IBMain.EachPageCount;
        }



        private void OnPagination(int arg1, int arg2)
        {
            InitTime();
            Task.Run(Search);
        }

        /// <summary>
        /// 场站
        /// </summary>
        private void _CBStation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as StationInfo;
            if (v == null) return;
            if (_CurrentStationInfo != null && _CurrentStationInfo.Id == v.Id) return;
            _CurrentStationInfo = v;
            InitTime();
            Task.Run(Search);
        }

        /// <summary>
        /// 级别
        /// </summary>
        private void _CBClass_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as AlarmTypeItem;
            if (v == null) return;
            _ClassTypeInfo = v;
            _IsWindturbineFilter = false;
            InitTime();
            Task.Run(Search);
        }

        /// <summary>
        /// 类型
        /// </summary>
        private void _CBType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as AlarmTypeItem;
            if (v == null) return;
            _TypeInfo = v;
            _CBSType.ItemsSource = v.SubItem;
            _CBSType.SelectedIndex = 0;
            _IsWindturbineFilter = false;
            InitTime();
            Task.Run(Search);
        }

        /// <summary>
        /// 子类型
        /// </summary>
        private void _CBSType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as AlarmTypeItem;
            if (v == null) return;
            _STypeInfo = v;
            _IsWindturbineFilter = false;
            InitTime();
            Task.Run(Search);
        }

        /// <summary>
        /// 风机
        /// </summary>
        private void _CBWindturbine_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as string;
            if (v == null) return;
            _WindturbineId = v == "全部" ? "" : v;
            _IsWindturbineFilter = true;
            InitTime();
            Task.Run(Search);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            switch (((Control)sender).Tag)
            {
                case "search":
                    InitTime();
                    Task.Run(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;
            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}");
                }
            });
        }

        private void Search()
        {
            if (!_IsLoaded) return;
            var ur = $"{_Url}/alarm/history/page?pagenum={_PageIndex}&pagesize={_EachPageCount}" +
                $"&stationid={_CurrentStationInfo.Id}&starttime={_StartTime}&endtime={_EndTime}&windturbineid={(string.IsNullOrWhiteSpace(_WindturbineId) ? "" : _WindturbineId)}" +
                $"&rank={GetInfoString(_ClassTypeInfo)}&category1={GetInfoString(_TypeInfo)}&category2={GetInfoString(_STypeInfo)}&keyword={(string.IsNullOrWhiteSpace(KeyString) ? "" : KeyString)}";
            try
            {
                _IBMain.Inof("查询数据...");
                var vs = _WEBHelper.HttpGetJSON<AlarmPage>(ur);
                _AlarmInfos = vs.Records;

                ShowData();

                _IBMain.Success();
                Dispatcher.Invoke(() =>
                {
                    _IBMain.PageCount = vs.Pages;
                });
            }
            catch (Exception ex)
            {
                _IBMain.Warning($"查询数据出现错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 展示信息
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ShowData()
        {
            if (_AlarmInfos == null || _AlarmInfos.Count <= 0)
            {
                _AlarmInfos = new List<AlarmInfo>();
            }

            var ids = new HashSet<string>() { "全部" };
            foreach (var v in _AlarmInfos)
            {
                if (!string.IsNullOrWhiteSpace(v.WindturbineId))
                {
                    ids.Add(v.WindturbineId);
                }
            }
            Dispatcher.Invoke(() =>
            {
                if (!_IsWindturbineFilter)
                {
                    _CBWindturbine.ItemsSource = ids;
                }
                _DGMain.ItemsSource = _AlarmInfos;
                _CurrentAlarmInfos = _AlarmInfos;
            });
        }

        private object GetInfoString(AlarmTypeItem ati)
        {
            if (ati == null) return "";
            return ati.Id == "all" ? "" : ati.Id;
        }

        private void _CBKeyString_LostFocus(object sender, RoutedEventArgs e)
        {
            KeyString = _CBKeyString.Text;
        }

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _IsLoaded = true;
            InitTime();
            Task.Run(Search);
        }
    }
}
