using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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 System.IO;
using Microsoft.Win32;
using System.ComponentModel;
using MeterVision.model;

namespace MeterVision.Single
{
    /// <summary>
    /// UCSingleMain.xaml 的交互逻辑
    /// </summary>
    public partial class UCSingleMain : UserControl, INotifyPropertyChanged
    {
        private const int COLUMN_RIGHT_WIDTH = 400;

        private bool RightVisiable = true;  //表示右侧的显示状态

        public event PropertyChangedEventHandler PropertyChanged;

        //private SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private void InitRightControls(SingleDetailItem PatchDetailItem)
        {
            pnlImage.Visibility =
                PatchDetailItem == null ? Visibility.Collapsed : Visibility.Visible;
            pnlLog.Visibility =
                PatchDetailItem == null ? Visibility.Collapsed : Visibility.Visible;
            txtRightItemIndex.Visibility =
                PatchDetailItem == null ? Visibility.Collapsed : Visibility.Visible;
        }

        public UCSingleMain()
        {
            InitializeComponent();

            ucSingleGrid.OnSelectedSingDetailItemChanged += UcSingleGrid_OnSelectedSingDetailItemChanged;
            InitRightControls(null);

            this.DataContext = this;

            //控制右侧栏目的显示
            RightVisiable = true;
            ChangeRightVisiable(RightVisiable);
        }


        private void UcSingleGrid_OnSelectedSingDetailItemChanged(object sender, SingleDetailItemChangedEventArgs e)
        {
            InitRightControls(e.SelectedSingleDetailItem);
            ucImagerSource.ImageName = "原始图片";
            ucImageResult.ImageName = "结果图片";
            txtRightItemIndex.Text = string.Empty;
            
            if (e.SelectedSingleDetailItem != null)
            {
                ucImagerSource.ImageSource = e.SelectedSingleDetailItem.SrcImage;
                ucImageResult.ImageSource = e.SelectedSingleDetailItem.DstImage;
                SetLogContent(e.SelectedSingleDetailItem);

                txtRightItemIndex.Text = $"{e.SelectedSingleDetailItem.Index}.";
            }
            //else
            //{
            //    ucImagerSource.ImageSource = null;
            //    ucImageResult.ImageSource = null;
            //}
        }

        private void BtnAddRow_Click(object sender, RoutedEventArgs e)
        {
            if(ucSingleGrid.SingleDetailItemList.Count > 0)
            {
                ucSingleGrid.SingleDetailItemList[0].RunFlag = 1;
            }
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许数字输入
            e.Handled = !Regex.IsMatch(e.Text, @"^\d$");
        }

        private void BtnSelectImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置对话框的标题
            openFileDialog.Title = "选择待识别的JPG文件";

            // 设置默认文件夹（可选）
            //openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // 设置过滤器，以便只显示特定类型的文件（可选）
            //openFileDialog.Filter = "图片文件 (*.jpg)|*.jpg|所有文件 (*.*)|*.*";
            openFileDialog.Filter = "图片文件 (*.jpg, *.bmp)|*.jpg;*.bmp";    //|所有文件 (*.*)|*.*";

            // 显示对话框并检查用户是否点击了“确定”
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取所选文件的全路径
                string filePath = openFileDialog.FileName;

                //判断文件是否合理
                if ( (ThisApp.IsJpgFile(filePath) || ThisApp.IsBmpFile(filePath) ) && 
                    ThisApp.IsFileSizeValid(filePath) && 
                    ThisApp.IsImageDimensionsValid(filePath))
                {
                    //ucSingleGrid.InsertFilesWithProgress(new List<string>() { filePath });
                    ucSingleGrid.DragRecong(filePath);
                }
                else
                {
                    MessageBox.Show(Application.Current.MainWindow,
                        "图片不符合要求。", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private void BtnSingleDetailFirstPage_Click(object sender, RoutedEventArgs e)
        {
            ucSingleGrid.FirstPage();
        }

        private void BtnSingleDetailPrePage_Click(object sender, RoutedEventArgs e)
        {
            ucSingleGrid.PrePage();
        }

        private void BtnSingleDetailNextPage_Click(object sender, RoutedEventArgs e)
        {
            ucSingleGrid.NextPage();
        }

        private void BtnSingleDetailLastPage_Click(object sender, RoutedEventArgs e)
        {
            ucSingleGrid.LastPage();
        }

        private void BtnSingleDetailSpeciPage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int pageNumber = int.Parse(txtSingleDetailPageNumber.Text.ToString());
                ucSingleGrid.SpeciPage(pageNumber);
            }
            catch
            {

            }
        }

        private void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            ucSingleGrid.RefreshData();
        }


        private async void SetLogContent(SingleDetailItem detailItem)
        {
            if (detailItem != null && File.Exists(detailItem.LogPath))
            {
                LogRichTextBox.Document.Blocks.Clear();
                await Task.Run(() =>
                {
                    string content = File.ReadAllText(detailItem.LogPath);
                    content = $"{detailItem.Index}. {detailItem.LogPath}\n\n{content}";
                    Dispatcher.Invoke(() =>
                    {
                        LogRichTextBox.ScrollToHome();
                        Paragraph logParagraph = new Paragraph(new Run(content));
                        LogRichTextBox.Document.Blocks.Add(logParagraph);
                    });
                });
            }
        }

        private void LogScrollTop_Click(object sender, RoutedEventArgs e)
        {
            LogRichTextBox.ScrollToHome();
        }

        private void LogScrollMiddle_Click(object sender, RoutedEventArgs e)
        {

        }

        private void LogScrollBottom_Click(object sender, RoutedEventArgs e)
        {

            LogRichTextBox.ScrollToEnd();
        }

        private void BtnClearAll_Click(object sender, RoutedEventArgs e)
        {
            //清空所有数据
            ucSingleGrid.ClearAllSingleDetail();
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void BtnRightCtl_Click(object sender, RoutedEventArgs e)
        {
            bool visiable = !RightVisiable;
            ChangeRightVisiable(visiable);
        }

        private void ChangeRightVisiable(bool visiable)
        {
            RightVisiable = visiable;
            colRight.Width = new GridLength(visiable ? COLUMN_RIGHT_WIDTH : 0);
            btnRightCtl.Content = visiable ? "▶️" : "◀️";
            btnRightCtl.ToolTip = visiable ? "点击隐藏右侧栏" : "点击显示右侧栏";
        }
        ////////////////////////////////////////////////////
    }
}
