using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Station;
using NEIntelligentControl2.Service.Station;
using NEIntelligentControl2.Service.Windturbine;
using System;
using System.Collections.Generic;
using System.Configuration;
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 RealTimeAlarmWindow : Window
    {
        private StationManager _StationManager;
        private WEBHelper _WEBHelper;
        private InfoManager _InfoManager;
        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;
        public RealTimeAlarmWindow(StationManager sm, WEBHelper web, InfoManager im)
        {
            InitializeComponent();
            _StationManager = sm;
            _WEBHelper = web;
            _InfoManager = im;
            Init();
        }

        private void Init()
        {
            try
            {
#if (DEBUG)
                _Url = ConfigurationManager.AppSettings["AlarmPathDebug"];
#else
                _Url = ConfigurationManager.AppSettings["AlarmPath"];
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取配置文件[ServicePath]出错！", ex);
            }
            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;
        }

        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()
        {
            RealTimeAlarmWindow rtw = App.ServiceProvider.GetService(typeof(RealTimeAlarmWindow)) as RealTimeAlarmWindow;
            rtw.Owner = Application.Current.MainWindow;
            rtw.ShowDialog();
        }

        /// <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;
            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;
            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;
            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;
            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;
            _IsWindturbineFilter = true;
            Task.Run(Search);
        }

        private void Search()
        {
            if (!_IsLoaded) return;
            try
            {
                _IBMain.Inof("查询数据...");
                var vs = _WEBHelper.HttpGetJSON<List<AlarmInfo>>($"{_Url}/alarm/snap?stationid={_CurrentStationInfo.Id}&isopened=1&windturbineid={(string.IsNullOrWhiteSpace(_WindturbineId) ? "" : _WindturbineId)}" +
                    $"&category1={GetInfoString(_TypeInfo)}&category2={GetInfoString(_STypeInfo)}&rank={GetInfoString(_ClassTypeInfo)}&keyword={(string.IsNullOrWhiteSpace(KeyString) ? "" : KeyString)}");
                _AlarmInfos = vs;

                Dispatcher.Invoke(() => ShowData());
            }
            catch(Exception e)
            {
                _IBMain.Warning($"查询数据出现错误：{e.Message}");
                return;
            }
            _IBMain.Success();
        }

        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);
                }
            }

            if (!_IsWindturbineFilter)
            {
                _CBWindturbine.ItemsSource = ids;
            }
            _DGMain.ItemsSource = _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;
            //Filter();
        }

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

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