using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.User;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Service.Windturbine;
using NEIntelligentControl2.Views.Matrix;
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.Controls.Primitives;
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 ConfirmWindow : Window
    {
        private OperateStyle _OperateStyle;
        private List<WindturbineInfo> _WindturbineInfos;
        private WindturbineInfoBridge _WindturbineInfoBridge;// 风机信息数据桥
        private MessageBridge _MessageBridge;
        private List<WindturbineInfo> _AllowSendWindturbines;
        private ControlManager _ControlManager;
        private HungType _HungType;
        private bool _IsLockOrUnLock;
        private string _CustomLock;// 自定义挂牌信息
        public ConfirmWindow(MessageBridge bridge, ControlManager cm)
        {
            InitializeComponent();
            _MessageBridge = bridge;
            _ControlManager = cm;
            _WindturbineInfoBridge = new WindturbineInfoBridge() { Messaged = OnMessage };
            _MessageBridge.Register(_WindturbineInfoBridge);
        }

        private void OnMessage(Dictionary<string, WindturbineInfo> obj)
        {
            if (obj == null) return;
            Dispatcher.Invoke(() =>
            {
                Update(_UGAllow, obj);
                Update(_UGNotAllow, obj);
            });
        }

        private void Update(UniformGrid ug, Dictionary<string, WindturbineInfo> obj)
        {
            foreach (var v in ug.Children)
            {
                var w = v as WindBlock;
                if (w == null || !obj.ContainsKey(w.WindturbineId)) continue;
                w.Update(obj[w.WindturbineId]);
            }
        }

        internal bool Show(OperateStyle os, List<WindturbineInfo> bks)
        {
            _TBTitle.Text = $"发送{os.GetStringValue()}指令";
            this.Owner = Application.Current.MainWindow;
            _OperateStyle = os;
            _WindturbineInfos = bks;
            InitView();
            var b = ShowDialog();
            return b != null && b == true;
        }

        internal bool Show(HungType hungType, List<WindturbineInfo> ls, string customLock = null)
        {
            _TBTitle.Text = $"发送挂牌指令";
            this.Owner = Application.Current.MainWindow;
            _HungType = hungType;
            _IsLockOrUnLock = true;
            _WindturbineInfos = ls;
            _CustomLock = customLock;
            InitView();
            var b = ShowDialog();
            return b != null && b == true;
        }

        private void InitView()
        {
            _AllowSendWindturbines = new List<WindturbineInfo>();
            foreach (var v in _WindturbineInfos)
            {
                WindBlock wb = new WindBlock(v) { WindturbineId = v.WindturbineId };
                wb.Update(v);
                if (GetIsAllowSend(v))
                {
                    _UGAllow.Children.Add(wb);
                    _AllowSendWindturbines.Add(v);
                }
                else
                {
                    _UGNotAllow.Children.Add(wb);
                }
            }
        }

        private bool GetIsAllowSend(WindturbineInfo v)
        {
            if (v.IsLocked)
            {
                return _IsLockOrUnLock && _HungType == HungType.UnLock;
            }
            else if(_IsLockOrUnLock)
            {
                return v.LockType == HungType.UnLock;
            }
            switch (_OperateStyle)
            {
                case OperateStyle.Start:
                    return v.State == WindturbineState.Standby;
                case OperateStyle.Stop:
                    return v.State == WindturbineState.GridConnected;
                case OperateStyle.Reset:
                    return v.State == WindturbineState.Malfunction;
                case OperateStyle.Maintain:
                    return v.State == WindturbineState.Standby && v.ModelId != "UP105-2000-S";
                case OperateStyle.UnMaintain:
                    return v.State == WindturbineState.Maintain && v.ModelId != "UP105-2000-S";
                default: return false;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            switch (((Control)sender).Tag)
            {
                case "send":
                    Send();
                    break;
                case "cancel":
                    this.DialogResult = false;
                    break;
                default: return;
            }
        }
        /// <summary>
        /// 发送控制指令
        /// </summary>
        private void Send()
        {
            var um = App.ServiceProvider.GetService(typeof(UserManager)) as UserManager;
            if (!um.IsLogined)
            {
                bool b1 = um.TempLogin();
                if (!b1) return;
            }
            if (_IsLockOrUnLock)
            {
                Task.Run(SendLock);
            }
            else
            {
                Task.Run(SendCmd);
            }

            try
            {
                this.DialogResult = true;
            }
            catch { }
        }

        private void SendLock()
        {
            var cis = GetControlInstructions();
            var v = _ControlManager.SendLock(cis);
            if (v == null)
            {
                return;
            }
            Dispatcher.Invoke(() =>
            {
                if (v.Length > 0)
                {
                    MessageWindowBig.ShowMessage(v);
                }
            });
        }

        void SendCmd()
        {
            var cis = GetControlInstructions();
            var v = _ControlManager.SendCmd(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>();
            foreach (var v in _AllowSendWindturbines)
            {
                ControlInstruction ci = new ControlInstruction();
                ci.WindturbineId = v.WindturbineId;
                ci.StationId = v.StationId;
                ci.ProjectId = v.ProjectId;
                ci.ModelId = v.ModelId;
                ci.LockType = _HungType;
                ci.LockValue = _CustomLock;
                ci.ControlType = _OperateStyle;
                ll.Add(ci.WindturbineId, ci);
            }
            return ll;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _MessageBridge.Unregister(_WindturbineInfoBridge);
        }
    }
}
