using JLHHJSvr.LJException;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace JLHHJSvr.Tools
{
    public class AutoInit
    {
        public static void AutoInitS <T>(SqlCommand cmd, T instance){
            cmd.CommandText = @"SELECT COLUMN_NAME, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@tableName", instance.GetType().Name);
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var column = Convert.ToString(reader["COLUMN_NAME"]).Trim();
                    var isNullable = Convert.ToString(reader["IS_NULLABLE"]).Trim();

                    var property = instance.GetType().GetProperties().FirstOrDefault(prop => prop.Name.Equals(column, StringComparison.OrdinalIgnoreCase));

                    if(property == null)
                    {
                        //throw new LJCommonException($"数据库字段:{column}在模型中找不到相关属性!");
                        continue;
                    }

                    if (isNullable.Equals("NO") && property.GetValue(instance) == null)
                    {
                        var type = property.PropertyType;

                        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            type = type.GetGenericArguments()[0];
                        }

                        if (type.IsAssignableFrom(typeof(string)))
                        {
                            property.SetValue(instance, "");
                        }
                        else if (type.IsAssignableFrom(typeof(int))
                            || type.IsAssignableFrom(typeof(decimal))
                            || type.IsAssignableFrom(typeof(byte)))
                        {
                            property.SetValue(instance, Activator.CreateInstance(type));
                        }
                    }
                }
            }
        }
    }
}
