using HslCommunication;
using HslCommunication.MQTT;
using MWS.Data.InterFace;
using MWS.Data.Manager;
using MWS.Library;
using MWS.Library.Common;
using MWS.Model;
using MWS.Model.Dto;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
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;
using Visifire.Charts;

namespace MWS.Domain.View.RealTime
{
    /// <summary>
    /// SixCarRealTimePage.xaml 的交互逻辑
    /// </summary>
    public partial class SixCarRealTimePage : Page
    {
        private IWeight weightManage;
        private IDevice deviceManage;
        private ITeam teamManage;
        private IEntrance entranceManage;
        private int entranceId = 0;
        private int deviceId = 0;
        private int teamId = 0;
        private DateTime startTime;
        private DateTime endTime;
        private Chart chart;
        public MqttClient _mqttClient;
        private List<Device> devices;
        private List<Zigbee> zigbees;
        private IZigbee zigbeeManager;
        public SixCarRealTimePage()
        {
            InitializeComponent();
            weightManage = new WeightManager();
            deviceManage = new DeviceManager();
            teamManage = new TeamManager();
            entranceManage = new EntranceManager(); 
            zigbeeManager = new ZigbeeManager();
            zigbees = zigbeeManager.GetAll(deviceId);
            #region MQTT
            var mqttPort = ConfigurationManager.AppSettings["MqttPort"];
            _mqttClient = new MqttClient(new MqttConnectionOptions
            {
                ClientId = Guid.NewGuid().ToString("N").ToUpper(),
                IpAddress = "127.0.0.1",
                Port = mqttPort.ToInt(),
            });
            var operateResult = _mqttClient.ConnectServer();
            if (!operateResult.IsSuccess)
            {
                LogHelper.WriteLog("MQTT服务连接失败！错误：" + operateResult.Message);
            }
            else
            {
                var subscribeResult = _mqttClient.SubscribeMessage(new string[] { "WeightRealTimeData1", "WeightRealTimeData3", "WeightRealTimeData4", "WeightRealTimeData5", "WeightRealTimeData6", "WeightRealTimeData7", "WeighingData", "ZigbeeState" });
                if (!subscribeResult.IsSuccess)
                {
                    LogHelper.WriteLog("订阅主题失败！Message:" + subscribeResult.Message);
                }
                _mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived;
                _mqttClient.OnNetworkError += MqttClient_OnNetworkError;
            }
            #endregion
        }

