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

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

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

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

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

        public async Task<ApiResponse> GetAsync(Guid id)
        {
            try
            {
                var examType = await _work.GetRepository<ExamType>().GetFirstOrDefaultAsync(
                    predicate: et => et.Id == id,
                    include: i => i
                        .Include(et => et.Exams));

                if (examType == null)
                {
                    return new ApiResponse("考试类型未找到。");
                }

                var examTypeDto = _mapper.Map<ExamTypeResponseDto>(examType);
                return new ApiResponse(true, examTypeDto);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取考试类型时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> AddAsync(ExamTypeDto model)
        {
            try
            {
                // 检查是否已存在同名考试类型
                var existingExamType = await _work.GetRepository<ExamType>().GetFirstOrDefaultAsync(
                    predicate: et => et.Name == model.Name);

                if (existingExamType != null)
                {
                    return new ApiResponse($"考试类型 '{model.Name}' 已存在。");
                }

                var examType = _mapper.Map<ExamType>(model);
                await _work.GetRepository<ExamType>().InsertAsync(examType);

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

        public async Task<ApiResponse> UpdateAsync(ExamTypeDto model)
        {
            try
            {
                var existingExamType = await _work.GetRepository<ExamType>().GetFirstOrDefaultAsync(
                    predicate: et => et.Id == model.Id);

                if (existingExamType == null)
                {
                    return new ApiResponse("考试类型未找到。");
                }

                // 检查是否要修改为已存在的考试类型名称（排除当前考试类型）
                var examTypeWithSameName = await _work.GetRepository<ExamType>().GetFirstOrDefaultAsync(
                    predicate: et => et.Name == model.Name && et.Id != model.Id);

                if (examTypeWithSameName != null)
                {
                    return new ApiResponse($"考试类型名称 '{model.Name}' 已被其他考试类型使用。");
                }

                _mapper.Map(model, existingExamType);
                _work.GetRepository<ExamType>().Update(existingExamType);

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

        public async Task<ApiResponse> DeleteAsync(Guid id)
        {
            try
            {
                var existingExamType = await _work.GetRepository<ExamType>().GetFirstOrDefaultAsync(
                    predicate: et => et.Id == id,
                    include: i => i.Include(et => et.Exams));

                if (existingExamType == null)
                {
                    return new ApiResponse("考试类型未找到。");
                }

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

                _work.GetRepository<ExamType>().Delete(existingExamType);

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