
using System;
using System.Collections.Generic;
using Modbus.Device;
using System.Net.Sockets;
using System.Text;
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 System.Windows.Threading;
using 头罩视野.Services;
using 头罩视野.Services.Data;

namespace 头罩视野.Views
{
    public partial class VisiData : Page
    {

        private IModbusMaster _modbusMaster => ModbusResourceManager.Instance.ModbusMaster;
        DispatcherTimer _timer;
        DataChange c = new DataChange();
        Function ma ;
        public VisiData()
        {
            InitializeComponent();
 
            _timer = InitDispatcherTimer();


            // 判断连接
            if (!ModbusHelper.IsConnected)
            {
                MessageBox.Show("未连接");
                return;
            }

        }
        //复位btn
        private void Button_Click_Reset(object sender, RoutedEventArgs e)
        {
            btnLeft.Content = "左眼开";
            btnRight.Content = "右眼开";
            ma.BtnClickFunction(Function.ButtonType.复归型, 90);
        }
        //左开眼
        private void Button_Click_left(object sender, RoutedEventArgs e)
        {
            // 切换文案：左眼开 ↔ 左眼关
            if (btnLeft.Content.ToString() == "左眼开")
            {
                btnLeft.Content = "左眼关";
                if (btnRight.Content.ToString() == "右眼关")
                {
                    btnRight.Content = "右眼开";
                    ma.BtnClickFunction(Function.ButtonType.切换型, 1);

                }
            }
            else
            {
                btnLeft.Content = "左眼开";
            }
            ma.BtnClickFunction(Function.ButtonType.切换型, 0);
        }
        //右开眼
        private void Button_Click_Right(object sender, RoutedEventArgs e)
        {    // 切换文案：左眼开 ↔ 左眼关
            if (btnRight.Content.ToString() == "右眼开")
            {
                btnRight.Content = "右眼关";
                if (btnLeft.Content.ToString() == "左眼关")
                {
                    btnLeft.Content = "左眼开";
                    ma.BtnClickFunction(Function.ButtonType.切换型, 0);

                }
            }
            else
            {
                btnRight.Content = "右眼开";
            }
            ma.BtnClickFunction(Function.ButtonType.切换型, 1);
        }


        private async void Button_Click_ResDown(object sender, MouseButtonEventArgs e)
        {
            await _modbusMaster.WriteSingleCoilAsync(1, 10, true);
            System.Diagnostics.Debug.WriteLine("反转开始");
        }

        private async void Button_Click_ResUp(object sender, MouseButtonEventArgs e)
        {
            await _modbusMaster.WriteSingleCoilAsync(1, 10, false);
            System.Diagnostics.Debug.WriteLine("反转结束");

        }
        //正转

        private async void Button_Click_ForDown(object sender, MouseButtonEventArgs e)
        {
            await _modbusMaster.WriteSingleCoilAsync(1, 11, true);
        }

        private async void Button_Click_ForUp(object sender, MouseButtonEventArgs e)
        {

            await _modbusMaster.WriteSingleCoilAsync(1, 11, false);
            //System.Diagnostics.Debug.WriteLine("正传end");
        }


        //读取数据
        private DispatcherTimer InitDispatcherTimer()
        {
            var timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(500)
            };
            timer.Tick += async (s, e) =>
            {
                if (_modbusMaster != null)
                {
                    try
                    {
                        await ReadAddr262DataAsync();
                    }
                    catch { }
                }
            };
            return timer;
        }

        private async System.Threading.Tasks.Task ReadAddr262DataAsync()
        {
            try
            {
                // 创建任务列表
                var tasks = new List<Task>
                {
                    //ReadAndUpdateFloatAsync(350, 1, c, "F2", ""),
                    //ReadAndUpdateFloatAsync(351, 1, sdtsj2, "F2", ""),
                    //ReadAndUpdateFloatAsync(352, 1, sdtsj3, "F2", ""),
                    //ReadAndUpdateFloatAsync(353, 1, sdtsj4, "F2", ""),
                    //ReadAndUpdateFloatAsync(354, 1, sdtsj5, "F2", ""),
                    //ReadAndUpdateFloatAsync(355, 1, xdtsj1, "F2", " "),
                    //ReadAndUpdateFloatAsync(356, 1, xdtsj2, "F2", " "),
                    //ReadAndUpdateFloatAsync(357, 1, xdtsj3, "F2", " "),
                    //ReadAndUpdateFloatAsync(358, 1, xdtsj4, "F2", " "),
                    //ReadAndUpdateFloatAsync(359, 1, xdtsj5, "F2", " "),
                    //ReadAndUpdateFloatAsync(360, 1, zdtsj1, "F2", " "),
                    //ReadAndUpdateFloatAsync(361, 1, zdtsj2, "F2", " "),
                    //ReadAndUpdateFloatAsync(362, 1, zdtsj3, "F2", " "),
                    //ReadAndUpdateFloatAsync(363, 1, zdtsj4, "F2", " "),
                    //ReadAndUpdateFloatAsync(364, 1, zdtsj5, "F2", " "),

                    ReadAndUpdateFloatAsync(212, 2, zymjxs, "F2", ""),
                    ReadAndUpdateFloatAsync(214, 2, yymjxs, "F2", ""),
                    ReadAndUpdateFloatAsync(428, 2, bcjzxs, "F2", ""),
                    ReadAndUpdateFloatAsync(340,2, fwbc, "F2", " "),
                    ReadAndUpdateFloatAsync(330,2, djxw, "F2", " "),
                    ReadAndUpdateFloatRangeAsync(350, 15, "F2", ""),
                };

                await Task.WhenAll(tasks);
            }
            catch (Exception ex)
            {
                ShowError($"读取数据失败：{ex.Message}");
            }
        }



