using Modbus.Device;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
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.Data;
using static 头罩视野.TestDataStore;

namespace 头罩视野.Views
{
   
    /// <summary>
    /// RecordPage.xaml 的交互逻辑
    /// </summary>
    public partial class RecordPage : Page
    {
        //长按清除
        private bool _isClearPressed = false;
        private Thread _clearThread;
        private IModbusMaster _modbusMaster => ModbusResourceManager.Instance.ModbusMaster;

        public RecordPage()
        {
            InitializeComponent();
        }

        //#region 2. 清除表格数据
        //private void btnClear_Click(object sender, RoutedEventArgs e)
        //{
        //    // 确认清除
        //    if (MessageBox.Show("确定要清除所有记录吗？", "确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        //    {
        //        TestDataStore.Records.Clear();
        //        RecordDataGrid.ItemsSource = null;
        //        RecordDataGrid.ItemsSource = TestDataStore.Records;
        //    }
        //}

        //清除
        private void btnClear_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _isClearPressed = true;
            _clearThread = new Thread(() =>
            {
                Thread.Sleep(500); // 长按1秒触发
                if (_isClearPressed)
                {
                    Application.Current.Dispatcher.Invoke(() => ClearAllData());
                }
            });
            _clearThread.Start();
        }
        // 清除所有数据
        private void ClearAllData()
        {
            TestDataStore.Records.Clear();
            RecordDataGrid.ItemsSource = null;
            RecordDataGrid.ItemsSource = TestDataStore.Records;

            MessageBox.Show("数据已清除");
        }

        private void btnClear_MouseUp(object sender, MouseButtonEventArgs e)
        {
            _isClearPressed = false;
            _clearThread?.Join(100); // 等待线程结束最多100毫秒，然后强制结束
        }
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            //_plcReadTimer?.Stop();
            //_plcReadTimer?.Dispose();
            //_modbusMaster?.Dispose();
            //ModbusHelper.TcpClient?.Close();

        }

        //#endregion
        //#region 3. 保存为Excel
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                // 1. 构建表格内容
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("编号,日期,时间,左目视野面积,右目视野面积,双目视野面积,空白视野面积,下方视野,视野保存率");

                foreach (var item in TestDataStore.Records)
                {
                    sb.AppendLine($"{item.Id},{item.Date},{item.Time},{item.LeftEyeArea},{item.RightEyeArea},{item.BinocularArea},{item.LowerVision},{item.VisionRetentionRate}");
                }

                // 2. 弹出保存框，让用户自己选位置
                Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv|所有文件 (*.*)|*.*";
                saveFileDialog.FileName = $"测试记录_{DateTime.Now:yyyyMMddHHmmss}";

                if (saveFileDialog.ShowDialog() == true)
                {
                    // 3. 保存文件
                    File.WriteAllText(saveFileDialog.FileName, sb.ToString(), Encoding.UTF8);
                    MessageBox.Show("保存成功！\n文件路径：" + saveFileDialog.FileName, "成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败：" + ex.Message);
            }
        }
        //#endregion

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //进入页面是否要保留原来的数据？？？？，
            RecordDataGrid.ItemsSource = null;
            RecordDataGrid.ItemsSource = TestDataStore.Records;
            // 判断连接
            if (!ModbusHelper.IsConnected)
            {
                MessageBox.Show("未连接");
                return;
            }

            // 获取客户端
            //var client = ModbusHelper.TcpClient;
            


        }

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