using Model;
using Model.Entity;
using ORM;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Service.Implement
{
    public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : BaseEntity, new()
    {
        protected readonly SqlSugarRepository<TEntity> _repository;

        public BaseService(SqlSugarRepository<TEntity> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        public virtual async Task<Result<List<TEntity>>> GetAllAsync()
        {
            try
            {
                var list = await _repository.Entities.ToListAsync();
                return Result<List<TEntity>>.Success(list);
            }
            catch (Exception ex)
            {
                return Result<List<TEntity>>.Error("查询所有数据失败", ex);
            }
        }
        /// <summary>
        /// 根据日期查询全部
        /// </summary>
        public virtual async Task<Result<List<TEntity>>> GetAllAsyncByDate(DateTime? startDate, DateTime? endDate)
        {
            try
            {
                var list = await _repository.Entities.Where(x => x.CreateTime >= startDate && x.CreateTime <= endDate).ToListAsync();
                return Result<List<TEntity>>.Success(list);
            }
            catch (Exception ex)
            {
                return Result<List<TEntity>>.Error("查询所有数据失败", ex);
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public virtual async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total)
        {
            try
            {
                var list = await _repository.Entities
                                            .OrderBy(d => d.Id)
                                            .ToPageListAsync(pageIndex, pageSize, total);
                total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
                return Result<List<TEntity>>.Success(list);
            }
            catch (Exception ex)
            {
                return Result<List<TEntity>>.Error("分页查询数据失败", ex);
            }
        }

        /// <summary>
        /// 分页查询，并可以根据日期范围进行过滤
        /// </summary>
        public virtual async Task<Result<List<TEntity>>> GetPagedAsync(int pageIndex, int pageSize, RefAsync<int> total, DateTime? startDate, DateTime? endDate)
        {
            try
            {
                var list = await _repository.Entities
                                            .Where(x=>x.CreateTime>=startDate&&x.CreateTime <= endDate)
                                            .OrderBy(d => d.Id)
                                            .ToPageListAsync(pageIndex, pageSize, total);
                total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
                return Result<List<TEntity>>.Success(list);
            }
            catch (Exception ex)
            {
                return Result<List<TEntity>>.Error("分页查询数据失败", ex);
            }
        }

        /// <summary>
        /// 插入单条数据
        /// </summary>
        public virtual async Task<Result<bool>> InsertAsync(TEntity entity)
        {
            try
            {
                var result = await _repository.Context.Insertable(entity).ExecuteCommandAsync();
                return Result<bool>.Success(result > 0);
            }
            catch (Exception ex)
            {
                return Result<bool>.Error("插入数据失败", ex);
            }
        }
        /// <summary>
        /// 删除单条数据（根据 Id）
        /// </summary>
        /// <param name="id">主键 Id</param>
        public virtual async Task<Result<bool>> DeleteAsync(long id)
        {
            if (id <= 0)
                return Result<bool>.Error("主键 Id 无效，无法删除");

            try
            {
                // 删除实体
                var result = await _repository.Context
                                                .Deleteable<TEntity>()
                                                .Where(x => x.Id == id)
                                                .ExecuteCommandAsync();

                return Result<bool>.Success(result > 0);
            }
            catch (Exception ex)
            {
                return Result<bool>.Error("删除数据失败", ex);
            }
        }

    }
}
