using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Identity;
using SharedDATA.Api;
using TechHelper.Features;

namespace TechHelper.Services.Beta
{
	/// <summary>
	/// 用户服务实现类
	/// 处理用户相关的业务逻辑操作
	/// </summary>
	public class UserServices : IUserSerivces
	{

		private readonly IUnitOfWork _unitOfWork;
		private readonly IClassService _classService;
		private readonly UserManager<User> _userManager;
		private readonly IMapper _mapper;
		private readonly TechHelper.Features.IEmailSender _emailSender;

		/// <summary>
		/// 初始化用户服务
		/// </summary>
		/// <param name="unitOfWork">工作单元实例</param>
		/// <param name="classService">班级服务实例</param>
		/// <param name="userManager">用户管理实例</param>
		/// <param name="mapper">对象映射实例</param>
		/// <param name="emailSender">邮件发送实例</param>
		public UserServices(IUnitOfWork unitOfWork, IClassService classService, UserManager<User> userManager, IMapper mapper, IEmailSender emailSender)
		{
			_unitOfWork = unitOfWork;
			_classService = classService;
			_userManager = userManager;
			_mapper = mapper;
			_emailSender = emailSender;
		}

		/// <summary>
		/// 添加新用户
		/// </summary>
		/// <param name="model">用户实体对象</param>
		/// <returns>操作结果响应</returns>
		public async Task<ApiResponse> AddAsync(UserDto model)
		{
			try
			{
				//var user = _mapper.Map<User>(model);
				//user.UserName = model.Email;
				//user.EmailConfirmed = true;

				//var result = await _userManager.CreateAsync(user, model.Password ?? "TempPassword123!");

				//if (!result.Succeeded)
				//{
				//	var errors = result.Errors.Select(e => e.Description).ToList();
				//	return new ApiResponse(false, errors);
				//}

				return new ApiResponse(true, "用户添加成功");
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"添加用户失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 删除指定用户
		/// </summary>
		/// <param name="id">用户唯一标识符</param>
		/// <returns>操作结果响应</returns>
		public async Task<ApiResponse> DeleteAsync(Guid id)
		{
			try
			{
				var user = await _userManager.FindByIdAsync(id.ToString());
				if (user == null)
				{
					return new ApiResponse(false, "用户不存在");
				}

				var result = await _userManager.DeleteAsync(user);

				if (!result.Succeeded)
				{
					var errors = result.Errors.Select(e => e.Description).ToList();
					return new ApiResponse(false, errors);
				}

				return new ApiResponse(true, "用户删除成功");
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"删除用户失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 获取所有用户列表
		/// </summary>
		/// <param name="query">查询参数对象</param>
		/// <returns>用户列表响应</returns>
		public async Task<ApiResponse> GetAllAsync(QueryParameter query)
		{

			try
			{
				var repository = _unitOfWork.GetRepository<User>();

				if (query.Search != null && !string.IsNullOrWhiteSpace(query.Search))
				{
					var users = await repository.GetPagedListAsync(
						predicate: u => u.Email.Contains(query.Search) || u.DisplayName.Contains(query.Search),
						pageSize: query.PageSize,
						pageIndex: query.PageIndex
					);
					var userDtosFiltered = _mapper.Map<IEnumerable<UserListDto>>(users.Items);
					return new ApiResponse(true, userDtosFiltered);
				}
				else
				{
					var users = await repository.GetPagedListAsync(
						pageSize: query.PageSize,
						pageIndex: query.PageIndex
					);
					var userDtos = _mapper.Map<IEnumerable<UserListDto>>(users.Items);
					return new ApiResponse(true, userDtos);
				}
			}
			catch (Exception ex)
			{
				return new ApiResponse($"获取所有用户时发生错误: {ex.Message}");
			}
		}



		/// <summary>
		/// 获取指定用户信息
		/// </summary>
		/// <param name="id">用户唯一标识符</param>
		/// <returns>用户信息响应</returns>
		public async Task<ApiResponse> GetAsync(Guid id)
		{
			try
			{
				var user = await _userManager.FindByIdAsync(id.ToString());
				if (user == null)
				{
					return new ApiResponse(false, "用户不存在");
				}

				var userDto = _mapper.Map<UserDto>(user);
				return new ApiResponse(true, userDto);
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"获取用户信息失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 获取学生详细信息
		/// </summary>
		/// <param name="userId">用户唯一标识符</param>
		/// <returns>学生详细信息响应</returns>
		public async Task<ApiResponse> GetStudentDetailInfo(Guid userId)
		{
			try
			{
				var user = await _userManager.FindByIdAsync(userId.ToString());
				if (user == null)
				{
					return new ApiResponse(false, "用户不存在");
				}

				var studentDetail = new
				{
					user.Id,
					user.Email,
					user.DisplayName,
					user.PhoneNumber,
					user.Role,
					IsEmailConfirmed = user.EmailConfirmed,
					UserStatus = user.EmailConfirmed ? "Verified" : "Pending Verification"
				};

				return new ApiResponse(true, studentDetail);
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"获取学生详细信息失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 恢复用户角色信息
		/// 根据用户所在班级信息恢复用户的角色权限
		/// </summary>
		/// <param name="user">用户实体对象</param>
		/// <returns>操作结果响应</returns>
		public async Task<ApiResponse> RestoreUserRoleInformation(User user)
		{
			var result = await _classService.GetUserClassRole(user.Id);
			if (result.Status)
			{
				var classRole = result.Result as string;
				if (classRole != null)
				{
					if (!await _userManager.IsInRoleAsync(user, classRole))
					{
						await _userManager.AddToRoleAsync(user, classRole);

						return ApiResponse.Success();
					}
				}
			}
			return ApiResponse.Error();
		}

		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="model">用户实体对象</param>
		/// <returns>操作结果响应</returns>
		public async Task<ApiResponse> UpdateAsync(UserDto model)
		{
			try
			{
				var user = await _userManager.FindByIdAsync(model.Id.ToString());
				if (user == null)
				{
					return new ApiResponse(false, "用户不存在");
				}

				user.DisplayName = model.DisplayName;
				user.PhoneNumber = model.PhoneNumber;

				var result = await _userManager.UpdateAsync(user);

				if (!result.Succeeded)
				{
					var errors = result.Errors.Select(e => e.Description).ToList();
					return new ApiResponse(false, errors);
				}

				return new ApiResponse(true, "用户信息更新成功");
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"更新用户信息失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 验证用户信息
		/// </summary>
		/// <param name="userId">用户唯一标识符</param>
		/// <returns>验证结果响应</returns>
		public async Task<ApiResponse> VerifyUserInformation(Guid userId)
		{
			try
			{
				var user = await _userManager.FindByIdAsync(userId.ToString());
				if (user == null)
				{
					return new ApiResponse(false, "用户不存在");
				}

				// 验证邮箱确认状态
				var isEmailConfirmed = user.EmailConfirmed;

				// 验证用户角色
				var isInRole = await _userManager.IsInRoleAsync(user, "Student") ||
							   await _userManager.IsInRoleAsync(user, "Teacher");

				var verificationResult = new
				{
					UserId = user.Id,
					Email = user.Email,
					IsEmailConfirmed = isEmailConfirmed,
					HasValidRole = isInRole,
					DisplayName = user.DisplayName,
					Role = user.Role
				};

				if (isEmailConfirmed && isInRole)
				{
					return new ApiResponse(true, "用户信息验证成功");
				}
				else
				{
					return new ApiResponse(false, "用户信息验证失败");
				}
			}
			catch (Exception ex)
			{
				return new ApiResponse(false, $"验证用户信息失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 注册新用户，并根据角色关联到班级
		/// </summary>
		/// <param name="registrationDto">用户注册数据</param>
		/// <returns>操作结果</returns>
		public async Task<ApiResponse> RegisterNewUserAsync(UserForRegistrationDto registrationDto)
		{
			try
			{
				var existingUserByEmail = await _userManager.FindByEmailAsync(registrationDto.Email);
				if (existingUserByEmail != null)
				{
					return new ApiResponse("此电子邮件地址已被注册。");
				}

				var user = _mapper.Map<User>(registrationDto);

				user.UserName = registrationDto.Email;
				user.DisplayName = registrationDto.DisplayName;
				user.Role = registrationDto.Roles;
				user.EmailConfirmed = false;
				user.TeachSubjectId = registrationDto.RegisterUserToClassDto.SubjectArea;

				var result = await _userManager.CreateAsync(user, registrationDto.Password);


				if (!result.Succeeded)
				{
					var errors = result.Errors.Select(e => e.Description).ToList();
					return new ApiResponse(false, errors);
				}

				var userResult = await _userManager.FindByEmailAsync(user.Email);
				if (userResult == null)
					return ApiResponse.Error("注册失败，请联系管理员。");

				var roleResult = await _userManager.AddToRoleAsync(userResult, registrationDto.Roles.ToString());

				if (!roleResult.Succeeded)
				{
					var errors = roleResult.Errors.Select(e => e.Description).ToList();
					return new ApiResponse(false, errors);
				}

				registrationDto.RegisterUserToClassDto.UserId = userResult.Id;
				var classRegisterResult = await _classService.UserRegister(registrationDto.RegisterUserToClassDto);

				if (!classRegisterResult.Status)
				{
					if (userResult != null)
						await _userManager.DeleteAsync(userResult);

					return new ApiResponse(false, classRegisterResult.Message ?? "Class registration failed");
				}

				return new ApiResponse(true, "操作成功。");

				//var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
				//var encodedToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(emailConfirmationToken));
				//var callbackUrl = QueryHelpers.AddQueryString(registrationDto.ClientURI, new Dictionary<string, string>
				//{
				//	{"token", encodedToken},
				//	{"email", user.Email} 
				//});

				//try
				//{
				//	await _emailSender.SendEmailAsync(user.Email, "请确认您的邮箱", $"请点击此链接确认您的邮箱: {callbackUrl}");
				//}
				//catch (Exception ex)
				//{
				//	Console.Error.WriteLine($"发送邮箱确认邮件失败: {ex.Message}");
				//}

			}
			catch (Exception ex)
			{
				var userResult = await _userManager.FindByEmailAsync(registrationDto.Email);
				if (userResult != null)
					await _userManager.DeleteAsync(userResult);
				return new ApiResponse(false, "注册过程中发生错误");
			}
		}

		public async Task<ApiResponse> InitAdminUser(UserForAdmin admin)
		{
			try
			{
				var existingUserByEmail = await _userManager.FindByEmailAsync(admin.Email);
				if (existingUserByEmail != null)
				{
					return new ApiResponse("此电子邮件地址已被注册。");
				}
				var user = new User { Role = UserRoles.Admin, DisplayName = admin.DisplayName, Email = admin.Email, UserName = admin.Email };

				var result = await _userManager.CreateAsync(user, admin.Password);
				if (!result.Succeeded)
				{
					return ApiResponse.Error("管理员用户创建失败, 用户注册时失败");
				}
				
				await _userManager.AddToRoleAsync(user, UserRoles.Admin.ToString());
				
				await _unitOfWork.GetRepository<School>().InsertAsync(new School { SchoolName = admin.SchoolName, CreateTime = DateTime.Now, Address = admin.Address });

				if (await _unitOfWork.SaveChangesAsync() > 0)
				{
					return ApiResponse.Success("管理员用户创建成功");
				}
				return ApiResponse.Error("管理员用户创建失败");
			}
			catch (Exception ex)
			{
				return ApiResponse.Error($"创建失败: {ex.Message}");
			}
		}
	}
}
