using System;
using Microsoft.Win32;
using System.Windows;
using System.ComponentModel;
using System.IO;
using MeterVision.model;
using System.Collections.Generic;
using OfficeOpenXml;
using MeterVision.db;
using System.Threading.Tasks;
using MeterVision.Dlg;

namespace MeterVision.Stand
{
    public partial class AddStandDialog : Window
    {
        //新增的TStand
        public TStand mTStand { get; set; }
        private List<TStandDetail> mStandDetailList;

        public AddStandDialog()
        {
            InitializeComponent();
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BtnImportExcel_Click(object sender, RoutedEventArgs e)
        {
            // 打开文件选择对话框
            var openFileDialog = new OpenFileDialog
            {
                //Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx",
                Filter = "Excel Files (*.xlsx)|*.xlsx",
                Title = "选择Excel文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 显示选择的文件名
                txtExcelFile.Text = openFileDialog.FileName;
                if(string.IsNullOrWhiteSpace(txtStandName.Text.Trim()))
                {
                    txtStandName.Text = ThisApp.GetFileNameWithoutExtension(txtExcelFile.Text.Trim());
                }
            }
        }

        // 当单选框的状态发生变化时，动态显示或隐藏Excel相关区域
        private void rbImportExcel_Checked(object sender, RoutedEventArgs e)
        {
            if (ExcelImportPanel != null)
            {
                ExcelImportPanel.Visibility = Visibility.Visible;
            }
        }

        private void rbCustomTemplate_Checked(object sender, RoutedEventArgs e)
        {
            if (ExcelImportPanel != null)
            {
                ExcelImportPanel.Visibility = Visibility.Collapsed;
            }
        }

        private async void BtnOK_Click(object sender, RoutedEventArgs e)
        {
            bool blGetData = false;
            string standName = txtStandName.Text.Trim();
            if (standName == string.Empty)
            {
                MessageBox.Show("请输入模板名称!");
                return;
            }

            mTStand = new TStand()
            {
                StandId = Guid.NewGuid().ToString(),
                StandName = standName,
                CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
                StandType = rbCustomTemplate.IsChecked == true ? 1 : 2
            };

            if(rbCustomTemplate.IsChecked == true)
            {
                blGetData = true;
            }
            else if (rbImportExcel.IsChecked == true)
            {
                string filePath = txtExcelFile.Text.Trim();
                if (string.IsNullOrWhiteSpace(filePath))
                {
                    MessageBox.Show(Application.Current.MainWindow, "请选择Excel文件！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                mTStand.StandFile = txtExcelFile.Text.Trim();
                //ImportExcel(filePath);
                bool blLoad = await LoadTStandDetailList();
                blGetData = blLoad;
            }  //IsChecked  

            //开始插入数据库操作
            if (blGetData)
            {
                bool blInsert = await InsertDataBase(mTStand, mStandDetailList);
                if (blInsert)
                {
                    this.DialogResult = true;
                    this.Close();
                }
            }
        }


        //插入数据库
        private async Task<bool> InsertDataBase(TStand stand,List<TStandDetail> standDetails)
        {
            bool blInsert = false;

            string titleInfo = "正在插入数据库，请稍候...";
            WaitWindow waitWindow = new WaitWindow(titleInfo)
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            waitWindow.Show();

            try
            {
                await Task.Run(() =>
                {
                    if (stand.StandType == 2)
                    {
                        blInsert = DBStand.InsertStandAndDetails(stand, standDetails);
                        if (blInsert) {
                            //获取不重复的站点
                            List<StationInfo> stationInfos = DBStand.GetUniqueStationInfo(stand.StandId);
                            blInsert = DBStation.InsertTStations(stationInfos);
                        }
                    }
                    else
                    {
                        blInsert = DBStand.InsertTStand(stand);
                    }
                });
            }
            catch(Exception ex)
            {
                MessageBox.Show($"插入数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                waitWindow.Close();
            }
            return blInsert;
        }


        //加载列表数据
        private async Task<bool> LoadTStandDetailList()
        {
            string titleInfo = "正在获取数据，请稍候...";
            WaitImportDlg waitWindow = new WaitImportDlg(titleInfo)
            {
                Owner = this,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            waitWindow.Show();

            try
            {
                await Task.Run(() => 
                {
                    ImportExcel(mTStand.StandFile,waitWindow);
                });
                // 如果mStandDetailList不为空，则表示导入成功
                return mStandDetailList != null && mStandDetailList.Count > 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, $"获取Excel数据失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            finally
            {
                waitWindow.Close();
            }
        }

        public void ImportExcel(string filePath,WaitImportDlg importDlg)
        {
            mStandDetailList = new List<TStandDetail>();

            Console.WriteLine($"正在读取文件: {filePath}");
            using (var package = new ExcelPackage(new FileInfo(filePath)))
            {
                Console.WriteLine($"工作表数量: {package.Workbook.Worksheets.Count}");
                //检查是否存在工作表
                if (package.Workbook.Worksheets.Count == 0)
                {
                    throw new InvalidOperationException("Excel文件中没有工作表。");
                }

                // 获取第一个工作表
                var worksheet = package.Workbook.Worksheets[1];

                // 获取总行数
                int rowCount = worksheet.Dimension?.Rows ?? 0;
                Console.WriteLine($"行数: {rowCount}");

                importDlg.PrgCount = rowCount;

                // 遍历每一行
                for (int row = 2; row <= rowCount; row++) // 假设第一行是标题行
                {
                    importDlg.PrgIndex = row;
                    //判断图像是否符合要求的规格
                    string srcImage = worksheet.Cells[row, 1].Text.Trim();
                    if (!ThisApp.IsImageDimensionsValid(srcImage))
                    {
                        continue;
                    }

                    var standDetail = new TStandDetail
                    {
                        StandDetailId = Guid.NewGuid().ToString(),
                        CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
                        StandId = mTStand.StandId,
                        // 读取图像路径（假设图像路径在A列）
                        SrcImage = worksheet.Cells[row, 1].Text.Trim(),
                        // 读取标准答案（假设标准答案在B列）
                        StandValue = worksheet.Cells[row, 2].Text.Trim(),
                        DeviceSn = worksheet.Cells[row, 3].Text.Trim(),
                        StationId = worksheet.Cells[row, 4].Text.Trim(),
                        SampleTime = worksheet.Cells[row, 5].Text.Trim(),
                        ENumCount = ThisApp.ConvertToInt(worksheet.Cells[row, 6].Text.Trim()),
                        ELastUnit = ThisApp.ConvertToInt(worksheet.Cells[row, 7].Text.Trim())
                    };
                    // 添加到结果列表
                    mStandDetailList.Add(standDetail);
                }
            }
        }

        //-------------------------------------------------------------
    }
}
