using Dapper;
using Ewide.Core.Extension.DataFilter.WebPage;
using Furion.DatabaseAccessor;
using Furion.LinqBuilder;
using Mapster;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;

namespace Ewide.Core.Extension
{
    public static class PageExtensions
    {
        private static string OrderBuilder(PageInputBase pageInput)
        {
            var orderStr = string.Empty;
            if (!string.IsNullOrEmpty(pageInput.SortField))
            {
                orderStr = $"{pageInput.SortField} {(pageInput.SortOrder == pageInput.DescStr ? "Desc" : "Asc")}";
            }
            return orderStr;
        }

        private static string OrderBuilder<T>(PageInputBase pageInput, bool descSort = false)
        {
            var type = typeof(T);
            var hasId = type.GetProperty("Id") != null;
            var hasSort = type.GetProperty("Sort") != null;
            var hasCreatedTime = type.GetProperty("CreatedTime") != null;

            var defaultField = hasSort ? "Sort" : hasCreatedTime ? "CreatedTime" : hasId ? "Id" : "";

            // 排序优先级 创建时间->序号->ID
            var orderStr = string.IsNullOrEmpty(defaultField) ? "" : defaultField + (descSort ? " Desc" : " Asc");

            // 排序是否可用-排序字段和排序顺序都为非空才启用排序            
            if (!string.IsNullOrEmpty(pageInput.SortField))
            {
                orderStr = OrderBuilder(pageInput);
            }
            return orderStr;
        }

        //public static IQueryable<T> GetFilterInfo<T>(this IQueryable<T> source, PageInputBase input, IEnumerable<string> equalsFields = null, IEnumerable<string> likeFields = null, IEnumerable<string> dateTimeRangeFields = null, IEnumerable<string> otherRangeFields = null) where T : new()
        //{
        //    var _searchStr = input._Search;
        //    var searchInfoObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DataFilter.Entity.SearchInfo[]>(_searchStr);
        //    foreach(var elem in searchInfoObj)
        //    {
        //        ParameterExpression param = Expression.Parameter(typeof(T), "p");
        //        var field = typeof(T).GetProperty(elem.Field, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
        //        Expression left = Expression.Property(param, field);
        //        Expression<Func<T, bool>> finalExpression = null;
        //        foreach(var value in elem.Value) 
        //        {
        //            Expression right = Expression.Constant(Convert.ChangeType(value, Nullable.GetUnderlyingType(left.Type) ?? left.Type));
        //            right = Expression.Convert(right, left.Type);

        //            Expression filter = null;
        //            filter = filter.Filter(left, right, elem.QueryType);

        //            if (finalExpression == null)
        //            {
        //                finalExpression = Expression.Lambda<Func<T, bool>>(filter, param);
        //            }
        //            else
        //            {
        //                finalExpression = finalExpression.Or(Expression.Lambda<Func<T, bool>>(filter, param));
        //            }
        //        }
        //        source.Where(finalExpression);
        //    }
        //    return source;
        //}

        private static Expression Filter(this Expression filter, Expression left, Expression right, Ewide.Core.QueryTypeEnum queryType)
        {
            switch (queryType)
            {
                //case "=":
                //    filter = Expression.Equal(left, right);
                //    break;
                //case "<>":
                //case "!=":
                //    filter = Expression.NotEqual(left, right);
                //    break;
                case QueryTypeEnum.GreaterThan:
                    filter = Expression.GreaterThan(left, right);
                    break;
                case QueryTypeEnum.GreaterThanOrEqual:
                    filter = Expression.GreaterThanOrEqual(left, right);
                    break;
                case QueryTypeEnum.LessThan:
                    filter = Expression.LessThan(left, right);
                    break;
                case QueryTypeEnum.LessThanOrEqual:
                    filter = Expression.LessThanOrEqual(left, right);
                    break;
                case QueryTypeEnum.Like:
                    filter = Expression.Call(left, typeof(string).GetMethod("Contains"), right);
                    break;
                //case "NOT LIKE":
                //    filter = Expression.Not(Expression.Call(left, typeof(string).GetMethod("Contains"), right));
                //    break;
                default:
                    filter = Expression.Equal(left, right);
                    break;
            }

            return filter;
        }

