using ApiTools.Core;
using Baidu.Aip.BodyAnalysis;
using Furion;
using Furion.DatabaseAccessor;
using Furion.HttpRemote;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiTools.CommonServer.Application
{
///
/// 诚立业短信平台回传通知
///
public class SmsChengLiYeNotifyCommandHandler(
IHttpContextAccessor httpContextAccessor,
IRepository repSmsSetting,
IRepository repSmsLog,
ApiTools.Core.SmsUtils smsUtils,
IHttpRemoteService httpRemoteService
) :
IRequestHandler
{
private readonly IHttpContextAccessor httpContextAccessor = httpContextAccessor;
private readonly IRepository repSmsSetting = repSmsSetting;
private readonly IRepository repSmsLog = repSmsLog;
private readonly ApiTools.Core.SmsUtils smsUtils = smsUtils;
private readonly IHttpRemoteService httpRemoteService = httpRemoteService;
///
/// 诚立业短信平台回传通知
///
///
///
///
public async Task Handle(SmsChengLiYeNotifyCommand request, CancellationToken cancellationToken)
{
if (App.GetConfig("Environment") == "Product")
{
try
{
await httpRemoteService.PostAsStringAsync("http://118.178.252.28:8780/api/common/sms/smsChengLiYeNotify",
builder => builder.SetJsonContent(request));
}
catch
{
}
}
if (request.MsgReports.IsNotNull())
{
var templateCodes = await EnumUtils.GetModel();
var msgIds = request.MsgReports.DistinctSelect(it => it.Msgid.ToString());
var entities = await repSmsLog.AsQueryable()
.Where(it =>
it.Access == EnumSmsAccess.ChengLiYe
&& msgIds.Contains(it.RequestId)
&& it.Status == EnumSmsStatus.InProcess)
.ToListAsync();
var channelIds = entities.DistinctSelect(it => it.ChannelId.HasValue, it => it.ChannelId.Value);
var settings = await repSmsSetting.AsQueryable().AsNoTracking()
.Include(it => it.Accesses)
.Where(it => it.ChannelId.HasValue && channelIds.Contains(it.ChannelId.Value))
.ToListAsync();
foreach (var entity in entities)
{
var report = request.MsgReports.FirstOrDefault(it => it.Msgid.ToString() == entity.RequestId);
if (report != null)
{
entity.Status = report.Status == "DELIVRD"
? EnumSmsStatus.Success
: EnumSmsStatus.Fail;
entity.Code = report.Status;
entity.Message = report.StatusDes;
await repSmsLog.UpdateNowAsync(entity);
if (entity.Status == EnumSmsStatus.Fail)
{
var templateCode = templateCodes.Items.FirstOrDefault(it => it.Name == entity.TemplateCode)?.Enum;
if (templateCode.HasValue)
{
var templateParam = entity.TemplateParam.IsNotNull()
? JObject.Parse(entity.TemplateParam)
: null;
var setting = settings.FirstOrDefault(it => it.ChannelId == entity.ChannelId);
await smsUtils.Send(setting, entity, new SendSmsModel
{
PhoneNumber = entity.PhoneNumber,
TemplateCode = templateCode.Value,
Expiry = entity.Expiry,
}, templateParam, cancellationToken);
}
}
}
}
}
return true;
}
}
}