using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MimeKit;
using Myshipping.Application.Entity;
using Myshipping.Application.Helper;
using Myshipping.Core;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Crypto;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Myshipping.Application
{
///
/// 邮件接收记录服务
///
[ApiDescriptionSettings("Application", Name = "EmaiReceiveRecordService", Order = 9)]
public class EmaiReceiveRecordService : IEmaiReceiveRecordService, IDynamicApiController, ITransient
{
private readonly SqlSugarRepository _emaiReceiveRecordeInfoRepository;
private readonly SqlSugarRepository _emaiReceiveRecordDetailInfoRepository;
private readonly ILogger _logger;
public EmaiReceiveRecordService(ILogger logger,
SqlSugarRepository emaiReceiveRecordeInfoRepository,
SqlSugarRepository emaiReceiveRecordDetailInfoRepository)
{
_logger = logger;
_emaiReceiveRecordeInfoRepository = emaiReceiveRecordeInfoRepository;
_emaiReceiveRecordDetailInfoRepository = emaiReceiveRecordDetailInfoRepository;
}
#region 获取邮件接收记录详情
///
/// 获取邮件接收记录详情
///
/// 邮件接收记录主键
/// 返回回执
[HttpGet("/EmaiReceiveRecord/GetInfo")]
public async Task GetInfo(string gid)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (string.IsNullOrWhiteSpace(gid))
{
throw Oops.Oh($"邮件接收记录主键不能为空", typeof(InvalidOperationException));
}
var model = await _emaiReceiveRecordeInfoRepository.AsQueryable().FirstAsync(a => a.GID == gid);
if (model == null)
throw Oops.Oh($"邮件接收记录获取失败,邮件接收记录不存在或已作废", typeof(InvalidOperationException));
var showModel = model.Adapt();
result.succ = true;
result.ext = showModel;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"获取邮件接收记录异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 删除
///
/// 删除
///
/// 邮件接收记录主键数组
/// 返回回执
[HttpPost("/EmaiReceiveRecord/Delete")]
public async Task Delete([FromBody] string[] gIds)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (gIds.Length == 0)
{
throw Oops.Oh($"邮件接收记录主键数组不能为空", typeof(InvalidOperationException));
}
var list = _emaiReceiveRecordeInfoRepository.AsQueryable()
.Where(a => gIds.Contains(a.GID)).ToList();
if (list.Count == 0)
throw Oops.Oh($"邮件接收记录获取失败,请确认邮件接收记录是否存在", typeof(InvalidOperationException));
if (list.Count != gIds.Length)
throw Oops.Oh($"部分邮件接收记录获取失败,请确认邮件接收记录是否存在", typeof(InvalidOperationException));
List rltList = new List();
list.ForEach(async record =>
{
await _emaiReceiveRecordeInfoRepository.UpdateAsync(x => x.GID == record.GID,
x => new EmaiReceiveRecordInfo { IsDeleted = true });
});
result.succ = true;
result.msg = "删除成功";
_logger.LogInformation("删除邮件接收记录成功 ids={id} user={usr}", gIds, UserManager.UserId);
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"删除邮件接收记录异常,原因:{ex.Message}";
}
return result;
}
#endregion
#region 邮件接收记录台账查询
///
/// 邮件接收记录台账查询
///
/// 邮件接收记录台账查询请求
/// 返回结果
[HttpPost("/EmaiReceiveRecord/GetPage")]
public async Task> GetPageAsync(QueryEmaiReceiveRecordDto QuerySearch)
{
var query = _emaiReceiveRecordeInfoRepository.AsQueryable();
#region 查询条件
//接收时间起始
if (!string.IsNullOrWhiteSpace(QuerySearch.RecBegin))
{
DateTime currDate = DateTime.MinValue;
if (!DateTime.TryParse(QuerySearch.RecBegin, out currDate))
throw Oops.Oh($"接收时间起始日期格式错误,{QuerySearch.RecBegin}");
query = query.Where(t => t.REC_TIME >= currDate);
}
//接收时间结束
if (!string.IsNullOrWhiteSpace(QuerySearch.RecEnd))
{
DateTime currDate = DateTime.MinValue;
if (!DateTime.TryParse(QuerySearch.RecEnd, out currDate))
throw Oops.Oh($"接收时间结束日期格式错误,{QuerySearch.RecEnd}");
currDate = currDate.AddDays(1);
query = query.Where(t => t.REC_TIME < currDate);
}
//更新时间起始
if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateBegin))
{
DateTime currDate = DateTime.MinValue;
if (!DateTime.TryParse(QuerySearch.UpdateBegin, out currDate))
throw Oops.Oh($"更新时间起始日期格式错误,{QuerySearch.UpdateBegin}");
query = query.Where(t => t.UpdatedTime >= currDate);
}
//更新时间结束
if (!string.IsNullOrWhiteSpace(QuerySearch.UpdateEnd))
{
DateTime currDate = DateTime.MinValue;
if (!DateTime.TryParse(QuerySearch.UpdateEnd, out currDate))
throw Oops.Oh($"更新时间结束日期格式错误,{QuerySearch.UpdateEnd}");
currDate = currDate.AddDays(1);
query = query.Where(t => t.UpdatedTime < currDate);
}
if(!string.IsNullOrWhiteSpace(QuerySearch.MailSubject))
{
query = query.Where(t => t.MAIL_SUBJECT.Contains(QuerySearch.MailSubject));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.Sender))
{
query = query.Where(t => t.SENDER.Contains(QuerySearch.Sender));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.MailAccount))
{
query = query.Where(t => t.MAIL_ACCOUNT.Contains(QuerySearch.MailAccount));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.StepNote))
{
query = query.Where(t => t.STEP_NOTE.Contains(QuerySearch.StepNote));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.Status))
{
query = query.Where(t => t.STATUS.Equals(QuerySearch.Status));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.IsParse))
{
query = query.Where(t => t.IS_PARSE == (QuerySearch.IsParse == "1" ? true : false));
}
if (!string.IsNullOrWhiteSpace(QuerySearch.IsProcess))
{
query = query.Where(t => t.IS_PROCESS == (QuerySearch.IsProcess == "1" ? true : false));
}
#endregion
string entityOrderCol = "REC_TIME";
//这里因为返回给前端的台账数据是DTO,所以这里排序时候需要转换成Entity对应的字段
if (!string.IsNullOrWhiteSpace(QuerySearch.SortField))
entityOrderCol = MapsterExtHelper.GetAdaptProperty(QuerySearch.SortField);
var entities = await query
.OrderBy(entityOrderCol + (QuerySearch.descSort ? " asc " : " desc "))
.ToPagedListAsync(QuerySearch.PageNo, QuerySearch.PageSize);
return entities.Adapt>();
}
#endregion
///
/// 获取重新解析邮件详情
///
/// 邮件接收记录主键
/// 返回回执
[HttpPost("/EmaiReceiveRecord/GetReParseInfo")]
public async Task GetReParseInfo(string gid)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (string.IsNullOrWhiteSpace(gid))
{
throw Oops.Oh($"邮件接收记录主键不能为空", typeof(InvalidOperationException));
}
var model = await _emaiReceiveRecordeInfoRepository.AsQueryable().FirstAsync(a => a.GID == gid);
if (model == null)
throw Oops.Oh($"邮件接收记录获取失败,邮件接收记录不存在或已作废", typeof(InvalidOperationException));
//这里读取一下收件处理明细表
var detailList = _emaiReceiveRecordDetailInfoRepository.AsQueryable()
.Where(a => a.P_GID == model.GID).ToList();
var showModel = model.Adapt();
if (detailList != null && detailList.Count > 0)
{
showModel.detailList = detailList.OrderByDescending(a => a.CreatedTime)
.Select(a => new EmaiReceiveRecordDetailDto
{
GID = a.GID,
FileName = a.FILE_NAME,
Status = a.STATUS,
OperType = a.OPER_TYPE,
ResponseNote = a.RESPONSE_NOTE,
CreatedTime = a.CreatedTime,
UpdatedTime = a.UpdatedTime
})
.ToList();
}
result.succ = true;
result.msg = "成功";
result.ext = showModel;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"获取重新解析邮件详情异常,原因:{ex.Message}";
}
return result;
}
#region 获取邮件接收记录的邮件详情
///
/// 获取邮件接收记录的邮件详情
///
/// 邮件接收记录主键
/// 返回回执
[HttpPost("/EmaiReceiveRecord/GetEmailInfo")]
public async Task GetEmailInfo(string gid)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
if (string.IsNullOrWhiteSpace(gid))
{
throw Oops.Oh($"邮件接收记录主键不能为空", typeof(InvalidOperationException));
}
var model = await _emaiReceiveRecordeInfoRepository.AsQueryable().FirstAsync(a => a.GID == gid);
if (model == null)
throw Oops.Oh($"邮件接收记录获取失败,邮件接收记录不存在或已作废", typeof(InvalidOperationException));
if(string.IsNullOrWhiteSpace(model.MAIL_FILEPATH))
throw Oops.Oh($"邮件文件提取失败,请联系管理员", typeof(InvalidOperationException));
//读取邮件,解析邮件正文
MimeMessage mimeMsg = MimeMessage.Load(model.MAIL_FILEPATH);
var strBody = mimeMsg.HtmlBody;
result.succ = true;
result.msg = "成功";
result.ext = strBody;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"获取邮件接收记录的邮件详情异常,原因:{ex.Message}";
}
return result;
}
#endregion
///
/// 重新解析邮件
///
/// 邮件接收记录详情
/// 返回回执
[HttpPost("/EmaiReceiveRecord/ReParseEmail")]
public async Task ReParseEmail(EmaiReceiveRecordDto model)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
result.succ = true;
result.msg = "成功";
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"获取重新解析邮件详情异常,原因:{ex.Message}";
}
return result;
}
}
}