using CCDCount.DLL;
using CCDCount.DLL.SqlDataClass;
using CCDCount.MODEL.ConfigModel;
using CCDCount.MODEL.ShuLiModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CCDCountWpf.WpfPage
{
    /// <summary>
    /// HistoryDataPage.xaml 的交互逻辑
    /// </summary>
    public partial class HistoryDataPage : Page
    {
        private static ActionMesSqliteDataClass actionMesSqliteDataClass = null;
        int DataStartLine = 0;
        private int PageHeight = 2000;
        public HistoryDataPage()
        {
            InitializeComponent();
            DataContext = ShowMessageBus.ShowBinding;
            InitBatchItems();
            //UpDateShowBinding();
        }

        private void PreviousBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ShowMessageBus.ShowBinding.HistoryImageNum <= 1)
            {
                MessageBox.Show("已经是第一页");
                return;
            }
            ShowMessageBus.ShowBinding.HistoryImageNum -= 1;
            UpDateShowBinding();
        }

        private void NextBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ShowMessageBus.ShowBinding.HistoryImageNum >= ShowMessageBus.ShowBinding.HistoryImageCount)
            {
                MessageBox.Show("已经是最后一页");
                return;
            }
            ShowMessageBus.ShowBinding.HistoryImageNum += 1;
            UpDateShowBinding();
        }

        private void UpDateShowBinding()
        {
            if (actionMesSqliteDataClass == null)
            {
                return;
            }
            Stopwatch stopwatch = Stopwatch.StartNew();
            BitmapImage ShowBitMap = null;
            Bitmap BitmapImage = null;
            List<ActiveObjectClass> ShowResult = actionMesSqliteDataClass.GetActiveObjectForPage((ShowMessageBus.ShowBinding.HistoryImageNum - 1) * PageHeight + DataStartLine, ShowMessageBus.ShowBinding.HistoryImageNum * PageHeight + DataStartLine);
            if (ShowResult.Count > 0)
            {
                int ThisImageStartLine = (int)ShowResult.Min(o => o.StartLine);
                int ImageHeight = (int)(ShowResult.Max(o => o.LastSeenLine) - ShowResult.Min(o => o.StartLine))+50;
                int ImageWidth = ShowResult.Max(o => o.ImageWidth);
                BitmapImage = new Bitmap(ImageWidth, ImageHeight <= PageHeight ? PageHeight : ImageHeight);

                using (Graphics g = Graphics.FromImage(BitmapImage))
                {
                    g.Clear(System.Drawing.Color.White);

                    var redPen = new System.Drawing.Pen(System.Drawing.Color.Red, 1);
                    var bluePen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(0, 146, 255), 1);
                    var GreenPen = new System.Drawing.Pen(System.Drawing.Color.SeaGreen, 5);

                    foreach (var item in ShowResult)
                    {
                        int roix = item.MinStartCol - 5;
                        int roiy = (int)(item.StartLine - ThisImageStartLine) + 15;
                        int roiheight = (int)(item.LastSeenLine - (long)item.StartLine) + 10;
                        int roiwidth = item.MaxEndCol - item.MinStartCol + 10;
                        g.DrawRectangle(GreenPen, new System.Drawing.Rectangle(roix, roiy, roiwidth, roiheight));

                        Font font = new Font("Arial", 20);
                        g.DrawString(item.Num.ToString(), font, System.Drawing.Brushes.Black, new System.Drawing.Point(roix - 20 * item.Num.ToString().Length, roiy - 20));

                        foreach (var item1 in item.RowsData)
                        {
                            int yPos = (int)(item1.RowsCol - ThisImageStartLine + 20);
                            g.DrawLine(item.StateCode == 0 ? bluePen : redPen, new System.Drawing.Point(item1.StartCol, yPos), new System.Drawing.Point(item1.EndCol, yPos));
                        }
                    }
                }
            }
            else
            {
                BitmapImage = new Bitmap(4096, PageHeight);
                using (Graphics g = Graphics.FromImage(BitmapImage))
                {
                    g.Clear(System.Drawing.Color.White);
                }
            }
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                ShowBitMap = ConvertToBitmapImage(BitmapImage);
                ShowMessageBus.ShowBinding.HistoryImage = ShowBitMap;
            });
            stopwatch.Stop();
            Console.WriteLine($"{stopwatch.ElapsedMilliseconds}ms");
        }

        // Bitmap 转 BitmapImage 的辅助方法
        private BitmapImage ConvertToBitmapImage(Bitmap bitmap)
        {
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
                memory.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = memory;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }

        private void SkipBtn_Click(object sender, RoutedEventArgs e)
        {
            UpDateShowBinding();
        }

        /// <summary>
        /// 初始化批次列表
        /// </summary>
        private void InitBatchItems()
        {
            string folderPath = $"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{MessageBus.NowSettingLoadMainThread.cameraConfig.CamerNo}";
            if (!Directory.Exists(folderPath))
            {
                // 创建文件夹
                Directory.CreateDirectory(folderPath);
            }
            try
            {
                // 使用 DirectoryInfo 获取文件并按修改时间排序
                DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
                FileInfo[] files = dirInfo.GetFiles("*.db", SearchOption.AllDirectories);

                // 按照修改时间排序（最新的在前）
                var sortedFiles = files.OrderByDescending(f => f.LastWriteTime).ToArray();
                ShowMessageBus.ShowBinding.BatchItems.Clear();
                foreach (FileInfo file in sortedFiles)
                {
                    ShowMessageBus.ShowBinding.BatchItems.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name).Split('_')[1]);
                }
                BatchNumComBox.SelectedIndex = 0;
            }
            catch
            { }
        }

        /// <summary>
        /// 初始化批号列表
        /// </summary>
        private void InitBatchItems(DateTime Mintime, DateTime MaxTime)
        {
            string folderPath = $"{AppDomain.CurrentDomain.BaseDirectory}DATA\\BatchData";
            if (!Directory.Exists(folderPath))
            {
                // 创建文件夹
                Directory.CreateDirectory(folderPath);
            }
            try
            {
                // 使用 DirectoryInfo 获取文件并按修改时间排序
                DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
                FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

                // 按照修改时间排序（最新的在前）
                var sortedFiles = files.Where(f => f.CreationTime > Mintime && f.CreationTime < MaxTime.AddDays(1)).OrderByDescending(f => f.LastWriteTime).ToArray();
                ShowMessageBus.ShowBinding.BatchItems.Clear();
                foreach (FileInfo file in sortedFiles)
                {
                    ShowMessageBus.ShowBinding.BatchItems.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name).Split('_')[1]);
                }
                BatchNumComBox.SelectedIndex = 0;
            }
            catch
            { }
        }

        /// <summary>
        /// 初始化批号列表
        /// </summary>
        private void InitBatchItemsByMinTime(DateTime Mintime)
        {
            string folderPath = $"{AppDomain.CurrentDomain.BaseDirectory}DATA\\BatchData";
            if (!Directory.Exists(folderPath))
            {
                // 创建文件夹
                Directory.CreateDirectory(folderPath);
            }
            try
            {
                // 使用 DirectoryInfo 获取文件并按修改时间排序
                DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
                FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

                // 按照修改时间排序（最新的在前）
                var sortedFiles = files.Where(f => f.CreationTime > Mintime).OrderByDescending(f => f.LastWriteTime).ToArray();
                ShowMessageBus.ShowBinding.BatchItems.Clear();
                foreach (FileInfo file in sortedFiles)
                {
                    ShowMessageBus.ShowBinding.BatchItems.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name).Split('_')[1]);
                }
                BatchNumComBox.SelectedIndex = 0;
            }
            catch
            { }
        }

        /// <summary>
        /// 初始化批号列表
        /// </summary>
        private void InitBatchItemsByMaxTime(DateTime MaxTime)
        {
            string folderPath = $"{AppDomain.CurrentDomain.BaseDirectory}DATA\\BatchData";
            if (!Directory.Exists(folderPath))
            {
                // 创建文件夹
                Directory.CreateDirectory(folderPath);
            }
            try
            {
                // 使用 DirectoryInfo 获取文件并按修改时间排序
                DirectoryInfo dirInfo = new DirectoryInfo(folderPath);
                FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

                // 按照修改时间排序（最新的在前）
                var sortedFiles = files.Where(f => f.CreationTime < MaxTime.AddDays(1)).OrderByDescending(f => f.LastWriteTime).ToArray();
                ShowMessageBus.ShowBinding.BatchItems.Clear();
                foreach (FileInfo file in sortedFiles)
                {
                    ShowMessageBus.ShowBinding.BatchItems.Add(System.IO.Path.GetFileNameWithoutExtension(file.Name).Split('_')[1]);
                }
                BatchNumComBox.SelectedIndex = 0;
            }
            catch
            { }
        }

        private void BatchNumRecordMinTime_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BatchNumRecordMinTime.SelectedDate == null)
            {
                return;
            }
            else
            {
                if (BatchNumRecordMaxTime.SelectedDate == null)
                {
                    InitBatchItemsByMinTime((DateTime)BatchNumRecordMinTime.SelectedDate);
                }
                else
                {
                    InitBatchItems((DateTime)BatchNumRecordMinTime.SelectedDate, (DateTime)BatchNumRecordMaxTime.SelectedDate);
                }
            }
        }

        private void BatchNumRecordMaxTime_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BatchNumRecordMaxTime.SelectedDate == null)
            {
                return;
            }
            else
            {
                if (BatchNumRecordMinTime.SelectedDate == null)
                {
                    InitBatchItemsByMaxTime((DateTime)BatchNumRecordMaxTime.SelectedDate);
                }
                else
                {
                    InitBatchItems((DateTime)BatchNumRecordMinTime.SelectedDate, (DateTime)BatchNumRecordMaxTime.SelectedDate);
                }
            }
        }

        private void BatchNumRecordComBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BatchNumComBox.SelectedItem != null && BatchNumComBox.SelectedItem.ToString() != string.Empty)
            {
                string BatchNumber = BatchNumComBox.SelectedItem.ToString();
                actionMesSqliteDataClass = new ActionMesSqliteDataClass($"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{MessageBus.NowSettingLoadMainThread.cameraConfig.CamerNo}\\ActiveObjectData_{BatchNumber}.db");
                //actionMesSqliteDataClass = new ActionMesSqliteDataClass($"{AppDomain.CurrentDomain.BaseDirectory}DATA\\ActiveObjectData\\Cam{MessageBus.MainThreadS[0].cameraConfig.CamerNo}\\ActiveObjectData_20250908.db");
                actionMesSqliteDataClass.GetAllActionMinStartMaxEndLine(out int num, out int StartLine, out int EndLine);
                ShowMessageBus.ShowBinding.HistoryImageCount = (EndLine - StartLine) / PageHeight;
                DataStartLine = StartLine;
                ShowMessageBus.ShowBinding.HistoryImageNum = 1;
                UpDateShowBinding();
            }
        }
    }
}
