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

namespace TechHelper.Services.Beta
{
	public class ExamQuestionService : IExamQuestionService
	{
		private readonly IUnitOfWork _work;
		private readonly IMapper _mapper;
		private readonly IClassService _classService;

		public ExamQuestionService(IUnitOfWork work, IMapper mapper, IClassService classService)
		{
			_work = work;
			_mapper = mapper;
			_classService = classService;
		}

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

				if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
				{
					var examQuestions = await repository.GetPagedListAsync(
						predicate: eq => eq.Title.Contains(query.Search) && eq.ParentExamQuestionId == null,
						pageSize: query.PageSize,
						pageIndex: query.PageIndex
					);
					var examQuestionDtosFiltered = _mapper.Map<IEnumerable<ExamQuestionDto>>(examQuestions.Items);
					return new ApiResponse(true, examQuestionDtosFiltered);
				}
				else
				{
					var examQuestions = await repository.GetPagedListAsync(
						predicate: eq => eq.ParentExamQuestionId == null,
						pageSize: query.PageSize,
						pageIndex: query.PageIndex
					);
					var examQuestionDtos = _mapper.Map<IEnumerable<ExamQuestionDto>>(examQuestions.Items);
					return new ApiResponse(true, examQuestionDtos);
				}
			}
			catch (Exception ex)
			{
				return new ApiResponse($"获取所有考试题目时发生错误: {ex.Message}");
			}
		}

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

				if (examQuestion == null)
				{
					return new ApiResponse("考试题目未找到。");
				}

				var examQuestionDto = _mapper.Map<ExamQuestionDto>(examQuestion);
				return new ApiResponse(true, examQuestionDto);
			}
			catch (Exception ex)
			{
				return new ApiResponse($"获取考试题目时发生错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> AddAsync(ExamQuestionDto model)
		{
			try
			{
				// 检查是否已存在相同考试和题目的组合
				var existingExamQuestion = await _work.GetRepository<ExamQuestion>().GetFirstOrDefaultAsync(
					predicate: eq => eq.Id == model.Id/* && eq.QuestionId == model.Question.Id*/);

				if (existingExamQuestion != null)
				{
					return new ApiResponse($"该题目已在此考试中存在。");
				}

				var examQuestion = _mapper.Map<ExamQuestion>(model);

				await _work.GetRepository<ExamQuestion>().InsertAsync(examQuestion);

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

		public async Task<ApiResponse> UpdateAsync(ExamQuestionDto model)
		{
			try
			{
				var existingExamQuestion = await _work.GetRepository<ExamQuestion>().GetFirstOrDefaultAsync(
					predicate: eq => eq.Id == model.Id);

				if (existingExamQuestion == null)
				{
					return new ApiResponse("考试题目未找到。");
				}

				// 检查是否要修改为已存在的考试题目组合（排除当前记录）
				var examQuestionWithSameCombination = await _work.GetRepository<ExamQuestion>().GetFirstOrDefaultAsync(
					predicate: eq => eq.Id == model.Id /*&& eq.QuestionId == model.QuestionId*/ && eq.Id != model.Id);

				if (examQuestionWithSameCombination != null)
				{
					return new ApiResponse($"该题目与考试的组合已存在。");
				}

				_mapper.Map(model, existingExamQuestion);
				_work.GetRepository<ExamQuestion>().Update(existingExamQuestion);

				if (await _work.SaveChangesAsync() > 0)
				{
					var examQuestionDto = _mapper.Map<ExamQuestionDto>(existingExamQuestion);
					return new ApiResponse(true, examQuestionDto);
				}
				return new ApiResponse("更新考试题目失败。");
			}
			catch (Exception ex)
			{
				return new ApiResponse($"更新考试题目时发生错误: {ex.Message}");
			}
		}

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

				if (existingExamQuestion == null)
				{
					return new ApiResponse("考试题目未找到。");
				}

				_work.GetRepository<ExamQuestion>().Delete(existingExamQuestion);

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

		public async Task<ApiResponse> GetQuestionDependy(QuesitionDenpendceyRequst request)
		{
			try
			{
				var classStudentsResponse = await _classService.GetClassStudentsAsync(request.ClassId);
				if (!classStudentsResponse.Status) return ApiResponse.Error(classStudentsResponse.Message);

				var classStudents = classStudentsResponse.Result as IEnumerable<UserListDto>;
				if (classStudents == null) return ApiResponse.Error("班级学生列表为空。");

				var submissionResult = await _work.GetRepository<SubmissionDetail>().GetAllAsync(predicate: sd => sd.ExamQuestionId == request.ExamQuestioId );
				var submission = submissionResult.Where(s => classStudents.Any(c => c.Id == s.StudentId));
				var errorStudents = submission.Select(s => s.Student);
				var scores = submission.Select(s => s.PointsAwarded);
				var lesson = submission.FirstOrDefault()?.ExamQuestion?.Question?.Lesson ?? null;
				var lessonDto = _mapper.Map<LessonDto>(lesson);
				var ErrorStudentDtro = _mapper.Map<IEnumerable<UserListDto>>(errorStudents);
				return ApiResponse.Success("获取成功", new QuestionDependecyDto(lessonDto, scores, ErrorStudentDtro));

			}
			catch (Exception ex)
			{
				return ApiResponse.Error($"获取考试题目密度时发生错误: {ex.Message}");
			}
		}
	}
}
