using NEIntelligentControl2.Models.Alarm;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Service.User;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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 DeviceDetailAlarmWindow : Window
    {
        /// <summary>
        /// 故障信息
        /// </summary>
        public FaultInfo FaultInfo { get; private set; }
        /// <summary>
        /// 是否需要确认
        /// </summary>
        public bool IsConfirm { get; set; }

        private WEBHelper _WEBHelper;
        private UserManager _UserManager;
        private string _Url;
        private List<DeviceAlarmInfo> _DeviceAlarmInfoList;
        public DeviceDetailAlarmWindow(WEBHelper web, UserManager um)
        {
            InitializeComponent();
            _WEBHelper = web;
            _UserManager = um;
            InitUrl();
        }

        private void InitUrl()
        {
            try
            {
#if(DEBUG)
                _Url = ConfigurationManager.AppSettings["ServicePathDebug"];
#else
                _Url = ConfigurationManager.AppSettings["ServicePath"];
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch { }
        }

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



        /// <summary>
        /// 显示窗口
        /// </summary>
        internal static bool Show(FaultInfo faultInfo, bool isConfirm = false)
        {
            var ddaw = App.ServiceProvider.GetService(typeof(DeviceDetailAlarmWindow)) as DeviceDetailAlarmWindow; ;
            ddaw.FaultInfo = faultInfo;
            ddaw.IsConfirm = isConfirm;
            ddaw.Owner = Application.Current.MainWindow;
            ddaw._TBTitle.Text = $"设备报警详情 -- [{faultInfo.ObjectName}]";
            var b = ddaw.ShowDialog();
            return b == true;
        }

        private void window_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(InitData);
        }

        private void InitData()
        {
            if (FaultInfo == null) return;
            string obj;
            if (FaultInfo.Category1 == "SYZ" || FaultInfo.Category1 == "STATION" || FaultInfo.Category1 == "GF")
            {
                obj = $"{FaultInfo.StationId}&cateGory1=SYZ";
            }
            else
            {
                obj = $"{FaultInfo.WindturbineId}&cateGory1=windturbine";
            }
            var url = $"{_Url}/alarm/real-time-alarm?objectId={obj}";
            var vs = _WEBHelper.HttpGetJSON<List<DeviceAlarmInfo>>(url);
            _DeviceAlarmInfoList = vs;


            Dispatcher.Invoke(() => _DGMain.ItemsSource = vs);
        }

        private void _DGMain_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (e.AddedCells.Count <= 0) return;
            var vv = e.AddedCells[0].Item as DeviceAlarmInfo;
            if (vv == null) return;
            foreach (var v in _DeviceAlarmInfoList)
            {
                v.IsSelected = v == vv;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            switch (((Control)sender).Tag)
            {
                case "generate":// 生成缺陷单
                    Generate();
                    break;
                case "ok":// 确认
                    Confrom();
                    break;
                default: return;
            }
        }

        /// <summary>
        /// 确认
        /// </summary>
        private void Confrom()
        {
            SendConfirmInfo();
        }

        private DeviceAlarmInfo GetSelectedItem()
        {
            foreach (var v in _DeviceAlarmInfoList)
            {
                if (v.IsSelected) return v;
            }
            return null;
        }


        /// <summary>
        /// 生成缺陷单
        /// </summary>
        private void Generate()
        {
            SendConfirmInfo();
        }

        private void SendConfirmInfo()
        {
            if (!_UserManager.IsLogined)
            {
                bool b = _UserManager.TempLogin();
                if (!b) return;
            }
            this.Close();
            try
            {
                string s = _WEBHelper.HttpGetString($"{_Url}/alarm/confirm?snapID={FaultInfo.SnapID}&faultID={FaultInfo.Id}&userName={_UserManager.User.Name}");
            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    class DeviceAlarmInfo : INotifyPropertyChanged
    {
        public long Id { get; set; }
        public string ObjectId { get; set; }
        public string ObjectName { get; set; }
        public long SnapId { get; set; }
        public DateTime LastUpdateTime { get; set; }
        public string AlertText { get; set; }
        public string RankName { get; set; }
        public string CategoryName { get; set; }
        public string FaultCause { get; set; }
        public string HaltType { get; set; }
        public string FaultCategory { get; set; }
        public string LastUpdateTimeString { get => LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss"); }

        private bool isSelected;
        public bool IsSelected { get => isSelected; set { isSelected = value; OnPropertyChanged(); } }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}
