using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using SharedDATA.Api;

namespace TechHelper.Services.Beta
{
    /// <summary>
    /// Lesson服务实现类
    /// </summary>
    public class LessonService : ILessonService
    {
        private readonly IUnitOfWork _work;
        private readonly IMapper _mapper;

        public LessonService(IUnitOfWork work, IMapper mapper)
        {
            _work = work;
            _mapper = mapper;
        }

        public async Task<ApiResponse> GetAllAsync(QueryParameter query)
        {
            try
            {
                var repository = _work.GetRepository<Lesson>();

                if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
                {
                    var lessons = await repository.GetPagedListAsync(
                        predicate: l => l.Title.Contains(query.Search),
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var lessonDtosFiltered = _mapper.Map<IEnumerable<LessonResponseDto>>(lessons.Items);
                    return new ApiResponse(true, lessonDtosFiltered);
                }
                else
                {
                    var lessons = await repository.GetPagedListAsync(
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var lessonDtos = _mapper.Map<IEnumerable<LessonResponseDto>>(lessons.Items);
                    return new ApiResponse(true, lessonDtos);
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取所有课程时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetAsync(Guid id)
        {
            try
            {
                var lesson = await _work.GetRepository<Lesson>().GetFirstOrDefaultAsync(
                    predicate: l => l.Id == id);

                if (lesson == null)
                {
                    return new ApiResponse("课程未找到。");
                }

                var lessonDto = _mapper.Map<LessonResponseDto>(lesson);
                return new ApiResponse(true, lessonDto);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取课程时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> AddAsync(LessonDto model)
        {
            try
            {
                // 检查是否已存在同名课程
                var existingLesson = await _work.GetRepository<Lesson>().GetFirstOrDefaultAsync(
                    predicate: l => l.Title == model.Title && l.TextbookID == model.TextBookId);

                if (existingLesson != null)
                {
                    return new ApiResponse($"课程 '{model.Title}' 在该教材中已存在。");
                }

                var lesson = _mapper.Map<Lesson>(model);

                await _work.GetRepository<Lesson>().InsertAsync(lesson);

                if (await _work.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, lesson.Id);
                }
                return new ApiResponse("添加课程失败。");
            }
            catch (Exception ex)
            {
                return new ApiResponse($"添加课程时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> UpdateAsync(LessonDto model)
        {
            try
            {
                var existingLesson = await _work.GetRepository<Lesson>().GetFirstOrDefaultAsync(
                    predicate: l => l.Id == model.Id);

                if (existingLesson == null)
                {
                    return new ApiResponse("课程未找到。");
                }

                // 检查是否要修改为已存在的课程名称（排除当前课程）
                var lessonWithSameName = await _work.GetRepository<Lesson>().GetFirstOrDefaultAsync(
                    predicate: l => l.Title == model.Title && l.TextbookID == model.TextBookId && l.Id != model.Id);

                if (lessonWithSameName != null)
                {
                    return new ApiResponse($"课程名称 '{model.Title}' 在该教材中已被其他课程使用。");
                }

                _mapper.Map(model, existingLesson);
                _work.GetRepository<Lesson>().Update(existingLesson);

                if (await _work.SaveChangesAsync() > 0)
                {
                    var lessonDto = _mapper.Map<LessonResponseDto>(existingLesson);
                    return new ApiResponse(true, lessonDto);
                }
                return new ApiResponse("更新课程失败。");
            }
            catch (Exception ex)
            {
                return new ApiResponse($"更新课程时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> DeleteAsync(Guid id)
        {
            try
            {
                var existingLesson = await _work.GetRepository<Lesson>().GetFirstOrDefaultAsync(
                    predicate: l => l.Id == id);

                if (existingLesson == null)
                {
                    return new ApiResponse("课程未找到。");
                }

                _work.GetRepository<Lesson>().Delete(existingLesson);

                if (await _work.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, "课程删除成功。");
                }
                return new ApiResponse("删除课程失败。");
            }
            catch (Exception ex)
            {
                return new ApiResponse($"删除课程时发生错误: {ex.Message}");
            }
        }
    }
}
