using Microsoft.Win32;
using NEIntelligentControl2.Models;
using NEIntelligentControl2.Models.Messages;
using NEIntelligentControl2.Models.Pages;
using NEIntelligentControl2.Models.Station;
using NEIntelligentControl2.Models.Windturbine;
using NEIntelligentControl2.Service.Station;
using NEIntelligentControl2.Service.WebSocket;
using NEIntelligentControl2.Views.Infos;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
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.Home
{
    /// <summary>
    /// 状态时间页面
    /// </summary>
    public partial class StateTimePage : Page
    {
        private StationManager _StationManager;
        private TagManager _TagManager;
        private WEBHelper _WEBHelper;
        private UrlManager _UrlManager;
        private string _Url;

        private List<StationInfo> _StationInfos;    // 场站信息
        private StationInfo _CurrentStationInfo;// 当前场站信息
        private Dictionary<string, List<StatusTimeInfo>> _CurrentData;
        public StateTimePage(WEBHelper web, TagManager tm, StationManager sm, UrlManager um)
        {
            InitializeComponent();
            _TagManager = tm;
            _StationManager = sm;
            _WEBHelper = web;
            _UrlManager = um;
            _Url = _UrlManager.ServicePath;
            Init();
        }

        private void Init()
        {
            var st = DateTime.Now.AddDays(-1);
            _tpstart.SelectedDateTime = st.AddSeconds(-st.Second);
        }

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

        /// <summary>
        /// 导出
        /// </summary>
        private void Output()
        {
            SaveFileDialog dialog = new SaveFileDialog
            {
                Title = "保存csv文件",
                Filter = "csv文件(*.csv) |*.csv |所有文件(*.*) |*.*",
                FilterIndex = 1
            };
            var v = dialog.ShowDialog();
            if (v != true) return;
            var path = dialog.FileName;

            Task.Run(output);

            void output()
            {
                try
                {
                    _IBMain.Inof("导出数据...");
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
                    {
                        sw.WriteLine("风机,状态,开始时间,结束时间,持续时间（小时）");

                        foreach (var vv in _CurrentData)
                        {
                            foreach(var dt in vv.Value)
                            {
                                sw.WriteLine(string.Format("{0},{1},{2},{3},{4}", dt.Code, dt.StatusName, dt.StartTime, dt.EndTime, dt.Duration));
                            }
                        }
                    }
                    _IBMain.Success();
                    Dispatcher.Invoke(() => MessageWindow.ShowMessage("数据导出成功！"));
                }
                catch (Exception ex)
                {
                    _IBMain.Warning($"导出数据出现错误：{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        private void Search()
        {
            if (_CurrentStationInfo == null) return;

            _lb.Items.Clear();


            var ur = $"{_Url}/api/windturbine/status-station?startTs={_tpstart.SelectedDateTime.GetTimeSpan()}&endTs={_tpend.SelectedDateTime.GetTimeSpan()}&stationId={this._CurrentStationInfo.Id}";


            Task.Run(search);

            void search()
            {
                try
                {
                    _IBMain.Inof("查询数据...");
                    var sts = _WEBHelper.HttpGetJSON<Dictionary<string, List<StatusTimeInfo>>>(ur);
                    _CurrentData = sts;
                    Dispatcher.Invoke(() =>
                    {
                        foreach (var v in sts)
                        {
                            StateInfo si = new StateInfo() { Width = _lb.ActualWidth - 20, ItemsTitle = v.Key, ItemsSource = v.Value };
                            _lb.Items.Add(si);
                        }
                    });
                    _IBMain.Success();
                }
                catch (Exception ex)
                {
                    _IBMain.Warning($"查询数据出现错误：{ex.Message}");
                }
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_StationInfos == null || _StationInfos.Count <= 0)
                {
                    _StationInfos = _StationManager.GetStationInfos().Where(s => s.Type == StationType.Wind).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取场站信息出错！", ex);
            }
            _TagManager.TagSwitched = TagSwitched;
            _TagManager.TagChanged?.Invoke(_StationInfos);
        }

        /// <summary>
        /// 标签切换
        /// </summary>
        private void TagSwitched(StationInfo si)
        {
            if (_CurrentStationInfo != null && (si == null || si.Id == _CurrentStationInfo.Id)) return;
            _CurrentStationInfo = si;
            Search();
        }
    }
}
