using NEIntelligentControl2.Models.Matrix;
using NEIntelligentControl2.Models.PV;
using NEIntelligentControl2.Models.Station;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.Windturbine;
using NEIntelligentControl2.Views.Matrix;
using NEIntelligentControl2.Windows;
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.Navigation;
using System.Windows.Shapes;

namespace NEIntelligentControl2.Pages.Matrix
{
    /// <summary>
    /// 场站矩阵页面
    /// </summary>
    public partial class PageMatrixStation : Page, IStationInfo
    {
        public StationInfo StationInfo { get; set; }

        /// <summary>
        /// 矩阵块
        /// </summary>
        private List<WindBlock> _WindBlocks;
        /// <summary>
        /// 光伏矩阵块
        /// </summary>
        private List<PVBlock> _PVBlocks;
        /// <summary>
        /// 缓存
        /// </summary>
        private CacheManager _CacheManager;
        public PageMatrixStation(CacheManager cm)
        {
            InitializeComponent();
            _CacheManager = cm;
        }

        public void UpdateData(object obj)
        {
            if (StationInfo.Type == StationType.Wind || StationInfo.Id == "WIND_ALL")
            {
                UpdateWindturbine(obj);
            }
            else
            {
                Dispatcher.Invoke(() => _GDMain.ContextMenu = null);
                UpdatePV(obj);
            }
        }

        private void UpdatePV(object obj)
        {
            var datas = obj as Dictionary<string, PVInfo>;
            if (datas == null) return;
            var ls = datas.Values.Where(wi => wi.Station == StationInfo.Id).ToList();
            if (_PVBlocks == null)
            {
                InitPVInfo(ls);
                return;
            }

            Dispatcher.Invoke(() =>
            {
                foreach (var v in _PVBlocks)
                {
                    if (!datas.ContainsKey(v.Id)) continue;
                    v.Update(datas[v.Id]);
                }
            });
        }

        private void InitPVInfo(List<PVInfo> ls)
        {
            if (ls == null) return;
            _PVBlocks = new List<PVBlock>();
            ls.Sort((x, y) => x.Index - y.Index);

            Dispatcher.Invoke(() =>
            {
                foreach (var v in ls)
                {
                    PVBlock pb = new PVBlock() { Id = v.Id };
                    pb.Update(v);
                    _PVBlocks.Add(pb);
                    _OPUGMain.Add(pb);
                }
            });
        }

        /// <summary>
        /// 更新风机数据
        /// </summary>
        /// <param name="obj"></param>
        private void UpdateWindturbine(object obj)
        {
            var datas = obj as Dictionary<string, WindturbineInfo>;
            if (datas == null) return;

            var ls = datas.Values.Where(wi => wi.StationId == StationInfo.Id).ToList();

            if (_WindBlocks == null)
            {
                InitWindturbineBlocks(ls);
                return;
            }

            var lockInfo = _CacheManager.CustomLockInfos;
            Dispatcher.Invoke(() =>
            {
                foreach (var v in _WindBlocks)
                {
                    if (!datas.ContainsKey(v.WindturbineId)) continue;
                    if (lockInfo.ContainsKey(v.WindturbineId))
                    {
                        v.CustomLockInfo = lockInfo[v.WindturbineId];
                    }
                    else
                    {
                        v.CustomLockInfo = null;
                    }
                    v.Update(datas[v.WindturbineId]);
                }
            });
        }

        /// <summary>
        /// 初始化风机矩阵块
        /// </summary>
        private void InitWindturbineBlocks(List<WindturbineInfo> ls)
        {
            if (ls == null) return;
            _WindBlocks = new List<WindBlock>();
            ls.Sort((x, y) => x.ID - y.ID);
            Dispatcher.Invoke(() =>
            {
                foreach (var v in ls)
                {
                    WindBlock bs = new WindBlock(v) { WindturbineId = v.WindturbineId };
                    bs.Update(v);
                    _WindBlocks.Add(bs);
                    _OPUGMain.Add(bs);
                }
            });
        }



        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            string tag = ((Control)sender).Tag as string;
            switch (tag)
            {
                case "Start":       // 启动
                case "Stop":        // 停机
                case "Reset":       // 复位
                case "Maintain":          // 维护
                case "UnMaintain":    // 取消维护
                    SendControl(tag);
                    break;
                case "compar":      // 参数对比
                    Compar();
                    break;
                default: return;
            }
        }


