using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Security.Cryptography;

namespace PushPlatform.Common.Util
{
    public static class DataTableHelper
    {
        #region Datatable转List集合
        /// <summary>
        /// Datatable转List集合
        /// </summary>
        /// <typeparam name="TResult">泛型</typeparam>
        /// <param name="dt">datatable</param>
        /// <returns></returns>
        public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class, new()
        {
            List<TResult> list = new List<TResult>();
            if (dt == null) return list;
            int len = dt.Rows.Count;

            for (int i = 0; i < len; i++)
            {
                TResult info = new TResult();
                foreach (DataColumn dc in dt.Rows[i].Table.Columns)
                {
                    if (dt.Rows[i][dc.ColumnName] == null || string.IsNullOrEmpty(dt.Rows[i][dc.ColumnName].ToString())) continue;
                    System.Reflection.PropertyInfo pi = info.GetType().GetProperty(dc.ColumnName);
                    if (pi != null)
                    {
                        if (pi.PropertyType == dt.Columns[dc.ColumnName].DataType)
                        {
                            pi.SetValue(info, dt.Rows[i][dc.ColumnName]);
                        }
                        else
                        {
                            var type = GetCoreType(pi.PropertyType);
                            object value = Convert.ChangeType(dt.Rows[i][dc.ColumnName], type);
                            pi.SetValue(info, value);
                        }
                    }

                }
                list.Add(info);
            }
            dt.Dispose(); dt = null;
            return list;
        }

        /// <summary>
        /// 在ToList之上，加上对Map字段自动找到数据库中的字段名称
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<TResult> ToList2<TResult>(this DataTable dt) where TResult : class, new()
        {
            List<TResult> list = new List<TResult>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return list;
            }
            Type entityType = typeof(TResult);

            foreach (DataRow dr in dt.Rows)
            {
                TResult info = new TResult();

                foreach (DataColumn dc in dt.Columns)
                {
                    if (dr[dc.ColumnName] == null || dr[dc.ColumnName] == DBNull.Value || string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                    {
                        continue;
                    }

                    PropertyInfo pi = entityType.GetProperty(dc.ColumnName);
                    FieldInfo fi = entityType.GetField("Map" + dc.ColumnName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                    string propertyName = null;
                    if (pi != null)
                    {
                        propertyName = pi.Name;
                    }
                    else if (fi != null)
                    {
                        propertyName = fi.GetValue(null).ToString();
                        pi = entityType.GetProperty(propertyName);
                    }
                    if (pi != null)
                    {
                        if (pi.PropertyType == dt.Columns[dc.ColumnName].DataType)
                        {
                            pi.SetValue(info, dr[dc.ColumnName]);
                        }
                        else
                        {
                            var type = GetCoreType(pi.PropertyType);
                            object value = Convert.ChangeType(dr[dc.ColumnName], type);
                            pi.SetValue(info, value);
                        }
                    }
                }

                list.Add(info);


            }
            return list;

        }


        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="dt">datatable</param>
        /// <param name="orderBy">排序列名</param>
        /// <returns></returns>
        public static DataTable OrderBy(this DataTable dt, string orderBy)
        {
            dt.DefaultView.Sort = orderBy;
            return dt.DefaultView.ToTable();
        }
        #endregion

        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="where">查询列名</param>
        /// <returns></returns>
        public static DataTable Where(this DataTable dt, string where)
        {
            DataTable resultDt = dt.Clone();
            DataRow[] resultRows = dt.Select(where);
            foreach (DataRow dr in resultRows) resultDt.Rows.Add(dr.ItemArray);
            return resultDt;

        }
        #endregion

        #region 获取datatable指定行号区间的行
        /// <summary>
        /// 获取datatable指定行号区间的行
        /// </summary>
        /// <param name="startIndex">起始行号</param>
        /// <param name="endIndex">终止行号(不包括该行)</param>
        /// <returns></returns>
        public static DataTable GetByRange(this DataTable dt, int startIndex, int endIndex)
        {
            if (startIndex < 0) startIndex = 0;
            if (endIndex > dt.Rows.Count) endIndex = dt.Rows.Count;

            DataTable dtOnePage = dt.Clone();
            for (int i = startIndex; i < endIndex; i++)
            {
                DataRow dr = dtOnePage.NewRow();
                dr.ItemArray = dt.Rows[i].ItemArray;
                dtOnePage.Rows.Add(dr);
            }

            return dtOnePage;
        }
        #endregion

        #region 将泛类型集合List类转换成DataTable
        /// <summary>
        /// 将泛类型集合List类转换成DataTable
        /// </summary>
        /// <param name="list">泛类型集合</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中，应将生成的DataTable结构Cache起来，此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
        #endregion

        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }

        #region DataSet转List
        public static List<T> DataSetToList<T>(DataSet ds, int tableIndext)
        {
            if (ds == null || ds.Tables.Count <= 0 || tableIndext < 0)
            {
                return null;
            }
            DataTable dt = ds.Tables[tableIndext];
            IList<T> list = new List<T>();
            PropertyInfo[] tMembersAll = typeof(T).GetProperties();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                T t = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    foreach (PropertyInfo tMember in tMembersAll)
                    {
                        if (dt.Columns[j].ColumnName.ToUpper().Equals(tMember.Name.ToUpper()))
                        {
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                tMember.SetValue(t, dt.Rows[i][j], null);
                            }
                            else
                            {
                                tMember.SetValue(t, null, null);
                            }
                            break;
                        }
                    }
                }
                list.Add(t);
            }
            return list.ToList();
        }
        #endregion
    }
}
