using Dapper;
using Furion.DatabaseAccessor;
using Mapster;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
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 = true)
        {
            var type = typeof(T);
            var hasId = type.GetProperty("Id") != null;
            var hasSort = type.GetProperty("Sort") != null;

            var defaultField = hasSort ? "Sort" : (hasId ? "Id" : "");

            // 约定默认每张表都有Id排序
            var orderStr = string.IsNullOrEmpty(defaultField) ? "" : defaultField + (descSort ? " Desc" : " Asc");

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

        public static Task<PagedList<T>> ToPageData<T>(this IQueryable<T> source, PageInputBase input) where T : new()
        {
            return source.OrderBy(OrderBuilder<T>(input)).ToPagedListAsync(input.PageNo, 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.PageNo, input.PageSize);
        }

        public static Task<IEnumerable<dynamic>> QueryPageData(this IDapperRepository source, string sql, PageInputBase input, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            return source.QueryAsync(
                 PageSqlBuilder(sql, input),
                 param: param,
                 transaction: transaction,
                 commandTimeout: commandTimeout,
                 commandType: commandType
             );
        }

        public static Task<IEnumerable<T>> QueryPageData<T>(this IDapperRepository source, string sql, PageInputBase input, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null)
        {
            return source.QueryAsync<T>(
                PageSqlBuilder(sql, input),
                param: param,
                transaction: transaction,
                commandTimeout: commandTimeout,
                commandType: commandType
            );
        }

        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.PageNo - 1) * input.PageSize).ToString() + "," + input.PageSize.ToString());
            sql += String.Join("", sqlStrList);
            return sql;
        }
    }
}