        private void MqttClient_OnMqttMessageReceived(MqttClient client, string topic, byte[] payload)
        {

            string changeRealTimeJson;
            switch (topic)
            {
                case "WeightRealTimeData1":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeightRealTimeData3":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeightRealTimeData4":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeightRealTimeData5":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeightRealTimeData6":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeightRealTimeData7":
                    changeRealTimeJson = Encoding.UTF8.GetString(payload);
                    BindData(changeRealTimeJson);
                    break;
                case "WeighingData":
                    var changeWeightJson = Encoding.UTF8.GetString(payload);
                    ChartBindData(changeWeightJson);
                    break;
                case "ZigbeeState":
                    var zigbeeStateJson = Encoding.UTF8.GetString(payload);
                    BindDataState(zigbeeStateJson);
                    break;

            }
            //BindData();
        }
        /// <summary>
        /// 实时重量稳定信号超载信号
        /// </summary>
        /// <param name="changTags"></param>
        public void BindData(string changTags)
        {
            JObject tagObject;
            if (changTags != null)
            {
                tagObject = JObject.Parse(changTags.ToString());
                int tempDeviceId = tagObject.GetValue("DeviceId").ToSafeInt();
                double netWeight = Convert.ToDouble(tagObject.GetValue("NetWeight"));
                bool overLoad = Convert.ToBoolean(tagObject.GetValue("OverLoad"));
                bool isSteady = Convert.ToBoolean(tagObject.GetValue("IsSteady"));
                bool state = Convert.ToBoolean(tagObject.GetValue("State"));
                //Console.WriteLine(changTags);
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                {
                    switch (tempDeviceId)
                    {
                        case 1:
                            tbRealTime1.Text = netWeight.ToString();
                           
                            if (overLoad)
                            {
                                brOverLoad1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        case 3:
                            tbRealTime2.Text = netWeight.ToString();
                           
                            if (overLoad)
                            {
                                brOverLoad2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        case 4:
                            tbRealTime3.Text = netWeight.ToString();
                           
                            if (overLoad)
                            {
                                brOverLoad3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        case 5:
                            tbRealTime4.Text = netWeight.ToString();
                            
                            if (overLoad)
                            {
                                brOverLoad4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        case 6:
                            tbRealTime5.Text = netWeight.ToString();
                            
                            if (overLoad)
                            {
                                brOverLoad5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        case 7:
                            tbRealTime6.Text = netWeight.ToString();
                            
                            if (overLoad)
                            {
                                brOverLoad6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            else
                            {
                                brOverLoad6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            if (isSteady)
                            {
                                brSteady6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                brSteady6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#90919E"));
                            }
                            break;
                        default:
                            break;
                    }
                    
                }));
            }
        }
        /// <summary>
        /// 通讯状态变化
        /// </summary>
        /// <param name="changTags"></param>
        public void BindDataState(string changTags)
        {
            JObject tagObject;
            if (changTags != null)
            {
                tagObject = JObject.Parse(changTags.ToString());
                int tempDeviceId = tagObject.GetValue("DeviceId").ToSafeInt();
                bool state = Convert.ToBoolean(tagObject.GetValue("State"));
                Console.WriteLine(changTags);
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                {
                    switch (tempDeviceId)
                    {
                        case 1:
                            if (state)
                            {
                                commStatus1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus1.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            break;
                        case 3:
                            if (state)
                            {
                                commStatus2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus2.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                           
                            break;
                        case 4:
                            if (state)
                            {
                                commStatus3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus3.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                           
                            break;
                        case 5:
                            if (state)
                            {
                                commStatus4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus4.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                           
                            break;
                        case 6:
                            if (state)
                            {
                                commStatus5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus5.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            
                            break;
                        case 7:
                            if (state)
                            {
                                commStatus6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#4BD77B"));
                            }
                            else
                            {
                                commStatus6.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F2465F"));
                            }
                            
                            break;
                        default:
                            break;
                    }

                }));
            }
        }
        private void MqttClient_OnNetworkError(object sender, EventArgs e)
        {
            // 当网络异常的时候触发，可以在此处重连服务器
            if (sender is MqttClient client)
            {
                // 开始重连服务器，直到连接成功为止
                Console.WriteLine("网络异常，准备5秒后重新连接。");
                while (true)
                {
                    // 每隔5秒重连
                    Thread.Sleep(5000);
                    Console.WriteLine("准备重新连接服务器...");
                    OperateResult connect = client.ConnectServer();
                    if (connect.IsSuccess)
                    {
                        var subscribeResult = _mqttClient.SubscribeMessage(new string[] { "SwitchTagChange", "ValueTagChange", "TeamChange", "WeighingData" });
                        if (!subscribeResult.IsSuccess)
                        {
                            LogHelper.WriteLog("订阅主题失败！Message:" + subscribeResult.Message);
                        }
                        // 连接成功后，可以在下方break之前进行订阅，或是数据初始化操作
                        Console.WriteLine("连接服务器成功！");
                        break;
                    }
                    Console.WriteLine("连接失败，准备5秒后重新连接。");
                }
            }
        }


        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            startTime = DateTime.Now.AddDays(-1);
            endTime = DateTime.Now;
            devices = deviceManage.GetAll();
            foreach (var item in zigbees)
            {
                switch (item.Id)
                {
                    case 1:
                        tbCaranName1.Text = item.Name;
                        break;
                    case 2:
                        tbCaranName2.Text = item.Name;
                        break;
                    case 3:
                        tbCaranName3.Text = item.Name;
                        break;
                    case 4:
                        tbCaranName4.Text = item.Name;
                        break;
                    case 5:
                        tbCaranName5.Text = item.Name;
                        break;
                    case 6:
                        tbCaranName6.Text = item.Name;
                        break;
                    default:
                        break;
                }
                GetListData(item.Id);
            }
            
        }
        /// <summary>
        /// 图表绑定
        /// </summary>
        /// <param name="changTags"></param>
        private void ChartBindData(string changTags)
        {
            JObject tagObject;
            if (changTags != null)
            {
                tagObject = JObject.Parse(changTags.ToString());
                int tempDeviceId = tagObject.GetValue("DeviceId").ToSafeInt();
                double netWeight = Convert.ToDouble(tagObject.GetValue("NetWeight"));
                int teamId = tagObject.GetValue("TeamId").ToSafeInt();
                bool isSteady = Convert.ToBoolean(tagObject.GetValue("IsSteady"));
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() =>
                {
                    GetListData(tempDeviceId);
                }));
            }
        }
        private void GetListData(int deviceId)
        {
            endTime = DateTime.Now.AddMinutes(1);
            List<RecordDto> details = weightManage.GetChartRecords(1, deviceId, 1, startTime, endTime);
            switch (deviceId)
            {
                case 1:
                    tbTotalWeight1.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                case 2:
                    tbTotalWeight2.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                case 3:
                    tbTotalWeight3.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                case 4:
                    tbTotalWeight4.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                case 5:
                    tbTotalWeight5.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                case 6:
                    tbTotalWeight6.Text = details.Sum(c => c.NetWeight).ToString();
                    break;
                default:
                    break;
            }
            CreateChartColumn(deviceId,"", details);
         
        }
        public void CreateChartColumn(int deviceId,string name, List<RecordDto> details)
        {
            //创建一个图标
            chart = new Chart();

            //设置图标的宽度和高度
            chart.Width = 550;
            chart.Height = 295;
            //chart.Margin = new Thickness(5, 5, 5, 5);
            //是否启用打印和保持图片
            chart.ToolBarEnabled = true;

            //设置图标的属性
            chart.ScrollingEnabled = false;//是否启用或禁用滚动
            chart.View3D = false;//3D效果显示

            //创建一个标题的对象
            Title title = new Title();

            //设置标题的名称
            title.Text = name;
            title.Padding = new Thickness(0, 10, 5, 0);

            //向图标添加标题
            chart.Titles.Add(title);

            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            //设置图表中Y轴的后缀          
            yAxis.Suffix = "T";
            chart.AxesY.Add(yAxis);

            // 创建一个新的数据线。               
            DataSeries dataSeries = new DataSeries();

            // 设置数据线的格式
            dataSeries.RenderAs = RenderAs.Spline;
            //RenderAs图标类型： 柱形图(Column) 曲线图(Line)折线图(Step Line)饼图(Pie)横道图(Bar)区域图(Area)环形图(Doughnut)堆积柱形图(Stacked Column)100 % 堆积柱形图(100 % Stacked Column)
            //堆积道图(Stacked Bar)100 % 堆积横道图(100 % Stacked Bar)堆积区域图(Stacked Area)100 % 堆积区域图(100 Stacked Area)气泡图(Bubble)散射图(Point)+
            //流线漏斗图(StreamLineFunnel)漏斗图(Section Funnel)阴阳烛图(CandleStick)股票图(Stock)极区图(Line)雷达图(Radar)光滑曲线图(Spline)高密度曲线图(QuickLine)


            // 设置数据点              
            DataPoint dataPoint;
            foreach (var item in details)
            {
                dataPoint = new DataPoint();
                // 设置X轴点                    
                //dataPoint.AxisXLabel = item.Time.ToString();
                //设置Y轴点                   
                dataPoint.YValue = double.Parse(item.NetWeight.ToString());
                //添加一个点击事件        
                //dataPoint.MouseLeftButtonDown += new MouseButtonEventHandler(dataPoint_MouseLeftButtonDown);
                //添加数据点                   
                dataSeries.DataPoints.Add(dataPoint);
            }

            //for (int i = 0; i < valuex.Count; i++)
            //{
            //    // 创建一个数据点的实例。                   
            //    dataPoint = new DataPoint();
            //    // 设置X轴点                    
            //    dataPoint.AxisXLabel = valuex[i];
            //    //设置Y轴点                   
            //    dataPoint.YValue = double.Parse(valuey[i]);
            //    //添加一个点击事件        
            //    //dataPoint.MouseLeftButtonDown += new MouseButtonEventHandler(dataPoint_MouseLeftButtonDown);
            //    //添加数据点                   
            //    dataSeries.DataPoints.Add(dataPoint);
            //}

            // 添加数据线到数据序列。                
            chart.Series.Add(dataSeries);

            //将生产的图表增加到Grid，然后通过Grid添加到上层Grid.           
            Grid gr = new Grid();
            gr.Children.Add(chart);
            switch (deviceId)
            {
                case 1:
                    this.chat1.Children.Add(gr);
                    break;
                case 2:
                    this.chat2.Children.Add(gr);
                    break;
                case 3:
                    this.chat3.Children.Add(gr);
                    break;
                case 4:
                    this.chat4.Children.Add(gr);
                    break;
                case 5:
                    this.chat5.Children.Add(gr);
                    break;
                case 6:
                    this.chat6.Children.Add(gr);
                    break;
                default:
                    break;
            }
          
            
        }


        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {

        }
    }
}