        public static Task<PagedList<T>> ToPageData<T>(this IQueryable<T> source, PageInputBase input) where T : new()
        {
            return source.OrderBy(OrderBuilder<T>(input)).ToPagedListAsync(input.PageIndex, input.PageSize);
        }

        public static Task<PagedList<O>> ToPageData<T, O>(this IQueryable<T> source, PageInputBase input) where O : new()
        {
            return source.OrderBy(OrderBuilder<T>(input)).Select(u => u.Adapt<O>()).ToPagedListAsync(input.PageIndex, input.PageSize);
        }

        public static Task<PagedList<O>> ToPageData<T, O>(this IQueryable<T> source, PageInputBase input, TypeAdapterConfig config) where O : new()
        {
            return source.OrderBy(OrderBuilder<T>(input)).Select(u => u.Adapt<O>(config)).ToPagedListAsync(input.PageIndex, input.PageSize);
        }

        #region DAPPER
        public async static Task<PagedList> QueryPageDataDynamic(this IDapperRepository source, string baseSql, PageInputBase input, object param = null, IEnumerable<string> filterFields = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            SearchJsonFitlerInfoGetService searchJsonFitlerInfoGetService = new SearchJsonFitlerInfoGetService(input, filterFields, param);
            var sql = searchJsonFitlerInfoGetService.GetWhereSql(baseSql);
            var sqlParam = searchJsonFitlerInfoGetService.sqlParameters;
            return await QueryPageData(source, sql, input, sqlParam, transaction, commandTimeout, commandType);
        }

        public async static Task<PagedList> QueryPageData(this IDapperRepository source, string sql, PageInputBase input, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            var count = await source.PageTotalCount(
                sql,
                param: param,
                transaction: transaction,
                commandTimeout: commandTimeout,
                commandType: commandType
            );

            var data = await source.QueryAsync(
                 PageSqlBuilder(sql, input),
                 param: param,
                 transaction: transaction,
                 commandTimeout: commandTimeout,
                 commandType: commandType
             );

            var page = new PagedList
            {
                PageIndex = input.PageIndex,
                PageSize = input.PageSize,
                Items = data,
                TotalCount = count,
                TotalPages = input.PageSize.Equals(0) ? 1 : (int)Math.Ceiling((decimal)count / (decimal)input.PageSize)
            };

            return page;
        }

        public async static Task<PagedList<T>> QueryPageData<T>(this IDapperRepository source, string sql, PageInputBase input, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null) where T : new()
        {
            var count = await source.PageTotalCount(
                sql,
                param: param,
                transaction: transaction,
                commandTimeout: commandTimeout,
                commandType: commandType
            );

            var data = await source.QueryAsync<T>(
                PageSqlBuilder(sql, input),
                param: param,
                transaction: transaction,
                commandTimeout: commandTimeout,
                commandType: commandType
            );

            var page = new PagedList<T>
            {
                PageIndex = input.PageIndex,
                PageSize = input.PageSize,
                Items = data,
                TotalCount = count,
                TotalPages = input.PageSize.Equals(0) ? 1 : (int)Math.Ceiling((decimal)count / (decimal)input.PageSize)
            };

            return page;
        }

        private async static Task<int> PageTotalCount(this IDapperRepository source, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            var countSql = String.Format("SELECT COUNT(0) FROM ({0}) T", sql);
            var countAsync = await source.QueryAsync<int>(
                countSql,
                param: param,
                transaction: transaction,
                commandTimeout: commandTimeout,
                commandType: commandType);
            var count = countAsync.SingleOrDefault();
            return count;
        }

        private static string PageSqlBuilder(string sql , PageInputBase input)
        {
            var sqlStrList = new List<string>();
            var orderStr = OrderBuilder(input);
            if (!string.IsNullOrEmpty(orderStr)) sqlStrList.Add(" ORDER BY " + orderStr);
            // input.PageSize = 0表示不分页
            if (input.PageSize != 0) sqlStrList.Add(" LIMIT " + ((input.PageIndex - 1) * input.PageSize).ToString() + "," + input.PageSize.ToString());
            sql += String.Join("", sqlStrList);
            return sql;
        }
        #endregion
    }
}
