using System.Data;
using System.Data.Common;
using System.Text;

namespace ThingsGateway.SqlSugar
{
    /// <summary>
    /// 数据库绑定辅助类
    /// </summary>
    public partial class DbBindAccessory
    {
        /// <summary>
        /// 查询构建器
        /// </summary>
        public QueryBuilder QueryBuilder { get; set; }

        /// <summary>
        /// 获取实体列表
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="context">SqlSugar提供者</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>实体列表</returns>
        protected List<T> GetEntityList<T>(SqlSugarProvider context, IDataReader dataReader)
        {
            Type type = typeof(T);
            var entityInfo = context.EntityMaintenance.GetEntityInfo(type);
            var isOwnsOne = entityInfo.Columns.Any(it => it.ForOwnsOnePropertyInfo != null);
            string types = null;
            var fieldNames = GetDataReaderNames(dataReader, ref types);
            string cacheKey = GetCacheKey(type, fieldNames) + types;
            var dataAfterFunc = context.CurrentConnectionConfig?.AopEvents?.DataExecuted;
            IDataReaderEntityBuilder<T> entytyList = context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, () =>
            {
                var cacheResult = new IDataReaderEntityBuilder<T>(context, dataReader, fieldNames).CreateBuilder(type);
                return cacheResult;
            });
            List<T> result = new List<T>();
            try
            {
                if (dataReader == null) return result;
                while (dataReader.Read())
                {
                    var addItem = entytyList.Build(dataReader);
                    if (this.QueryBuilder?.QueryableFormats?.Count > 0)
                    {
                        FormatT(addItem);
                    }
                    result.Add(addItem);
                    SetAppendColumns(dataReader);
                    SetOwnsOne(addItem, isOwnsOne, entityInfo, dataReader);
                }
                ExecuteDataAfterFun(context, dataAfterFunc, result);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Common Language Runtime detected an invalid program.")
                {
                    Check.Exception(true, ErrorMessage.EntityMappingErrorCompositeFormat, ex.Message);
                }
                else
                {
                    throw;
                }
            }
            return result;
        }