        private async Task ReadAndUpdateFloatRangeAsync(int address, int length, string format, string unit)
        {
            try
            {
                ushort[] registers = await Task.Run(async () =>
                   await _modbusMaster!.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length)
                );

                if (registers != null && registers.Length >= 2)
                {
                    var controls = new TextBox[]
                     {
                        sdtsj1, sdtsj2, sdtsj3, sdtsj4, sdtsj5,
                        xdtsj1, xdtsj2, xdtsj3, xdtsj4, xdtsj5,
                        zdtsj1, zdtsj2, zdtsj3, zdtsj4, zdtsj5
                     };

                    // 一次在UI线程批量更新，避免多次Invoke阻塞0
                    await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        for (int i = 0; i < controls.Length; i++)
                        {
                            // 因为你这里是1个寄存器=1个值，所以直接用registers[i]
                            controls[i].Text = registers[i].ToString(format);
                        }
                    }), DispatcherPriority.Background);
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取地址{address}失败：{ex.Message}");
            }
        }

        // 地址，  根据格式显示字符长度  32：2 16：1  ，绑定页面的name 值，F2 保留两位小数，单位
        private async Task ReadAndUpdateFloatAsync(int address, int length, System.Windows.Controls.TextBox control, string format, string unit)
        {
            try
            {
                ushort[] registers = await Task.Run(async () =>
                   await _modbusMaster.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length)
                );

                if (registers != null && registers.Length >= 2)
                {
                    float value = c.UshortToFloat(registers[1], registers[0]);
                    Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
                }
                else if (registers != null && registers.Length >= 1)
                {
                    int value = registers[0];
                    Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取地址{address}失败：{ex.Message}");
            }
        }

        private async Task ReadAndUpdateFloatAsync(int address, int length, System.Windows.Controls.TextBlock control, string format, string unit)
        {
            try
            {
                ushort[] registers = await Task.Run(async () =>
                   await _modbusMaster.ReadHoldingRegistersAsync(1, (ushort)address, (ushort)length)
                );

                if (registers != null && registers.Length >= 2)
                {
                    float value = c.UshortToFloat(registers[1], registers[0]);
                    Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
                }
                else if (registers != null && registers.Length >= 1)
                {
                    int value = registers[0];
                    Dispatcher.Invoke(() => control.Text = value.ToString(format) + unit);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取地址{address}失败：{ex.Message}");
            }
        }

        private async Task ReadAndUpdateIntAsync(int address, int length, System.Windows.Controls.Control control, string format)
        {
            try
            {
                ushort[] registers = await Task.Run(() =>
                   _modbusMaster.ReadHoldingRegisters(1, (ushort)address, (ushort)length)
                );

                if (registers != null && registers.Length >= 1)
                {
                    int value = registers[0];
                    Dispatcher.Invoke(() =>
                    {
                        if (control is System.Windows.Controls.ContentControl contentControl)
                            contentControl.Content = value.ToString(format);
                        else if (control is System.Windows.Controls.TextBox textBox)
                            textBox.Text = value.ToString(format);
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"读取地址{address}失败：{ex.Message}");
            }
        }

        private void ShowError(string msg) => MessageBox.Show(msg, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        private void GoHome(object s, RoutedEventArgs e) => NavigationService.Content = null;
        private void GoTest(object s, RoutedEventArgs e) => NavigationService.Content = new Views.PageTest();
        private void GoRecord(object s, RoutedEventArgs e) => NavigationService.Content = new Views.RecordDate();
        private void GoView(object s, RoutedEventArgs e) => NavigationService.Content = new Views.RecordPage();
        
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
           

            _timer.Start();

            ma = new Function(_modbusMaster);
            c = new DataChange();
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            
            _timer?.Stop();

        }
      
    }
}
