using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using 材料热传导系数;

namespace 全自动水压检测仪
{
    public partial class ScanImport : UIForm
    {
        private NormalTemperatureMode _normalTemperatureMode;

        private ConductivityRepository _repository;
        public ScanImport()
        {
            InitializeComponent();
            _repository = new ConductivityRepository();
            uiDataGridView1.AutoGenerateColumns = false;
        }

        private void SafeInvoke(Action action)
        {
            if (action == null) return;

            // 检查窗体是否已释放/句柄是否创建
            if (this.IsDisposed || !this.IsHandleCreated)
            {
                System.Diagnostics.Debug.WriteLine("ScanImport窗体已释放或句柄未创建，跳过UI操作");
                return;
            }

            try
            {
                // 如果已经在UI线程，直接执行；否则Invoke
                if (this.InvokeRequired)
                {
                    this.Invoke(action);
                }
                else
                {
                    action();
                }
            }
            catch (ObjectDisposedException ex)
            {
                System.Diagnostics.Debug.WriteLine($"ScanImport UI操作时控件已释放: {ex.Message}");
            }
            catch (InvalidOperationException ex)
            {
                System.Diagnostics.Debug.WriteLine($"ScanImport UI操作异常: {ex.Message}");
            }
        }


        private void save_Click(object sender, EventArgs e)
        {
            SafeInvoke(() =>
            {
                float diffpressure = 0, exit_temperature = 0, dwelltime = 0, temperature = 0;
                float pressureDifference = 0; decimal standardError = 0;
                int quantity = 0;

                float.TryParse(uiTextBox4?.Text ?? "", out diffpressure);
                float.TryParse(uiTextBox9?.Text ?? "", out exit_temperature);
                float.TryParse(uiTextBox5?.Text ?? "", out dwelltime);
                float.TryParse(uiTextBox1?.Text ?? "", out temperature);
                float.TryParse(uiTextBoxPressureDiff?.Text ?? "", out pressureDifference);
                decimal.TryParse(uiTextBoxStandardError?.Text ?? "", out standardError);
                int.TryParse(uiTextBoxQuantity?.Text ?? "", out quantity);

                string temperatureMode = "";
                if (uiCheckBox1?.Checked == true)
                {
                    temperatureMode = "常温模式";
                }
                else if (uiCheckBox2?.Checked == true)
                {
                    temperatureMode = "高温模式";
                }

                // 获取联络单号、件号、刻字号和数量
                string contactNumber = uiTextBox2?.Text?.Trim() ?? "";
                string itemNumber = uiTextBox11?.Text?.Trim() ?? "";
                string engravingNumber = uiTextBoxEngravingNumber?.Text?.Trim() ?? "";

                //if (string.IsNullOrEmpty(contactNumber))
                //{
                //    MessageBox.Show("请输入联络单号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}

                if (string.IsNullOrEmpty(itemNumber))
                {
                    MessageBox.Show("请输入件号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 组合条码用于兼容性（可选）
                string barcode = $"{contactNumber}-{itemNumber}";

                // 修改这里：新增记录时，检查件号是否已存在
                // 因为是新增，所以只需要检查是否有任何记录使用了相同的件号
                bool isDuplicate = _repository.GetScanDataBylldh_jh(uiTextBox11.Text).Any();

                if (isDuplicate)
                {
                    MessageBox.Show("件号已存在，请使用不同的件号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    _repository.InsertScanItems(new ScanData
                    {
                        barcode = barcode,
                        //Quantity = quantity,
                        diffpressure = diffpressure,
                        exit_temperature = exit_temperature,
                        dwelltime = dwelltime,
                        // IsHighMode = temperature > 0,
                        temperature = temperature,
                        // PressureDifference = pressureDifference,
                        TemperatureMode = temperatureMode,
                        jh = uiTextBox11.Text,
                        CreateTime = DateTime.Now,
                        kzh = uiTextBoxEngravingNumber.Text,
                        lldh = uiTextBox2.Text,
                        pressuresetting = pressureDifference,
                        quantity = quantity,
                        standarderror = standardError
                    });

                    // 重新加载数据
                    LoadData();

                    // 可选：清空输入框
                    ClearInputFields();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });
        }


        private void ClearInputFields()
        {
            if (uiTextBox1 != null) uiTextBox1.Text = "";
            if (uiTextBox2 != null) uiTextBox2.Text = "";
            if (uiTextBox11 != null) uiTextBox11.Text = "";
            if (uiTextBoxEngravingNumber != null) uiTextBoxEngravingNumber.Text = "";
            if (uiTextBoxQuantity != null) uiTextBoxQuantity.Text = "";
            if (uiTextBox4 != null) uiTextBox4.Text = "";
            if (uiTextBox5 != null) uiTextBox5.Text = "";
            if (uiTextBox9 != null) uiTextBox9.Text = "";
            if (uiTextBoxPressureDiff != null) uiTextBoxPressureDiff.Text = "";
            if (uiTextBoxStandardError != null) uiTextBoxStandardError.Text = "";
            if (uiCheckBox1 != null) uiCheckBox1.Checked = false;
            if (uiCheckBox2 != null) uiCheckBox2.Checked = false;
        }

        private void ScanImport_Load(object sender, EventArgs e)
        {
            SafeInvoke(() =>
            {
                LoadData();
            });
        }


        // 设置行号的方法
        private void SetRowNumbers()
        {
            SafeInvoke(() =>
            {
                if (uiDataGridView1 == null || uiDataGridView1.IsDisposed)
                    return;

                // 为每一行设置序号
                for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
                {
                    uiDataGridView1.Rows[i].Cells["SerialNumber"].Value = (i + 1).ToString();
                }
            });
        }
        //private void LoadData()
        //{
        //    try
        //    {
        //        // 将数据查询操作移到后台线程，避免UI卡顿
        //        System.Threading.Tasks.Task.Run(() =>
        //        {
        //            var data = _repository.GetScanData();

        //            // 安全更新DataGridView
        //            SafeInvoke(() =>
        //            {
        //                // 避免重复绑定导致的异常
        //                if (uiDataGridView1 != null && !uiDataGridView1.IsDisposed)
        //                {
        //                    // 先解绑再重新绑定
        //                    uiDataGridView1.DataSource = new List<ScanData>();
        //                    uiDataGridView1.DataSource = data;


        //                    if (uiDataGridView1.Columns.Contains("Column1"))
        //                    {
        //                        uiDataGridView1.Columns["Column1"].Visible = false;
        //                    }

        //                    SetRowNumbers();
        //                    uiDataGridView1.Refresh();

        //                }
        //            });
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        SafeInvoke(() =>
        //        {
        //            MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        });
        //    }
        //}

        //private void SwitchWindow<T>(ref T windowInstance, Func<T> createFunc) where T : UIForm
        //{
        //    if (windowInstance == null || windowInstance.IsDisposed)
        //    {
        //        windowInstance = createFunc();
        //        windowInstance.FormClosed += (s, e) =>
        //        {
        //            this.Invoke(new Action(() =>
        //            {
        //                this.Show();
        //                this.Activate();
        //            }));
        //        };
        //    }
        //    else
        //    {
        //        windowInstance.Activate();
        //        return;
        //    }
        //    this.Hide();
        //    windowInstance.Show();
        //}
        private void LoadData()
        {
            try
            {
                // 将数据查询操作移到后台线程，避免UI卡顿
                System.Threading.Tasks.Task.Run(() =>
                {
                    var data = _repository.GetScanData();

                    // 安全更新DataGridView
                    SafeInvoke(() =>
                    {
                        // 避免重复绑定导致的异常
                        if (uiDataGridView1 != null && !uiDataGridView1.IsDisposed)
                        {
                            // ============ 启用编辑功能 ============
                            // 关键设置：允许用户编辑
                            uiDataGridView1.ReadOnly = false;
                            uiDataGridView1.AllowUserToAddRows = false;
                            uiDataGridView1.AllowUserToDeleteRows = false;
                            uiDataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; // 或 EditOnKeystrokeOrF2
                                                                                         // ============ 结束设置 ============

                            // 先解绑再重新绑定
                            uiDataGridView1.DataSource = new List<ScanData>();
                            uiDataGridView1.DataSource = data;

                            // ============ 添加编辑按钮列 ============
                            // 检查是否已存在编辑按钮列
                            if (!uiDataGridView1.Columns.Contains("EditButton"))
                            {
                                DataGridViewButtonColumn editButtonColumn = new DataGridViewButtonColumn();
                                editButtonColumn.Name = "EditButton";
                                editButtonColumn.HeaderText = "保存修改";
                                editButtonColumn.Text = "保存";
                                editButtonColumn.UseColumnTextForButtonValue = true;
                                editButtonColumn.Width = 80;

                                // 将按钮列添加到DataGridView中（放在第一列）
                                uiDataGridView1.Columns.Add(editButtonColumn);
                                uiDataGridView1.Columns["EditButton"].DisplayIndex = 0; // 放在第一列
                            }

                            // ============ 设置各列属性，使数据可编辑 ============
                            // 确保所有列都可编辑（除了Id列和按钮列）
                            foreach (DataGridViewColumn column in uiDataGridView1.Columns)
                            {
                                if (column.Name != "Id" && column.Name != "EditButton")
                                {
                                    column.ReadOnly = false;

                                    // 特别设置数值列的编辑属性
                                    if (column.Name.Contains("pressure") ||
                                        column.Name.Contains("temperature") ||
                                        column.Name.Contains("dwelltime") ||
                                        column.Name.Contains("quantity") ||
                                        column.Name.Contains("standarderror"))
                                    {
                                        // 设置单元格为文本框，可以编辑数值
                                        if (column is DataGridViewTextBoxColumn textBoxColumn)
                                        {
                                            textBoxColumn.DefaultCellStyle.Format = "F2"; // 显示两位小数
                                        }
                                    }
                                }
                            }

                            // 隐藏ID列（如果需要）
                            if (uiDataGridView1.Columns.Contains("Id"))
                            {
                                uiDataGridView1.Columns["Id"].Visible = false;
                            }

                            // ============ 添加按钮点击事件处理 ============
                            // 移除旧的事件处理程序（避免重复）
                            uiDataGridView1.CellClick -= DataGridViewCellClickHandler;
                            // 添加新的事件处理程序
                            uiDataGridView1.CellClick += DataGridViewCellClickHandler;
                            // ============ 结束添加 ============

                            SetRowNumbers();
                            uiDataGridView1.Refresh();
                        }
                    });
                });
            }
            catch (Exception ex)
            {
                SafeInvoke(() =>
                {
                    MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            }
        }
        //// 编辑按钮点击事件处理
        //private void DataGridViewCellClickHandler(object sender, DataGridViewCellEventArgs e)
        //{
        //    // 确保点击的是按钮列
        //    if (e.RowIndex >= 0 && e.ColumnIndex >= 0 &&
        //        uiDataGridView1.Columns[e.ColumnIndex].Name == "EditButton")
        //    {
        //        // 获取选中的行数据
        //        if (uiDataGridView1.Rows[e.RowIndex].DataBoundItem is ScanData scanData)
        //        {
        //            // 保存修改到数据库
        //            try
        //            {
        //                bool isAny = _repository.GetScanDataBylldh_jh(scanData.jh).Any();
        //                if (isAny)
        //                {
        //                    MessageBox.Show("件号重复");
        //                    return;
        //                }

        //                _repository.UpdateScanItem(scanData);

        //                MessageBox.Show("修改已保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

        //                // 刷新数据
        //                LoadData();
        //            }
        //            catch (Exception ex)
        //            {
        //                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //            }
        //        }
        //    }
        //}
        // 编辑按钮点击事件处理
        private void DataGridViewCellClickHandler(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是按钮列
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 &&
                uiDataGridView1.Columns[e.ColumnIndex].Name == "EditButton")
            {
                // 获取选中的行数据
                if (uiDataGridView1.Rows[e.RowIndex].DataBoundItem is ScanData scanData)
                {
                    // 保存修改到数据库
                    try
                    {
                        // 修改这里：检查件号重复时排除当前记录自身
                        // 获取除了当前记录ID之外，是否有其他记录使用了相同的件号
                        bool isDuplicate = _repository.GetScanDataBylldh_jh(scanData.jh)
                            .Any(x => x.Id != scanData.Id);  // 排除当前记录自身

                        if (isDuplicate)
                        {
                            MessageBox.Show("件号重复，请使用不同的件号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        _repository.UpdateScanItem(scanData);

                        MessageBox.Show("修改已保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 刷新数据
                        LoadData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        private void SwitchWindow<T>(T windowInstance, Func<T> createFunc) where T : UIForm
        {

            // 需要将 windowInstance 声明为局部变量
            T localInstance = windowInstance;

            // 复用窗口实例
            if (localInstance == null || localInstance.IsDisposed)
            {
                localInstance = createFunc();
                localInstance.FormClosed += (s, e) =>
                {
                    SafeInvoke(() =>
                    {
                        this.Show();
                        this.Activate();
                    });
                };
            }
            else
            {
                SafeInvoke(() => localInstance.Activate());
                return;
            }

            SafeInvoke(() =>
            {
                this.Hide();
                localInstance.Show();
            });

            // 如果需要更新外部引用，可以返回实例
            // return localInstance;
        }
        private void uiButton1_Click(object sender, EventArgs e)
        {
            SwitchWindow(_normalTemperatureMode, () => new NormalTemperatureMode());
        }


        //清除
        private void uiButton2_Click(object sender, EventArgs e)
        {
            var ids = new List<int>();
            foreach (DataGridViewRow row in uiDataGridView1.SelectedRows)
            {
                if (row.DataBoundItem is ScanData scanData && scanData.Id > 0)
                {
                    ids.Add(scanData.Id);
                }
            }
            _repository.DeleteScanItems(ids[0]);
            LoadData();
        }

        private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // 当添加新行时更新序号
            SetRowNumbers();
        }

        private void uiDataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            // 当移除行时更新序号
            SetRowNumbers();
        }

        private void uiDataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            // 当移除行时更新序号
            SetRowNumbers();
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            Application.Restart();

            // 关闭当前窗口
            Environment.Exit(0);
        }
    }
}
