using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CowainHmi.Alarm
{
    public partial class FrmEditAlarmTable : Form
    {
        private string excelFileName;
        public FrmEditAlarmTable(string _excelFileName)
        {
            InitializeComponent();
            this.excelFileName = _excelFileName;
        }
        private BindingList<PLCInfoModel.PLCAlarmInfo> alarmModels=new BindingList<PLCInfoModel.PLCAlarmInfo>();
        private void FrmEditAlarmTable_Load(object sender, EventArgs e)
        {
            var excelDataTable = AlarmExcelHelper.ReadReleaseExcel(excelFileName,alarmModels);
            alarmModels= AlarmExcelHelper.GetDataList<PLCInfoModel.PLCAlarmInfo>(excelDataTable);
            dataGridView1.DataSource = alarmModels;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
        string selectAddress = "";
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            //selectAddress = GetCellValueByRowColumnIndex(dataGridView1, e.RowIndex, "地址");
        }

        public string GetCellValueByRowColumnIndex(DataGridView dataGridView, int rowIndex, string columnName)
        {
            // 确保行号和DataGridView的行数在有效范围内  
            if (rowIndex < 0 || rowIndex >= dataGridView.Rows.Count)
            {
                throw new IndexOutOfRangeException("rowIndex is out of range.");
            }

            // 查找具有指定列名的列  
            DataGridViewColumn column = dataGridView.Columns.Cast<DataGridViewColumn>().FirstOrDefault(c => c.Name == columnName);

            // 确保找到了列  
            if (column == null)
            {
                throw new ArgumentException("Column with specified name not found.", nameof(columnName));
            }

            // 获取单元格的值  
            // 注意：这里使用rowIndex作为行索引，column.Index作为列索引  
            // 因为DataGridViewCellCollection是基于列的索引来访问单元格的，而不是直接使用列名  
            return dataGridView.Rows[rowIndex].Cells[column.Index].Value?.ToString() ?? string.Empty;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex < 0)
                {
                    return;
                }
                var address = GetCellValueByRowColumnIndex(dataGridView1, e.RowIndex, "地址");
                var rowInfo = alarmModels.Where(item => item.地址 == address).FirstOrDefault();
                if (rowInfo != null)
                {
                    var previousList = AlarmExcelHelper.DeepCopyList<PLCInfoModel.PLCAlarmInfo>(alarmModels);
                    string previousAddress = rowInfo.地址;
                    FrmEditAlarmRecord frmEditAlarmRecord = new FrmEditAlarmRecord(rowInfo);
                    frmEditAlarmRecord.ShowDialog();
                    int count = previousList.Where(item => item.地址 != previousAddress && item.地址 == rowInfo.地址).Count();
                    if (count > 0)
                    {
                        rowInfo.地址 = previousAddress;
                        MessageBox.Show("PLC地址冲突，已回滚为以前的地址！");
                    }
                    dataGridView1.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            AlarmExcelHelper.SaveBindingListToExcel<PLCInfoModel.PLCAlarmInfo>(alarmModels, excelFileName);
            MessageBox.Show("保存成功");
        }
        public static int rowCount;
        private void button3_Click(object sender, EventArgs e)
        {
            //int rowCount = 1;
            AddRowCount addRowCount = new AddRowCount();
            addRowCount.ShowDialog();
            for (int i = 0; i < rowCount; i++)
            {
                PLCInfoModel.PLCAlarmInfo rowInfo = new PLCInfoModel.PLCAlarmInfo();
                rowInfo.地址=Guid.NewGuid().ToString().Substring(0,8);
                alarmModels.Add(rowInfo);
            }
            dataGridView1.Refresh();
            //PLCInfoModel.PLCAlarmInfo rowInfo = new PLCInfoModel.PLCAlarmInfo();
            //int count=alarmModels.Where(item => item.地址==rowInfo.地址).Count();
            //if (count>0)
            //{
            //    MessageBox.Show("有新增加的行没有更改，请先修改！");
            //    return;
            //}
            //alarmModels.Add(rowInfo);
            //var previousList = AlarmExcelHelper.DeepCopyList<PLCInfoModel.PLCAlarmInfo>(alarmModels);
            //string previousAddress = rowInfo.地址;
            //FrmEditAlarmRecord frmEditAlarmRecord = new FrmEditAlarmRecord(rowInfo);
            //frmEditAlarmRecord.ShowDialog();
            //count = previousList.Where(item => item.地址 != previousAddress && item.地址 == rowInfo.地址).Count();
            //if (count > 0)
            //{
            //    rowInfo.地址 = previousAddress;
            //    MessageBox.Show("PLC地址冲突，已回滚为以前的地址！");
            //}
            //dataGridView1.Refresh();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                // 显示确认对话框
                var result = MessageBox.Show("确定要删除选中的行吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (result != DialogResult.Yes)
                { 
                    return;
                }
                // 遍历所有选中行并删除
                foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                {
                    // 如果行不是新行（未保存的行），则删除
                    if (!row.IsNewRow && row.Index>=0)
                    {
                        //dataGridView1.Rows.Remove(row);
                        selectAddress = GetCellValueByRowColumnIndex(dataGridView1, row.Index, "地址");
                        var deleteItem = alarmModels.Where(item => item.地址 == selectAddress).FirstOrDefault();
                        alarmModels.Remove(deleteItem);
                    }
                }
                dataGridView1.Refresh();
                MessageBox.Show("删除成功！");
            }
            else
            {
                MessageBox.Show("请选择要删除的行。");
            } 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < alarmModels.Count; i++)
            {
                alarmModels[i].代码 = (i + 1).ToString();
            }
            dataGridView1.Refresh();
        }
    }
}
