using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Station;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.Station;
using NEIntelligentControl2.Service.User;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Service.Windturbine;
using NEIntelligentControl2.Views.Matrix;
using System;
using System.Collections.Generic;
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>
    /// 推荐窗口
    /// </summary>
    public partial class RecomendWindow : Window
    {
        private SuggestionManager _SuggestionManager;
        private WindturbineInfoBridge _WindturbineInfoBridge;
        private MessageBridge _MessageBridge;
        private StationManager _StationManager;
        private UserManager _UserManager;
        /// <summary>
        /// 矩阵块
        /// </summary>
        private List<WindBlock> _WindBlocks;
        private HashSet<string> _WindturbineIds;
        private StationInfo _CurrentStationInfo;
        private string _OperationType;
        private ControlManager _ControlManager;
        private CacheManager _CacheManager;
        public RecomendWindow(SuggestionManager sm, MessageBridge mb, StationManager smm, ControlManager cm, UserManager um, CacheManager cam)
        {
            InitializeComponent();
            _WindBlocks = new List<WindBlock>();
            _WindturbineIds = new HashSet<string>();
            _SuggestionManager = sm;
            _MessageBridge = mb;
            _StationManager = smm;
            _ControlManager = cm;
            _UserManager = um;
            _CacheManager = cam;
            _SuggestionManager.OnSuggestion = OnSuggestion;
            _WindturbineInfoBridge = new WindturbineInfoBridge() { Messaged = WindturbineMessaged };
            _MessageBridge.Register(_WindturbineInfoBridge);
            Init();
        }

        private void WindturbineMessaged(Dictionary<string, WindturbineInfo> obj)
        {
            Dispatcher.Invoke(() =>
            {
                foreach(var v in _WindBlocks)
                {
                    if (!obj.ContainsKey(v.WindturbineId)) continue;
                    v.Update(obj[v.WindturbineId]);
                }
            });
        }

        private void Init()
        {
            var vs = _StationManager.GetStationInfos().Where(s => s.Type == Models.Station.StationType.Wind).ToList();
            vs.Add(new Models.Station.StationInfo() { Name = "全部", Id = "all" });
            _LBMain.ItemsSource = vs;
            _LBMain.SelectedIndex = vs.Count - 1;
        }

        private void OnSuggestion(List<WindturbineSuggestion> obj)
        {
            try
            {
                if (obj == null)
                {
                    obj = new List<WindturbineSuggestion>();
                }
                var ids = obj.Select(s => s.WindturbineId).ToList();
                var removed = _WindBlocks.Where(w => !ids.Contains(w.WindturbineId)).ToList();
                Dispatcher.Invoke(() =>
                {
                    InitCount(obj);
                    foreach (var v in obj)
                    {
                        if (_WindturbineIds.Contains(v.WindturbineId)) continue;
                        _WindturbineIds.Add(v.WindturbineId);
                        WindBlock wb = new WindBlock() { WindturbineId = v.WindturbineId, Suggestion = v };
                        if(_CacheManager.Windturbineinfos!=null&& _CacheManager.Windturbineinfos.ContainsKey(v.WindturbineId))
                        {
                            wb.Update(_CacheManager.Windturbineinfos[v.WindturbineId]);
                        }
                        _WindBlocks.Add(wb);
                        if (IsFilterOK(wb))
                        {
                            _OPUGMain.Add(wb);
                        }
                    }
                    foreach (var v in removed)
                    {
                        _WindBlocks.Remove(v);
                        _WindturbineIds.Remove(v.WindturbineId);
                        _OPUGMain.Remove(v);
                    }
                });
            }
            catch { }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitCount(List<WindturbineSuggestion> obj)
        {
            _TBAll.Text = obj.Count.ToString();
            _TBStart.Text = obj.Where(w => w.OperateType == OperateStyle.Start).ToArray().Length.ToString();
            _TBStop.Text = obj.Where(w => w.OperateType == OperateStyle.Stop).ToArray().Length.ToString();
            _TBReset.Text = obj.Where(w => w.OperateType == OperateStyle.Reset).ToArray().Length.ToString();
            _TBMaintain.Text = obj.Where(w => w.OperateType == OperateStyle.Maintain).ToArray().Length.ToString();
            _TBUnMaintain.Text = obj.Where(w => w.OperateType == OperateStyle.UnMaintain).ToArray().Length.ToString();
        }

        private bool IsFilterOK(WindBlock wb)
        {
            if (_OperationType != null && _OperationType != "all")
            {
                Enum.TryParse(_OperationType, out OperateStyle ot);
                if(_CurrentStationInfo.Id == "all")
                {
                    return wb.Suggestion.OperateType == ot;
                }
                else
                {
                    return wb.Suggestion.OperateType == ot && wb.WindturbineInfo?.StationId == _CurrentStationInfo.Id;
                }
            }
            else
            {
                if (_CurrentStationInfo.Id != "all")
                {
                    return wb.WindturbineInfo?.StationId == _CurrentStationInfo.Id;
                }
            }
            return true;
        }

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


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Send();
        }

        /// <summary>
        /// 发送控制指令
        /// </summary>
        private void Send()
        {
            if (!_UserManager.IsLogined)
            {
                bool b = _UserManager.TempLogin();
                if (!b) return;
            }

            var cis = GetControlInstructions();
            Task.Run(send);
            MessageWindow.ShowMessage("指令发送成功！");


            void send()
            {
                var v = _ControlManager.SendCmdNotCheck(cis);
                if (v == null)
                {
                    return;
                }
                Dispatcher.Invoke(() =>
                {
                    if (v.Length > 0)
                    {
                        MessageWindowBig.ShowMessage(v);
                    }
                });
            }
        }
        private Dictionary<string, ControlInstruction> GetControlInstructions()
        {
            Dictionary<string, ControlInstruction> ll = new Dictionary<string, ControlInstruction>();
            List<WindBlock> ls = GetSelectedItems();
            foreach (var v in ls)
            {
                ControlInstruction ci = new ControlInstruction();
                ci.WindturbineId = v.WindturbineId;
                ci.StationId = v.WindturbineInfo.StationId;
                ci.ProjectId = v.WindturbineInfo.ProjectId;
                ci.ModelId = v.WindturbineInfo.ModelId;
                ci.ControlType = v.Suggestion.OperateType;
                ci.LockType = v.WindturbineInfo.LockType;
                ll.Add(ci.WindturbineId, ci);
            }
            return ll;
        }

        private List<WindBlock> GetSelectedItems()
        {
            List<WindBlock> ls = new List<WindBlock>();
            foreach(var v in _WindBlocks)
            {
                if (v.IsSelected)
                {
                    ls.Add(v);
                }
            }
            return ls;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _MessageBridge.Unregister(_WindturbineInfoBridge);
        }
        /// <summary>
        /// 场站选择
        /// </summary>
        private void _LBMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as StationInfo;
            if (v == null) return;
            _CurrentStationInfo = v;
            ToFilter();
        }
        /// <summary>
        /// 操作选择
        /// </summary>
        private void _LBOperation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count <= 0) return;
            var v = e.AddedItems[0] as ListBoxItem;
            if (v == null) return;
            _OperationType = v.Tag as string;
            ToFilter();
        }

        private void ToFilter()
        {
            if (_WindBlocks == null) return;
            _OPUGMain?.Clear();
            foreach(var v in _WindBlocks)
            {
                if (IsFilterOK(v))
                {
                    _OPUGMain.Add(v);
                }
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            OnSuggestion(_SuggestionManager.WindturbineSuggestions);
        }
    }
}
