using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using Microsoft.EntityFrameworkCore;
using SharedDATA.Api;
using TechHelper.Services;

namespace TechHelper.Services.Beta
{
    public class KeyPointService : IKeyPointService
    {
        private readonly IUnitOfWork _work;
        private readonly IMapper _mapper;

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

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

                if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
                {
                    var keyPoints = await repository.GetPagedListAsync(
                        predicate: k => k.Key.Contains(query.Search),
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var keyPointDtosFiltered = _mapper.Map<IEnumerable<KeyPointDto>>(keyPoints);
                    return new ApiResponse(true, keyPointDtosFiltered);
                }
                else
                {
                    var keyPoints = await repository.GetPagedListAsync(
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var keyPointDtos = _mapper.Map<IEnumerable<KeyPointDto>>(keyPoints);
                    return new ApiResponse(true, keyPointDtos);
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取所有知识点时发生错误: {ex.Message}");
            }
        }

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

                if (keyPoint == null)
                {
                    return new ApiResponse("知识点未找到。");
                }

                var keyPointDto = _mapper.Map<KeyPointResponseDto>(keyPoint);
                return new ApiResponse(true, keyPointDto);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取知识点时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> AddAsync(KeyPointDto model)
        {
            try
            {
                var existingKeyPoint = await _work.GetRepository<KeyPoint>().GetFirstOrDefaultAsync(
                    predicate: k => k.Key == model.Key && k.LessonID == model.LessonId);

                if (existingKeyPoint != null)
                {
                    return new ApiResponse($"知识点 '{model.Key}' 在此课程中已存在。");
                }

                var keyPoint = _mapper.Map<KeyPoint>(model);
                await _work.GetRepository<KeyPoint>().InsertAsync(keyPoint);

                if (await _work.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, _mapper.Map<KeyPointDto>(keyPoint));
                }
                return new ApiResponse("添加知识点失败。");
            }
            catch (Exception ex)
            {
                return new ApiResponse($"添加知识点时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> UpdateAsync(KeyPointDto model)
        {
            try
            {
                var existingKeyPoint = await _work.GetRepository<KeyPoint>().GetFirstOrDefaultAsync(
                    predicate: k => k.Id == model.Id);

                if (existingKeyPoint == null)
                {
                    return new ApiResponse("知识点未找到。");
                }

                _mapper.Map(model, existingKeyPoint);
                _work.GetRepository<KeyPoint>().Update(existingKeyPoint);

                if (await _work.SaveChangesAsync() > 0)
                {
                    return new ApiResponse(true, _mapper.Map<KeyPointDto>(existingKeyPoint));
                }
                return new ApiResponse("更新知识点失败。");
            }
            catch (Exception ex)
            {
                return new ApiResponse($"更新知识点时发生错误: {ex.Message}");
            }
        }

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

                if (existingKeyPoint == null)
                {
                    return new ApiResponse("知识点未找到。");
                }

                _work.GetRepository<KeyPoint>().Delete(existingKeyPoint);

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

        public async Task<ApiResponse> GetKeyPointsByLessonIdAsync(Guid lessonId)
        {
            try
            {
                var keyPoints = await _work.GetRepository<KeyPoint>().GetAllAsync(
                    predicate: k => k.LessonID == lessonId);

                var keyPointDtos = _mapper.Map<IEnumerable<KeyPointResponseDto>>(keyPoints);
                return new ApiResponse(true, keyPointDtos);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"根据课程ID获取知识点时发生错误: {ex.Message}");
            }
        }
    }
}
