using System.Xml.Serialization; // 用于 XML 序列化/反序列化
using TechHelper.Client.AI;
using Entities.DTO;
using System.Net.Http.Json; // 用于 PostAsJsonAsync
using Newtonsoft.Json;

namespace TechHelper.Client.Services
{
	public class ExamService : IExamService
	{
		private readonly IAIService _aIService;
		private readonly HttpClient _client;

		public ExamService(IAIService aIService, HttpClient client)
		{
			_aIService = aIService;
			_client = client;
		}

		public ApiResponse ConvertToXML<T>(string xmlContent)
		{
			string cleanedXml = xmlContent.Trim();
			XmlSerializer serializer = new XmlSerializer(typeof(T));

			using (StringReader reader = new StringReader(cleanedXml))
			{
				try
				{
					T deserializedObject = (T)serializer.Deserialize(reader);
					return ApiResponse.Success(result: deserializedObject, message: "XML 反序列化成功。");
				}
				catch (InvalidOperationException ex)
				{
					return ApiResponse.Error(
						message: $"XML 反序列化操作错误: {ex.Message}. 内部异常: {ex.InnerException?.Message ?? "无"}");
				}
				catch (Exception ex)
				{
					return ApiResponse.Error(message: $"处理 XML 反序列化时发生未知错误: {ex.Message}");
				}
			}
		}

		public async Task<ApiResponse> DividExam(string examContent)
		{
			try
			{
				string? response = await _aIService.CallGLM(examContent, AIConfiguration.BreakQuestions);

				if (response != null)
				{
					return ApiResponse.Success(result: response, message: "试题分割成功。");
				}
				else
				{
					return ApiResponse.Error(message: "AI 服务未能返回有效内容，或返回内容为空。");
				}
			}
			catch (Exception ex)
			{
				// 实际应用中，这里应该加入日志记录
				return ApiResponse.Error(message: $"处理试题分割时发生内部错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> FormatExam(string examContent)
		{
			try
			{
				string? response = await _aIService.CallGLM(examContent, AIConfiguration.Format);

				if (response != null)
				{
					return ApiResponse.Success(result: response, message: "试题格式化成功。");
				}
				else
				{
					return ApiResponse.Error(message: "AI 服务未能返回有效内容，或返回内容为空。");
				}
			}
			catch (Exception ex)
			{
				// 实际应用中，这里应该加入日志记录
				return ApiResponse.Error(message: $"处理试题格式化时发生内部错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> GetAllExam()
		{
			var response = await _client.GetAsync($"exam/getAllPreview");

			if (response.IsSuccessStatusCode)
			{
				var content = await response.Content.ReadAsStringAsync();
				var result = JsonConvert.DeserializeObject<List<ExamDto>>(content);
				return ApiResponse.Success(result: result);
			}
			else
			{
				// 读取错误信息，并返回 ApiResponse
				var errorContent = await response.Content.ReadAsStringAsync();
				return ApiResponse.Error(message: $"获取所有试题失败: {response.StatusCode} - {errorContent}");
			}
		}

		public async Task<ApiResponse> GetAllSubmission()
		{
			try
			{
				var response = await _client.GetAsync($"exam/getAllSubmission");
				if (response.IsSuccessStatusCode)
				{
					var content = await response.Content.ReadAsStringAsync();
					var exam = JsonConvert.DeserializeObject<ExamDto>(content);
					return ApiResponse.Success();
				}
				return ApiResponse.Error(message: "获取失败");
			}
			catch (Exception ex)
			{
				return ApiResponse.Error(message: $"内部错误{ex.Message}, InerEx{ex.InnerException}");
			}
		}

		public async Task<ApiResponse> GetExam(Guid guid)
		{

			var response = await _client.GetAsync($"exam/{guid}");
			if (response.IsSuccessStatusCode)
			{
				var content = await response.Content.ReadAsStringAsync();
				var exam = JsonConvert.DeserializeObject<ExamDto>(content);
				return ApiResponse.Success(result: exam);
			}
			else
			{
				var errorContent = await response.Content.ReadAsStringAsync();
				return ApiResponse.Error(message: $"获取试题失败: {response.StatusCode} - {errorContent}");
			}
		}

		public async Task<ApiResponse> ParseSingleQuestionGroup(string examContent)
		{
			try
			{
				string? response = await _aIService.CallGLM(examContent, AIConfiguration.ParseSignelQuestion2);

				if (response != null)
				{
					return ApiResponse.Success(result: response, message: "试题解析成功。");
				}
				else
				{
					return ApiResponse.Error(message: "AI 服务未能返回有效内容，或返回内容为空。");
				}
			}
			catch (Exception ex)
			{
				// 实际应用中，这里应该加入日志记录
				return ApiResponse.Error(message: $"处理试题解析时发生内部错误: {ex.Message}");
			}
		}

		public async Task<ApiResponse> SaveParsedExam(ExamDto assiDto)
		{
			// 直接使用注入的 _client 实例
			var response = await _client.PostAsJsonAsync("exam/add", assiDto);

			if (response.IsSuccessStatusCode)
			{
				return ApiResponse.Success(message: "试题保存成功。");
			}
			else
			{
				var errorContent = await response.Content.ReadAsStringAsync();
				return ApiResponse.Error(message: $"保存试题失败: {response.StatusCode} - {errorContent}");
			}
		}

		public async Task<ApiResponse> SubmissionAssignment(SubmissionDto submission)
		{
			var response = await _client.PostAsJsonAsync("exam/submission", submission);
			if (response.IsSuccessStatusCode)
			{
				return ApiResponse.Success("提交成功");
			}
			else
			{
				return ApiResponse.Error("提交失败");
			}
		}
	}
}