using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PTMedicalInsurance.Common
{
    public static class DataGridViewExtensions
    {
        public static void Bind<T>(DataGridView dataGridView, IEnumerable<T> dataSource)
        {
            dataGridView.AutoGenerateColumns = false;

            // 清空原有的列
            dataGridView.Columns.Clear();
            var properties = typeof(T).GetProperties();

            foreach (var property in properties)
            {
                // 获取属性上的显示名称（注释）
                var displayNameAttribute = property.GetCustomAttribute<DisplayNameAttribute>();
                string columnName = displayNameAttribute != null ? displayNameAttribute.DisplayName : property.Name;

                // 创建一个新的DataGridViewTextBoxColumn并设置HeaderText和DataPropertyName
                var column = new DataGridViewTextBoxColumn()
                {
                    HeaderText = columnName,
                    DataPropertyName = property.Name
                };

                // 将新列添加到DataGridView中
                dataGridView.Columns.Add(column);
            }

            // 设置数据源并刷新DataGridView
            dataGridView.DataSource = dataSource.ToList();
        }

        public static string getProperty<T>(string key)
        {
            var properties = typeof(T).GetProperties();
            string pName = null;

            foreach (var property in properties)
            {
                // 获取属性上的显示名称（注释）
                var displayNameAttribute = property.GetCustomAttribute<DisplayNameAttribute>();
                pName = displayNameAttribute != null ? displayNameAttribute.DisplayName : property.Name;
                if (key == pName)
                {
                    // 返回属性名
                    pName = property.Name;
                    break;
                }
            }
            return pName;
        }
    }
}
