using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using CowainHmi.Alarm;
using CowainHmi.UIEditor;
using PCHMI;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CowainHmi
{
    public partial class FrmPlcDataTable : Form
    {
        public static List<PlcTagColumn> Str2TagList(string txt)
        {
            List<PlcTagColumn> list = new List<PlcTagColumn>();
            if (!string.IsNullOrEmpty(txt))
            {
                string[] rows = Regex.Split(txt, "\r\n", RegexOptions.IgnoreCase);
                if (rows.Length > 0)
                {
                    for (int i = 0; i < rows.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(rows[i]))
                        {
                            PlcTagColumn plcTagColumn = new PlcTagColumn(rows[i]);
                            list.Add(plcTagColumn);
                        }
                    }
                }
            }
            return list;
        }


        public bool IsSaved { get; set; }
        public string SaveData { get; set; } = "";
        private BindingList<PlcTagColumn> tagList = new BindingList<PlcTagColumn>();
        public FrmPlcDataTable(string dataTxt)
        {
            InitializeComponent();
            this.dgvData.AutoGenerateColumns = false;
            this.dgvData.DataSource = tagList;
            this.SaveData = dataTxt;
            var list = Str2TagList(dataTxt);
            foreach (var item in list)
            {
                tagList.Add(item);
            }
            if (tagList.Count == 0)
            {
                tagList.Add(new PlcTagColumn("请重命名", ""));
            }
        }
        public DataTable ExcelToDataTable(string fileName)
        {
            try
            {
                Type type = Assembly.Load(File.ReadAllBytes(new FILE().GET_RELEASE_DIR() + "\\NPOI(2.3).dll")).GetType("NPOI.ExcelHelper");
                object obj = Activator.CreateInstance(type);
                return (DataTable)type.GetMethod("ExcelToDataTable").Invoke(obj, new object[1] { fileName });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return new DataTable();
        }


        private void btnImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = new FILE().GET_RELEASE_DIR();
            openFileDialog.Filter = "(*.xlsx)|*.xls";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            DataTable dataTable = ExcelToDataTable(openFileDialog.FileName);
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                tagList.Clear();
                foreach (DataRow row in dataTable.Rows)
                {
                    int val = 0;
                    PlcTagColumn tag = new PlcTagColumn
                    {
                        PLC = row["PLC"] != null ? (int.TryParse(row["PLC"].ToString(), out val) ? val : 0) : 0,
                        Address = row["地址"] != null ? row["地址"].ToString() : "",
                        DecimalPlaces = row["小数位数"] != null ? (int.TryParse(row["小数位数"].ToString(), out val) ? val : 0) : 0,
                        StringLength = row["字符长度"] != null ? (int.TryParse(row["字符长度"].ToString(), out val) ? val : 0) : 0,
                        VarName = row["名称"] != null ? row["名称"].ToString() : "",
                        VarDesc = row["注释"] != null ? row["注释"].ToString() : "",
                        IsReadOnly = row["只读"] != null ? (bool.TryParse(row["只读"].ToString(), out bool readOnly) ? readOnly : false) : false,
                        DatType = row["数据类型"] != null ? (Enum.TryParse<字段.DatType>(row["数据类型"].ToString(), out 字段.DatType datType) ? datType : 字段.DatType.INT16) : 字段.DatType.INT16
                    };
                    tagList.Add(tag);
                }
            }
            else
            {
                MessageBox.Show("文件内容不匹配！", "错误提示！");
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            Excel.Export(this.dgvData);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            foreach (var item in this.tagList)
            {
                list.Add(item.ToString());
            }
            if (list.Count > 0)
            {
                this.SaveData = string.Join("\r\n", list);
            }
            this.IsSaved = true;
            this.DialogResult = DialogResult.OK;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FrmAddRow frmAddRow = new FrmAddRow();
            if (frmAddRow.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < frmAddRow.RowCount; i++)
                {
                    tagList.Add(new PlcTagColumn("请重命名", ""));
                }

            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (this.dgvData.SelectedRows.Count > 0)
            {
                // 显示确认对话框
                var result = MessageBox.Show("确定要删除选中的行吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result != DialogResult.Yes)
                {
                    return;
                }
                // 遍历所有选中行并删除
                foreach (DataGridViewRow row in dgvData.SelectedRows)
                {
                    // 如果行不是新行（未保存的行），则删除
                    if (!row.IsNewRow && row.Index >= 0)
                    {
                        dgvData.Rows.RemoveAt(row.Index);
                    }
                }
                dgvData.Refresh();
            }
            else
            {
                MessageBox.Show("请选择要删除的行。");
            }
        }

        private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 2 && e.ColumnIndex <= 6 && e.RowIndex >= 0)
            {
                FrmTagEdit frmTagEdit = new FrmTagEdit(tagList[e.RowIndex]);
                if (frmTagEdit.ShowDialog() == DialogResult.OK)
                {
                    tagList[e.RowIndex] = frmTagEdit.PlcTag;
                }
            }
        }
    }
}
