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

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

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

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

                if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
                {
                    var schools = await repository.GetPagedListAsync(
                        predicate: s => s.SchoolName.Contains(query.Search),
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var schoolDtosFiltered = _mapper.Map<IEnumerable<SchoolDto>>(schools.Items);
                    return new ApiResponse(true, schoolDtosFiltered);
                }
                else
                {
                    var schools = await repository.GetPagedListAsync(
                        pageSize: query.PageSize,
                        pageIndex: query.PageIndex
                    );
                    var schoolDtos = _mapper.Map<IEnumerable<SchoolDto>>(schools.Items);
                    return new ApiResponse(true, schoolDtos);
                }
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取所有学校时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetAsync(Guid id)
        {
            try
            {
                var school = await _work.GetRepository<School>().GetFirstOrDefaultAsync(
                    predicate: s => s.Id == id,
					include: i
					=> i.Include(s => s.Grades));

                if (school == null)
                {
                    return new ApiResponse("学校未找到。");
                }

                var schoolDto = _mapper.Map<SchoolResponseDto>(school);
                return new ApiResponse(true, schoolDto);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"获取学校时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetSchoolByNameAsync(string schoolName)
        {
            try
            {
                var school = await _work.GetRepository<School>().GetFirstOrDefaultAsync(
                    predicate: s => s.SchoolName == schoolName,
                    include: i
                    =>i.Include(s => s.Grades));

                if (school == null)
                {
                    return new ApiResponse("学校未找到。");
                }

                var schoolDto = _mapper.Map<SchoolResponseDto>(school);
                return new ApiResponse(true, schoolDto);
            }
            catch (Exception ex)
            {
                return new ApiResponse($"根据名称获取学校时发生错误: {ex.Message}");
            }
        }

        public async Task<ApiResponse> AddAsync(SchoolDto model)
        {
            try
            {
                // 检查是否已存在同名学校
                var existingSchool = await _work.GetRepository<School>().GetFirstOrDefaultAsync(
                    predicate: s => s.SchoolName == model.SchoolName);

                if (existingSchool != null)
                {
                    return new ApiResponse($"学校 '{model.SchoolName}' 已存在。");
                }

                var school = _mapper.Map<School>(model);
                await _work.GetRepository<School>().InsertAsync(school);

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

        public async Task<ApiResponse> UpdateAsync(SchoolDto model)
        {
            try
            {
                var existingSchool = await _work.GetRepository<School>().GetFirstOrDefaultAsync(
                    predicate: s => s.Id == model.Id);

                if (existingSchool == null)
                {
                    return new ApiResponse("学校未找到。");
                }

                _mapper.Map(model, existingSchool);
                _work.GetRepository<School>().Update(existingSchool);

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

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

                if (existingSchool == null)
                {
                    return new ApiResponse("学校未找到。");
                }

                _work.GetRepository<School>().Delete(existingSchool);

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