using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Nirvana.Data
{
    /// <summary>
    /// 仓储实现类
    /// </summary>
    public abstract class Repository<T> : IRepository<T> where T : class, new()
    {
        public object Add(T entity)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var addresult = dbClient.Insertable(entity).ExecuteCommand();
                return addresult > 0;
            }
        }

        public bool AddList(List<T> TModels)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return dbClient.Insertable(TModels.ToArray()).ExecuteCommand() > 0;
            }
        }

        public bool Delete(Expression<Func<T, bool>> predicate)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var deleteresult = dbClient.Deleteable<T>(predicate).ExecuteCommand();
                return deleteresult > 0;
            }
        }

        public List<T> GetList(Expression<Func<T, bool>> predicate)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return dbClient.Queryable<T>().Where(predicate).ToList();
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public async Task<List<T>> GetListAsync(Expression<Func<T, bool>> predicate)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<T>().Where(predicate).ToListAsync();
            }
        }


        public T GetModel(Expression<Func<T, bool>> predicate)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return dbClient.Queryable<T>().Where(predicate).First();
            }
        }

        public PageData<T> GetPageList(int pageIndex, int pageSize, string strwhere, string strorder)
        {
            List<T> query;
            var rows = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                query = dbClient.Queryable<T>().Where(strwhere).OrderBy(strorder).ToPageList(pageIndex, pageSize, ref rows);
            }
            return new PageData<T>
            {
                CurrentPage = pageIndex,
                Items = query,
                TotalNum = rows,
                TotalPageCount = Convert.ToInt32(Math.Ceiling(rows * 1.0 / pageSize))
            };
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ParamReturnData<T>> GetPageListAsync(ParamQuery param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<T>();
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                     .ToPageListAsync(param.page, param.pagesize, totalnum);
                return new ParamReturnData<T>
                {
                    page = param.page,
                    items = query,
                    totalnum = totalnum,
                    pagesize = param.pagesize
                };
            }
        }
        /// <summary>
        /// 获取分页结果
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<T>> GetPageListAsync(QueryParams param)
        {
            RefAsync<int> totalnum = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var temquery = dbClient.Queryable<T>();
                if (param.queryParam != null && param.queryParam.Count > 0)
                {
                    List<IConditionalModel> conModels = new List<IConditionalModel>();
                    param.queryParam.ForEach(x =>
                    {
                        if (!string.IsNullOrEmpty(x.Value))
                        {
                            conModels.Add(new ConditionalModel()
                            {
                                FieldName = x.Name,
                                ConditionalType = (ConditionalType)x.Type,
                                FieldValue = x.Value.Trim()
                            });
                        }
                    });
                    if (conModels.Count > 0)
                    {
                        temquery = temquery.Where(conModels);
                    }
                }
                string sorts = string.Format("{0} {1}", param.sort, param.order);
                var query = await temquery.OrderBy(sorts)
                     .ToPageListAsync(param.offset, param.limit, totalnum);
                return new PageParms<T>
                {
                    page = param.offset,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.limit
                };
            }
        }

        public PageData<T> GetPageList(int pageIndex, int pageSize, Expression<Func<T, bool>> whereLambda, params MutilOrderExpress<T>[] orderBy)
        {
            List<T> query;
            var rows = 0;
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var tempquery = dbClient.Queryable<T>()
                        .Where(whereLambda);
                orderBy.ToList().ForEach((item) =>
                {
                    tempquery = item.OrderBy.HasValue
                        ? tempquery.OrderBy(item.Expression, item.OrderBy.Value)
                        : tempquery.OrderBy(item.Expression);
                });
                query = tempquery
                    .ToPageList(pageIndex, pageSize, ref rows);
            }
            return new PageData<T>
            {
                CurrentPage = pageIndex,
                Items = query,
                TotalNum = rows,
                TotalPageCount = pageSize == 0 ? 0 : Convert.ToInt32(Math.Ceiling(rows * 1.0 / pageSize))
            };
        }

        public bool IsExist(Expression<Func<T, bool>> predicate)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return dbClient.Queryable<T>().Any(predicate);
            }
        }

        public bool Update(T entity)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var updateresult = dbClient
                    .Updateable(entity)
                    .ExecuteCommand();
                return updateresult > 1;
            }
        }

        public bool UpdateList(List<T> TModels)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return dbClient.Updateable(TModels).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 生成随机的唯一ID
        /// </summary>
        /// <returns></returns>
        public long GenWorkId(long workerId = 1)
        {
            return new IdWorker(workerId).nextid();
        }

        /// <summary>
        /// 生成随机的唯一ID
        /// </summary>
        /// <param name="workerId"></param>
        /// <returns></returns>
        public static long genunionid(long workerId = 1)
        {
            return new IdWorker(workerId).nextid();
        }

        List<T> IRepository<T>.GetListAsync(Expression<Func<T, bool>> predicate)
        {
            throw new NotImplementedException();
        }
    }

}