        private void MenuItem_Click_Lock(object sender, RoutedEventArgs e)
        {
            // lockValue
            var type = ((Control)sender).Tag as string;
            if (type == null) return;
            bool b1 = Enum.TryParse(type, out HungType hungType);
            if (!b1) return;

            var bks = GetSelectedItems();
            if (bks.Count <= 0) return;

            string customValue = null;
            if (hungType == HungType.CustomerLock)
            {
                customValue = CustomValueWindow.ShowWindow();
                if (customValue == null) return;
            }

            var w = App.ServiceProvider.GetService(typeof(Windows.ConfirmWindow)) as Windows.ConfirmWindow;

            var ls = bks.Select(item => item.Value.WindturbineInfo).ToList();

            bool b = w.Show(hungType, ls, customValue);


            if (!b) return;


            //确认操作后,将所有选中的风机修改为非选中状态
            foreach (var item in bks)
            {
                item.Value.IsSelected = false;
            }
        }


        /// <summary>
        /// 参数对比
        /// </summary>
        private void Compar()
        {
            var vs = GetSelectedItems();
            foreach (var item in vs)
            {
                item.Value.IsSelected = false;
            }
            var ws = vs.Select(x => x.Value.WindturbineInfo).ToList();
            Windows.ParameterComparisonWindow.ShowWindow(ws);
        }

        /// <summary>
        /// 发送控制命令
        /// </summary>
        public void SendControl(string tag)
        {
            OperateStyle os = (OperateStyle)Enum.Parse(typeof(OperateStyle), tag);
            //List<WindBlockInfo> dataList = new List<WindBlockInfo>();

            var bks = GetSelectedItems();
            if (bks.Count <= 0) return;

            foreach (var item in bks)
            {
                WindBlockInfo data = GetSendData(item.Value);
                //dataList.Add(data);
            }

            //if (dataList.Count <= 0) return;

            var w = App.ServiceProvider.GetService(typeof(Windows.ConfirmWindow)) as Windows.ConfirmWindow;

            var ls = bks.Select(item => item.Value.WindturbineInfo).ToList();

            bool b = w.Show(os, ls);


            if (!b) return;


            //确认操作后,将所有选中的风机修改为非选中状态
            foreach (var item in bks)
            {
                item.Value.IsSelected = false;
            }
        }

        private Dictionary<string, WindBlock> GetSelectedItems()
        {
            Dictionary<string, WindBlock> bsw = new Dictionary<string, WindBlock>();
            foreach (var v in _WindBlocks)
            {
                if (v.IsSelected && v.WindturbineInfo != null && !bsw.ContainsKey(v.WindturbineInfo.WindturbineId))
                {
                    bsw.Add(v.WindturbineInfo.WindturbineId, v);
                }
            }

            return bsw;
        }

        /// <summary>
        /// 获取控制数据
        /// </summary>
        private WindBlockInfo GetSendData(WindBlock item)
        {
            WindBlockInfo data = new WindBlockInfo();
            //data.OperatedTime = item.OperatedTime;
            data.ID = item.WindturbineInfo.WindturbineId;
            data.WindturbineId = item.WindturbineInfo.WindturbineId;
            data.Status = item.WindturbineInfo.Status;
            data.ModelId = item.WindturbineInfo.ModelId;

            data.StationId = item.WindturbineInfo.StationId;
            data.ProjectId = item.WindturbineInfo.ProjectId;

            return data;
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (StationInfo.Type == StationType.Wind || StationInfo.Id == "WIND_ALL")
            {
                var ls = _CacheManager.Windturbineinfos?.Values.Where(wi => wi.StationId == StationInfo.Id).ToList();

                if (_WindBlocks == null)
                {
                    InitWindturbineBlocks(ls);
                }
            }
            else
            {
                var ls = _CacheManager.PVInfos?.Values.Where(wi => wi.Station == StationInfo.Id).ToList();
                if (ls == null) return;
                if (_PVBlocks == null)
                {
                    InitPVInfo(ls);
                }
            }
        }
    }
}
