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

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

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

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

				if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
				{
					var questionTypes = await repository.GetPagedListAsync(
						predicate: qt => qt.Name.Contains(query.Search) || qt.Description.Contains(query.Search),
						pageSize: query.PageSize,
						pageIndex: query.PageIndex
					);
					var questionTypeDtosFiltered = _mapper.Map<IEnumerable<TypeCommonDto>>(questionTypes.Items);
					return new ApiResponse(true, questionTypeDtosFiltered);
				}
				else
				{
					var questionTypes = await repository.GetPagedListAsync(
						pageSize: query.PageSize,
						pageIndex: query.PageIndex,
						include: i => i.Include(qt => qt.Subject)
					);
					var questionTypeDtos = _mapper.Map<IEnumerable<TypeCommonDto>>(questionTypes.Items);
					return new ApiResponse(true, questionTypeDtos);
				}
			}
			catch (Exception ex)
			{
				return new ApiResponse($"获取所有题型时发生错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> GetAsync(Guid id)
		{
			try
			{
				var questionType = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(
					predicate: qt => qt.Id == id,
					include: i => i
						.Include(qt => qt.Subject)
						.Include(qt => qt.Questions));

				if (questionType == null)
				{
					return new ApiResponse("题型未找到。");
				}

				var questionTypeDto = _mapper.Map<QuestionTypeResponseDto>(questionType);
				return new ApiResponse(true, questionTypeDto);
			}
			catch (Exception ex)
			{
				return new ApiResponse($"获取题型时发生错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> AddAsync(QuestionTypeDto model)
		{
			try
			{
				var QuestionTypeExists = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(predicate: qt => qt.Id == model.Id);
				if (QuestionTypeExists != null)
				{
					if (QuestionTypeExists.Name == model.Name && QuestionTypeExists.SubjectId == model.SubjectId)
						return new ApiResponse("题型已存在。");
					else
						return new ApiResponse($"主键已被 '{QuestionTypeExists.Name}' 题型使用。");
				}
				// 检查科目是否存在
				var subjectExists = await _work.GetRepository<Subject>().GetFirstOrDefaultAsync(
					predicate: s => s.Id == model.SubjectId);

				if (subjectExists == null)
				{
					return new ApiResponse("指定的科目不存在。");
				}

				// 检查是否已存在相同科目下的同名题型
				var existingQuestionType = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(
					predicate: qt => qt.SubjectId == model.SubjectId && qt.Name == model.Name);

				if (existingQuestionType != null)
				{
					return new ApiResponse($"在当前科目下，题型 '{model.Name}' 已存在。");
				}

				var questionType = _mapper.Map<QuestionType>(model);
				await _work.GetRepository<QuestionType>().InsertAsync(questionType);

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

		public async Task<ApiResponse> UpdateAsync(QuestionTypeDto model)
		{
			try
			{
				var existingQuestionType = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(
					predicate: qt => qt.Id == model.Id);

				if (existingQuestionType == null)
				{
					return new ApiResponse("题型未找到。");
				}

				// 检查科目是否存在
				var subjectExists = await _work.GetRepository<Subject>().GetFirstOrDefaultAsync(
					predicate: s => s.Id == model.SubjectId);

				if (subjectExists == null)
				{
					return new ApiResponse("指定的科目不存在。");
				}

				// 检查是否要修改为已存在的题型名称（排除当前题型）
				var questionTypeWithSameName = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(
					predicate: qt => qt.Name == model.Name && qt.Id != model.Id && qt.SubjectId == model.SubjectId);

				if (questionTypeWithSameName != null)
				{
					return new ApiResponse($"在当前科目下，题型名称 '{model.Name}' 已被其他题型使用。");
				}

				_mapper.Map(model, existingQuestionType);
				_work.GetRepository<QuestionType>().Update(existingQuestionType);

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

		public async Task<ApiResponse> DeleteAsync(Guid id)
		{
			try
			{
				var existingQuestionType = await _work.GetRepository<QuestionType>().GetFirstOrDefaultAsync(
					predicate: qt => qt.Id == id,
					include: i => i.Include(qt => qt.Questions));

				if (existingQuestionType == null)
				{
					return new ApiResponse("题型未找到。");
				}

				// 检查是否有关联的题目
				if (existingQuestionType.Questions != null && existingQuestionType.Questions.Any())
				{
					return new ApiResponse("无法删除该题型，因为存在关联的题目。");
				}

				_work.GetRepository<QuestionType>().Delete(existingQuestionType);

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