        /// <summary>
        /// 异步获取实体列表
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="context">SqlSugar提供者</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>实体列表</returns>
        protected async Task<List<T>> GetEntityListAsync<T>(SqlSugarProvider context, IDataReader dataReader)
        {
            Type type = typeof(T);
            var entityInfo = context.EntityMaintenance.GetEntityInfo(type);
            var isOwnsOne = entityInfo.Columns.Any(it => it.ForOwnsOnePropertyInfo != null);
            string types = null;
            var fieldNames = GetDataReaderNames(dataReader, ref types);
            string cacheKey = GetCacheKey(type, fieldNames) + types;
            var dataAfterFunc = context.CurrentConnectionConfig?.AopEvents?.DataExecuted;
            IDataReaderEntityBuilder<T> entytyList = context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey, () =>
            {
                var cacheResult = new IDataReaderEntityBuilder<T>(context, dataReader, fieldNames).CreateBuilder(type);
                return cacheResult;
            });
            List<T> result = new List<T>();
            try
            {
                if (dataReader == null) return result;
                while (await GetReadAsync(dataReader, context).ConfigureAwait(false))
                {
                    var addItem = entytyList.Build(dataReader);
                    if (this.QueryBuilder?.QueryableFormats?.Count > 0)
                    {
                        FormatT(addItem);
                    }
                    result.Add(addItem);
                    SetAppendColumns(dataReader);
                    SetOwnsOne(addItem, isOwnsOne, entityInfo, dataReader);
                }
                ExecuteDataAfterFun(context, dataAfterFunc, result);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Common Language Runtime detected an invalid program.")
                {
                    Check.Exception(true, ErrorMessage.EntityMappingErrorCompositeFormat, ex.Message);
                }
                else
                {
                    throw;
                }
            }
            return result;
        }

        /// <summary>
        /// 异步读取数据
        /// </summary>
        /// <param name="dataReader">数据读取器</param>
        /// <param name="context">SqlSugar提供者</param>
        /// <returns>是否读取成功</returns>
        private Task<bool> GetReadAsync(IDataReader dataReader, SqlSugarProvider context)
        {
            if (this.QueryBuilder?.Builder?.SupportReadToken == true && context.Ado.CancellationToken != null)
            {
                return this.QueryBuilder.Builder.GetReaderByToken(dataReader, context.Ado.CancellationToken.Value);
            }
            else
            {
                return ((DbDataReader)dataReader).ReadAsync();
            }
        }

        /// <summary>
        /// 设置OwnsOne属性
        /// </summary>
        /// <param name="addItem">实体对象</param>
        /// <param name="isOwnsOne">是否包含OwnsOne属性</param>
        /// <param name="entityInfo">实体信息</param>
        /// <param name="dataReader">数据读取器</param>
        private void SetOwnsOne(object addItem, bool isOwnsOne, EntityInfo entityInfo, IDataReader dataReader)
        {
            if (isOwnsOne)
            {
                var ownsOneColumnsKv = entityInfo.Columns.Where(it => it.ForOwnsOnePropertyInfo != null)
                    .GroupBy(it => it.ForOwnsOnePropertyInfo).ToList();
                foreach (var kv in ownsOneColumnsKv)
                {
                    var parentObj = kv.Key.GetValue(addItem);
                    if (parentObj == null)
                    {
                        parentObj = kv.Key.PropertyType.Assembly.CreateInstance(kv.Key.PropertyType.FullName);
                        kv.Key.SetValue(addItem, parentObj);
                    }
                    foreach (var item in kv.ToList())
                    {
                        if (this.QueryBuilder?.SelectValue?.Equals("1") == true)
                        {
                            continue;
                        }
                        var itemIndex = dataReader.GetOrdinal(item.DbColumnName);
                        if (item.SqlParameterDbType is Type && item.UnderType.IsEnum && dataReader.GetValue(itemIndex) is string value)
                        {
                            item.PropertyInfo.SetValue(parentObj, UtilMethods.ChangeType2(value, item.PropertyInfo.PropertyType));
                        }
                        else if (item.IsJson)
                        {
                            item.PropertyInfo.SetValue(parentObj, Newtonsoft.Json.JsonConvert.DeserializeObject(dataReader.GetValue(itemIndex)?.ToString(), item.PropertyInfo.PropertyType));
                        }
                        else
                        {
                            var setValue = dataReader.GetValue(itemIndex);
                            if (setValue == DBNull.Value)
                            {
                                setValue = null;
                            }
                            if (item.UnderType == UtilConstants.GuidType && setValue is string)
                            {
                                if (setValue != null)
                                {
                                    setValue = Guid.Parse(setValue + "");
                                }
                            }
                            else if (item.UnderType?.IsEnum == true && setValue != null)
                            {
                                setValue = UtilMethods.ChangeType2(setValue, item.UnderType);
                            }
                            else if (UtilMethods.IsParameterConverter(item))
                            {
                                setValue = UtilMethods.QueryConverter(itemIndex, null, dataReader, entityInfo, item);
                            }
                            item.PropertyInfo.SetValue(parentObj, setValue);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 格式化实体对象
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="addItem">实体对象</param>
        private void FormatT<T>(T addItem)
        {
            var formats = this.QueryBuilder.QueryableFormats;
            var columns = this.QueryBuilder.Context.EntityMaintenance.GetEntityInfoWithAttr(typeof(T))
                .Columns.Where(it => formats.Any(y => y.PropertyName == it.PropertyName)).ToList();
            if (columns.Count != 0)
            {
                foreach (var item in formats)
                {
                    var columnInfo = columns.FirstOrDefault(it => it.PropertyName == item.PropertyName);
                    var value = columnInfo.PropertyInfo.GetValue(addItem);
                    value = UtilMethods.GetFormatValue(value, item);
                    columnInfo.PropertyInfo.SetValue(addItem, value);
                }
            }
        }

        /// <summary>
        /// 执行数据后处理函数
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="context">SqlSugar提供者</param>
        /// <param name="dataAfterFunc">数据后处理函数</param>
        /// <param name="result">结果列表</param>
        private static void ExecuteDataAfterFun<T>(SqlSugarProvider context, Action<object, DataAfterModel> dataAfterFunc, List<T> result)
        {
            if (dataAfterFunc != null)
            {
                ((AdoProvider)context.Ado).AfterTime = DateTime.Now;
                var entity = context.EntityMaintenance.GetEntityInfo<T>();
                foreach (var item in result)
                {
                    dataAfterFunc(item, new DataAfterModel()
                    {
                        EntityColumnInfos = entity.Columns,
                        Entity = entity,
                        EntityValue = item
                    });
                }
            }
        }

        /// <summary>
        /// 获取缓存键
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="keys">键列表</param>
        /// <returns>缓存键</returns>
        private string GetCacheKey(Type type, List<string> keys)
        {
            StringBuilder sb = new StringBuilder("DataReaderToList.");
            sb.Append(type.FullName);
            sb.Append('.');
            foreach (var item in keys)
            {
                sb.Append(item);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 设置附加列
        /// </summary>
        /// <param name="dataReader">数据读取器</param>
        private void SetAppendColumns(IDataReader dataReader)
        {
            if (QueryBuilder?.AppendColumns != null && QueryBuilder.AppendColumns.Count != 0)
            {
                if (QueryBuilder.AppendValues == null)
                    QueryBuilder.AppendValues = new List<List<QueryableAppendColumn>>();
                List<QueryableAppendColumn> addItems = new List<QueryableAppendColumn>();
                foreach (var item in QueryBuilder.AppendColumns)
                {
                    var vi = dataReader.GetOrdinal(item.AsName);
                    var value = dataReader.GetValue(vi);
                    addItems.Add(new QueryableAppendColumn()
                    {
                        Name = item.Name,
                        AsName = item.AsName,
                        Value = value
                    });
                }
                QueryBuilder.AppendValues.Add(addItems);
            }
            if (QueryBuilder?.AppendNavInfo != null)
            {
                var navResult = new AppendNavResult();
                foreach (var item in QueryBuilder?.AppendNavInfo.AppendProperties)
                {
                    var vi = dataReader.GetOrdinal("SugarNav_" + item.Key);
                    var value = dataReader.GetValue(vi);
                    navResult.result.Add("SugarNav_" + item.Key, value);
                }
                QueryBuilder?.AppendNavInfo.Result.Add(navResult);
            }
        }

        /// <summary>
        /// 获取数据读取器字段名
        /// </summary>
        /// <param name="dataReader">数据读取器</param>
        /// <param name="types">类型字符串</param>
        /// <returns>字段名列表</returns>
        private List<string> GetDataReaderNames(IDataReader dataReader, ref string types)
        {
            List<string> keys = new List<string>();
            StringBuilder sbTypes = new StringBuilder();
            var count = dataReader.FieldCount;
            for (int i = 0; i < count; i++)
            {
                keys.Add(dataReader.GetName(i));
                var type = dataReader.GetFieldType(i);
                if (type != null)
                {
                    sbTypes.Append(type.Name.AsSpan(0, 2));
                }
            }
            types = sbTypes.ToString();
            if (this.QueryBuilder?.Context?.Ado is AdoProvider adoProvider)
            {
                if (adoProvider.IsNoSql)
                {
                    types = "NoSql";
                }
            }
            return keys;
        }

        /// <summary>
        /// 获取键值对列表
        /// </summary>
        /// <typeparam name="T">键值对类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>键值对列表</returns>
        protected List<T> GetKeyValueList<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            while (dataReader.Read())
            {
                GetKeyValueList(type, dataReader, result);
            }
            return result;
        }

        /// <summary>
        /// 异步获取键值对列表
        /// </summary>
        /// <typeparam name="T">键值对类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>键值对列表</returns>
        protected async Task<List<T>> GetKeyValueListAsync<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            while (await ((DbDataReader)dataReader).ReadAsync().ConfigureAwait(false))
            {
                GetKeyValueList(type, dataReader, result);
            }
            return result;
        }

        /// <summary>
        /// 获取键值对列表
        /// </summary>
        /// <typeparam name="T">键值对类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <param name="result">结果列表</param>
        private static void GetKeyValueList<T>(Type type, IDataReader dataReader, List<T> result)
        {
            if (UtilConstants.DicOO == type)
            {
                var kv = new KeyValuePair<object, object>(dataReader.GetValue(0), dataReader.GetValue(1));
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<object, object>)));
            }
            else if (UtilConstants.DicIS == type)
            {
                var kv = new KeyValuePair<int, string>(dataReader.GetValue(0).ObjToInt(), dataReader.GetValue(1).ObjToString());
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<int, string>)));
            }
            else if (UtilConstants.Dicii == type)
            {
                var kv = new KeyValuePair<int, int>(dataReader.GetValue(0).ObjToInt(), dataReader.GetValue(1).ObjToInt());
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<int, int>)));
            }
            else if (UtilConstants.DicSi == type)
            {
                var kv = new KeyValuePair<string, int>(dataReader.GetValue(0).ObjToString(), dataReader.GetValue(1).ObjToInt());
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<string, int>)));
            }
            else if (UtilConstants.DicSo == type)
            {
                var kv = new KeyValuePair<string, object>(dataReader.GetValue(0).ObjToString(), dataReader.GetValue(1));
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<string, object>)));
            }
            else if (UtilConstants.DicSS == type)
            {
                var kv = new KeyValuePair<string, string>(dataReader.GetValue(0).ObjToString(), dataReader.GetValue(1).ObjToString());
                result.Add((T)Convert.ChangeType(kv, typeof(KeyValuePair<string, string>)));
            }
            else
            {
                Check.Exception(true, ErrorMessage.NotSupportedDictionaryCompositeFormat);
            }
        }

        /// <summary>
        /// 异步获取数组列表
        /// </summary>
        /// <typeparam name="T">数组类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>数组列表</returns>
        protected async Task<List<T>> GetArrayListAsync<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            int count = dataReader.FieldCount;
            var childType = type.GetElementType();
            while (await ((DbDataReader)dataReader).ReadAsync().ConfigureAwait(false))
            {
                GetArrayList(type, dataReader, result, count, childType);
            }
            return result;
        }

        /// <summary>
        /// 获取数组列表
        /// </summary>
        /// <typeparam name="T">数组类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>数组列表</returns>
        protected List<T> GetArrayList<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            int count = dataReader.FieldCount;
            var childType = type.GetElementType();
            while (dataReader.Read())
            {
                GetArrayList(type, dataReader, result, count, childType);
            }
            return result;
        }

        /// <summary>
        /// 获取数组列表
        /// </summary>
        /// <typeparam name="T">数组类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <param name="result">结果列表</param>
        /// <param name="count">字段数量</param>
        /// <param name="childType">子元素类型</param>
        private static void GetArrayList<T>(Type type, IDataReader dataReader, List<T> result, int count, Type childType)
        {
            object[] array = new object[count];
            for (int i = 0; i < count; i++)
            {
                array[i] = Convert.ChangeType(dataReader.GetValue(i), childType);
            }
            if (childType == UtilConstants.StringType)
                result.Add((T)Convert.ChangeType(array.Select(it => it.ObjToString()).ToArray(), type));
            else if (childType == UtilConstants.ObjType)
                result.Add((T)Convert.ChangeType(array.Select(it => it == DBNull.Value ? null : (object)it).ToArray(), type));
            else if (childType == UtilConstants.BoolType)
                result.Add((T)Convert.ChangeType(array.Select(it => it.ObjToBool()).ToArray(), type));
            else if (childType == UtilConstants.ByteType)
                result.Add((T)Convert.ChangeType(array.Select(it => it == DBNull.Value ? 0 : (byte)it).ToArray(), type));
            else if (childType == UtilConstants.DecType)
                result.Add((T)Convert.ChangeType(array.Select(it => it.ObjToDecimal()).ToArray(), type));
            else if (childType == UtilConstants.GuidType)
                result.Add((T)Convert.ChangeType(array.Select(it => it == DBNull.Value ? Guid.Empty : (Guid)it).ToArray(), type));
            else if (childType == UtilConstants.DateType)
                result.Add((T)Convert.ChangeType(array.Select(it => it == DBNull.Value ? DateTime.MinValue : (DateTime)it).ToArray(), type));
            else if (childType == UtilConstants.IntType)
                result.Add((T)Convert.ChangeType(array.Select(it => it.ObjToInt()).ToArray(), type));
            else
                Check.Exception(true, ErrorMessage.NotSupportedArrayCompositeFormat);
        }

        /// <summary>
        /// 获取值类型列表
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>值类型列表</returns>
        protected List<T> GetValueTypeList<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            while (dataReader.Read())
            {
                GetValueTypeList(type, dataReader, result);
            }
            return result;
        }

        /// <summary>
        /// 异步获取值类型列表
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <returns>值类型列表</returns>
        protected async Task<List<T>> GetValueTypeListAsync<T>(Type type, IDataReader dataReader)
        {
            List<T> result = new List<T>();
            while (await ((DbDataReader)dataReader).ReadAsync().ConfigureAwait(false))
            {
                GetValueTypeList(type, dataReader, result);
            }
            return result;
        }

        /// <summary>
        /// 获取值类型列表
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="type">类型</param>
        /// <param name="dataReader">数据读取器</param>
        /// <param name="result">结果列表</param>
        private static void GetValueTypeList<T>(Type type, IDataReader dataReader, List<T> result)
        {
            var value = dataReader.GetValue(0);
            if (type == UtilConstants.GuidType)
            {
                value = Guid.Parse(value.ToString());
            }
            if (value == DBNull.Value)
            {
                result.Add(default(T));
            }
            else if (type.IsEnum)
            {
                result.Add((T)Enum.Parse(type, value.ObjToString()));
            }
            else if (value != null && UtilMethods.GetUnderType(type).IsEnum)
            {
                result.Add((T)Enum.Parse(UtilMethods.GetUnderType(type), value.ObjToString()));
            }
            else
            {
                result.Add((T)UtilMethods.ChangeType2(value, type));
            }
        }
    }
}