namespace WebApi.Controllers.EmailMessage; [ApiController] [Route("api/[controller]/[action]")] public class EmailMessageController( IEmailMessageRepository emailRepository, ITransactionRecordRepository transactionRepository, ILogger logger, IEmailHandleService emailHandleService, IEmailBackgroundService emailBackgroundService ) : ControllerBase { /// /// 获取邮件列表(分页) /// [HttpGet] public async Task> GetListAsync( [FromQuery] DateTime? lastReceivedDate = null, [FromQuery] long? lastId = null ) { try { var (list, lastTime, lastIdResult) = await emailRepository.GetPagedListAsync(lastReceivedDate, lastId); var total = await emailRepository.GetTotalCountAsync(); // 为每个邮件获取账单数量 var emailDtos = new List(); foreach (var email in list) { var transactionCount = await transactionRepository.GetCountByEmailIdAsync(email.Id); emailDtos.Add(EmailMessageDto.FromEntity(email, transactionCount)); } return new PagedResponse { Success = true, Data = emailDtos.ToArray(), Total = (int)total, LastId = lastIdResult, LastTime = lastTime }; } catch (Exception ex) { logger.LogError(ex, "获取邮件列表失败,时间: {LastTime}, ID: {LastId}", lastReceivedDate, lastId); return PagedResponse.Fail($"获取邮件列表失败: {ex.Message}"); } } /// /// 根据ID获取邮件详情 /// [HttpGet("{id}")] public async Task> GetByIdAsync(long id) { try { var email = await emailRepository.GetByIdAsync(id); if (email == null) { return BaseResponse.Fail("邮件不存在"); } // 获取账单数量 var transactionCount = await transactionRepository.GetCountByEmailIdAsync(id); var emailDto = EmailMessageDto.FromEntity(email, transactionCount); return new BaseResponse { Success = true, Data = emailDto }; } catch (Exception ex) { logger.LogError(ex, "获取邮件详情失败,邮件ID: {EmailId}", id); return BaseResponse.Fail($"获取邮件详情失败: {ex.Message}"); } } public async Task DeleteByIdAsync(long id) { try { var success = await emailRepository.DeleteAsync(id); if (success) { return new BaseResponse { Success = true }; } else { return BaseResponse.Fail("删除邮件失败,邮件不存在"); } } catch (Exception ex) { logger.LogError(ex, "删除邮件失败,邮件ID: {EmailId}", id); return BaseResponse.Fail($"删除邮件失败: {ex.Message}"); } } /// /// 重新分析邮件并刷新交易记录 /// [HttpPost] public async Task RefreshTransactionRecordsAsync([FromQuery] long id) { try { var email = await emailRepository.GetByIdAsync(id); if (email == null) { return BaseResponse.Fail("邮件不存在"); } var success = await emailHandleService.RefreshTransactionRecordsAsync(id); if (success) { return new BaseResponse { Success = true }; } else { return BaseResponse.Fail("重新分析失败"); } } catch (Exception ex) { logger.LogError(ex, "重新分析邮件失败,邮件ID: {EmailId}", id); return BaseResponse.Fail($"重新分析失败: {ex.Message}"); } } /// /// 立即同步邮件 /// [HttpPost] public async Task SyncEmailsAsync() { try { await emailBackgroundService.SyncEmailsAsync(); return new BaseResponse { Success = true, Message = "同步成功" }; } catch (Exception ex) { logger.LogError(ex, "同步邮件失败"); return BaseResponse.Fail($"同步邮件失败: {ex.Message}"); } } }