using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using Microsoft.EntityFrameworkCore;
using SharedDATA.Api;
using TechHelper.Context;
using TechHelper.Repository;
using TechHelper.Server.Repositories;
using TechHelper.Services;

namespace TechHelper.Server.Services
{
    public class StudentSubmissionService : IStudentSubmissionService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMapper _mapper;
        private readonly IRepository<Submission> _submissionRepository;
        private readonly IRepository<Exam> _assignmentRepository;
        private readonly IRepository<User> _userRepository;

        public StudentSubmissionService(
            IUnitOfWork unitOfWork, 
            IMapper mapper,
            IRepository<Submission> submissionRepository,
            IRepository<Exam> assignmentRepository,
            IRepository<User> userRepository)
        {
            _unitOfWork = unitOfWork;
            _mapper = mapper;
            _submissionRepository = submissionRepository;
            _assignmentRepository = assignmentRepository;
            _userRepository = userRepository;
        }

        public async Task<ApiResponse> GetStudentSubmissionsAsync(Guid studentId)
        {
            try
            {
                var submissions = await _submissionRepository
                    .GetAll(s => s.StudentId == studentId)
                    .Include(s => s.Exam)
                    .ThenInclude(a => a.Creator)
                    .OrderByDescending(s => s.SubmissionTime)
                    .ToListAsync();

                var result = new List<StudentSubmissionSummaryDto>();

                foreach (var submission in submissions)
                {
                    var summary = new StudentSubmissionSummaryDto
                    {
                        Id = submission.Id,
                        AssignmentName = submission.Exam?.Title ?? "未知作业",
                        ErrorCount = await CalculateErrorCountAsync(submission.Id),
                        CreatedDate = submission.SubmissionTime,
                        Score = (int)submission.OverallGrade,
                        TotalQuestions = submission.Exam?.TotalQuestions ?? 0,
                        StudentName = submission.Exam?.Creator?.UserName ?? "未知老师",
                        Status = submission.Status.ToString()
                    };
                    result.Add(summary);
                }

                return ApiResponse.Success(result: result);
            }
            catch (Exception ex)
            {
                return ApiResponse.Error($"获取学生提交信息失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetStudentSubmissionsPagedAsync(Guid studentId, int pageNumber = 1, int pageSize = 10)
        {
            try
            {
                var totalCount = await _submissionRepository
                    .GetAll(s => s.StudentId == studentId)
                    .CountAsync();

                var submissions = await _submissionRepository
                    .GetAll(s => s.StudentId == studentId)
                    .Include(s => s.Exam)
                    .ThenInclude(a => a.Creator)
                    .OrderByDescending(s => s.SubmissionTime)
                    .Skip((pageNumber - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                var result = new List<StudentSubmissionSummaryDto>();

                foreach (var submission in submissions)
                {
                    var summary = new StudentSubmissionSummaryDto
                    {
                        Id = submission.Id,
                        AssignmentName = submission.Exam?.Title ?? "未知作业",
                        ErrorCount = await CalculateErrorCountAsync(submission.Id),
                        CreatedDate = submission.SubmissionTime,
                        Score = submission.OverallGrade,
                        TotalQuestions = submission.Exam?.TotalQuestions ?? 0,
                        StudentName = submission.Exam?.Creator?.UserName ?? "未知老师",
                        Status = submission.Status.ToString()
                    };
                    result.Add(summary);
                }

                var response = new StudentSubmissionSummaryResponseDto
                {
                    Submissions = result,
                    TotalCount = totalCount
                };

                return ApiResponse.Success(result: response);
            }
            catch (Exception ex)
            {
                return ApiResponse.Error($"获取学生提交信息失败: {ex.Message}");
            }
        }

        private async Task<int> CalculateErrorCountAsync(Guid submissionId)
        {

            var submissionDetails = await _unitOfWork.GetRepository<SubmissionDetail>()
                .GetAll(sd => sd.SubmissionId == submissionId)
                .ToListAsync();
            return submissionDetails.Select(x => !x.IsCorrect).Count();
        }

        // 以下方法是IBaseService接口的实现，可以根据需要实现
        public Task<ApiResponse> GetAllAsync() => throw new NotImplementedException();
        public Task<ApiResponse> GetAsync(Guid id) => throw new NotImplementedException();
        public Task<ApiResponse> AddAsync(StudentSubmissionSummaryDto model) => throw new NotImplementedException();
        public Task<ApiResponse> UpdateAsync(StudentSubmissionSummaryDto model) => throw new NotImplementedException();
        public Task<ApiResponse> DeleteAsync(Guid id) => throw new NotImplementedException();

		public Task<ApiResponse> GetAllAsync(QueryParameter query)
		{
			throw new NotImplementedException();
		}
	}
}
