using AutoMapper;
using LinqKit;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Ropin.Inspection.Common;
using Ropin.Inspection.Common.Accessor.Interface;
using Ropin.Inspection.Common.Helper;
using Ropin.Inspection.Model;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Model.ViewModel;
using Ropin.Inspection.Repository;
using Ropin.Inspection.Repository.SYS.Interface;
using Ropin.Inspection.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
namespace Ropin.Inspection.Service
{
public class PushMsgService : IPushMsgService
{
private readonly IClaimsAccessor _claims;
private readonly IMapper _mapper;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ITsysUserRepository _tsysUserRepository;
private readonly ITmtnPushMsgToRepository _tmtnPushMsgToRepository;
private readonly ITmtnPushMsgResultRepository _tmtnPushMsgResultRepository;
private readonly ITbdmCodeDetailRepository _tbdmCodeDetailRepository;
private readonly ITdevDevStoreRepository _tdevDevStoreRepository;
private readonly ITsysUserService _tsysUserService;
private readonly ITsysMessageRepository _messageRepository;
private readonly ITsysMessageFileRepository _tsysMessageFileRepository;
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(PushMsgService));
private string IsSendEmail = "true";
public PushMsgService(IClaimsAccessor claims,
ITmtnPushMsgToRepository tmtnPushMsgToRepository,
ITbdmCodeDetailRepository tbdmCodeDetailRepository,
ITmtnPushMsgResultRepository tmtnPushMsgResultRepository,
ITdevDevStoreRepository tdevDevStoreRepository,
IMapper mapper,
ITsysUserService tsysUserService,
IHttpClientFactory httpClientFactory,
ITsysUserRepository tsysUserRepository
, IConfiguration configuration, ITsysMessageRepository messageRepository, ITsysMessageFileRepository tsysMessageFileRepository)
{
_mapper = mapper;
_claims = claims;
_httpClientFactory = httpClientFactory;
_tsysUserRepository = tsysUserRepository;
_tmtnPushMsgToRepository = tmtnPushMsgToRepository;
_tbdmCodeDetailRepository = tbdmCodeDetailRepository;
_tmtnPushMsgResultRepository = tmtnPushMsgResultRepository;
_tdevDevStoreRepository = tdevDevStoreRepository;
_tsysUserService = tsysUserService;
_messageRepository = messageRepository;
_tsysMessageFileRepository= tsysMessageFileRepository;
string IsEmail = configuration.GetSection("IsSendEmail")?.Value;
IsSendEmail = !string.IsNullOrEmpty(IsEmail)? IsEmail :"true";
}
///
///
///
///
///
///
/// 跳转小程序URLID
/// 状态
///
public async Task PushAlarmMsgAsync(TpushMsgModel pushModel,string Subject=null,RabbitMQModel rabbitMQModel=null, string UrlId = null,string status=null)
{
try
{
List messageFiles = pushModel.FileList;
pushModel.FileList = null;
log.Info($"发送消息-Begin");
log.Info($"发送消息-接收数据【{JsonConvert.SerializeObject(pushModel)}】");
int msgStatus = DataDictionaryHelper.GetMsgStatus(pushModel.C_MsgTypeCode);
pushModel.msgStatus = msgStatus;
string createBy = "6e864cbc-5252-11ec-8681-fa163e02b3e4";
var devStore = await _tdevDevStoreRepository.GetByIdAsync(pushModel.C_DevStoreCode);
if(devStore == null) return await Task.FromResult(false);
pushModel.DevName = devStore.C_Name;
pushModel.DevNumber = devStore.C_NumberCode;
var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选
if (!string.IsNullOrEmpty(pushModel.C_DevStoreCode))
{
predicate = predicate.And(i => i.C_DevStoreCode.Equals(pushModel.C_DevStoreCode));
}
if (!string.IsNullOrEmpty(pushModel.C_MsgTypeCode))
{
predicate = predicate.And(i => i.C_MsgTypeCode.Equals(pushModel.C_MsgTypeCode));
}
IEnumerable pushMsgTo = await _tmtnPushMsgToRepository.GetByConditionAsync(predicate);
IList pushMsgTolist = pushMsgTo.ToList();
//IEnumerable users = await _tsysUserRepository.GetByConditionAsync(x=>x.C_Status == "1");
IList userList = _tsysUserRepository.GetUserList();//users.ToList();
IEnumerable tBDMCodeDetail = await _tbdmCodeDetailRepository.GetAllAsync();
IList tBDMCodeDetailList = tBDMCodeDetail.ToList();
List sendUserWechatIDList = new List();
List pushMsgResultList = new List();
log.Info($"发送消息-pushMsgTolist【{JsonConvert.SerializeObject(pushMsgTolist)}】");
foreach (var pushMsgToItem in pushMsgTolist)
{
var user = userList.Where(x => x.C_UserID.ToString() == pushMsgToItem.C_PushPersonCode)?.FirstOrDefault();
if (user is null)
continue;
if (string.IsNullOrWhiteSpace(pushModel.UserName))
{
var creadUser = await _tsysUserService.GetByIdAsync(_claims.ApiUserId);
createBy = _claims.ApiUserId.ToString();
pushModel.UserName = creadUser?.C_Name;
pushModel.UserMobile = creadUser?.C_Mobile;
}
if (pushMsgToItem.C_PushTypeCode == "PUSH_TYPE_001")//Email
{
if (!string.IsNullOrEmpty(user.C_Email))
{
if (!string.IsNullOrEmpty(user.C_Email))
{
switch (pushModel.C_MsgTypeCode)
{
case "MSG_TYPE_001"://通知维修消息
break;
case "MSG_TYPE_002"://通知运维消息
break;
case "MSG_TYPE_003"://通知巡检消息
break;
case "MSG_TYPE_004"://巡检异常消息
break;
case "MSG_TYPE_005"://异常消除消息
break;
case "MSG_TYPE_006"://维修确认消息
break;
case "MSG_TYPE_007"://维修取消消息
break;
case "MSG_TYPE_008"://维修完成消息
break;
case "MSG_TYPE_009"://运维取消消息
break;
case "MSG_TYPE_010"://异常确认消息
break;
case "MSG_TYPE_011"://设备启停消息
break;
case "MSG_TYPE_012"://设备点报警
break;
case "MSG_TYPE_013"://设备点报警取消
break;
case "MSG_TYPE_014"://正在维修消息
break;
case "MSG_TYPE_015"://维修返工消息
break;
case "MSG_TYPE_016"://维修完成确认
break;
default:
break;
}
string msg =
"设备编号: | " + pushModel.DevNumber + "
" +
"设备名称: | " + pushModel.DevName + "" +
"消息内容: | " + pushModel.Msg + "" +
"设备地址: | " + pushModel.DevAddress + "" +
" 报警时间: | " + pushModel.CreateOn + "" +
" 上报人: | " + pushModel.UserName + ""
//+" 上报人手机号: | " + pushModel.UserMobile + ""
;
if (IsSendEmail== "true")
{
var bols= EmailHelper.SendEmail(user.C_Email, tBDMCodeDetailList.Where(i => i.C_Code == pushMsgToItem.C_MsgTypeCode).Select(x => x.C_Name).FirstOrDefault(), pushModel.Subject, msg);
if (!bols)
{
log.Info($"发送邮件失败【C_Email={user.C_Email},C_MsgTypeCode={pushMsgToItem.C_MsgTypeCode} ,C_DevStoreCode={pushModel.C_DevStoreCode}】");
}
}
}
}
pushMsgResultList.Add(new TMTN_PushMsgResult
{
C_ID = Guid.NewGuid().ToString(),
C_PushMsgToCode = pushMsgToItem.C_PushPersonCode,
//C_Content = "消息主题:" + pushModel.Subject + " 设备编号:" + pushModel.DevNumber + " 设备名称:" + pushModel.DevName + " 设备地址:" + pushModel.DevAddress + " 消息内容:" + pushModel.Msg,
C_Content = JsonConvert.SerializeObject(pushModel),
C_PushTypeCode = pushMsgToItem.C_PushTypeCode,
C_DevStoreCode = pushMsgToItem.C_DevStoreCode,
C_MsgTypeCode = pushModel.C_MsgTypeCode,
C_Subject = Subject,
C_CreateBy = new Guid(createBy),
D_CreateOn = DateTime.Now,
C_Status = "1"
}) ;
}
if (pushMsgToItem.C_PushTypeCode == "PUSH_TYPE_002")//wx
{
//if (!string.IsNullOrEmpty(user.C_WechatID)&& IsSendEmail == "true")
//{
// if (!sendUserWechatIDList.Contains(user.C_WechatID))
// sendUserWechatIDList.Add(user.C_WechatID);
//}
log.Info($"发送消息-获取微信C_WxopenID【{user.C_WxopenID}】用户名字【{user.C_Name}】IsSendEmail【{IsSendEmail}】");
if (!string.IsNullOrEmpty(user.C_WxopenID) && IsSendEmail == "true")
{
if (!sendUserWechatIDList.Contains(user.C_WxopenID))
sendUserWechatIDList.Add(user.C_WxopenID);
}
pushMsgResultList.Add(new TMTN_PushMsgResult
{
C_ID = Guid.NewGuid().ToString(),
C_PushMsgToCode = pushMsgToItem.C_PushPersonCode,
//C_Content = "消息主题:" + pushModel.Subject + " 设备编号:" + pushModel.DevNumber + " 设备名称:" + pushModel.DevName + " 设备地址:" + pushModel.DevAddress + " 消息内容:" + pushModel.Msg,
C_Content = JsonConvert.SerializeObject(pushModel),
C_PushTypeCode = pushMsgToItem.C_PushTypeCode,
C_DevStoreCode = pushMsgToItem.C_DevStoreCode,
C_MsgTypeCode = pushModel.C_MsgTypeCode,
C_Subject = Subject,
C_CreateBy = new Guid(createBy),
D_CreateOn = DateTime.Now,
C_Status = "1"
});
}
}
log.Info($"发送消息-sendUserWechatIDList【{JsonConvert.SerializeObject(sendUserWechatIDList)}】pushMsgResultList=【{JsonConvert.SerializeObject(pushMsgResultList)}】");
string GenerationCode = "";
switch (pushModel.GenerationType)
{
case 1: GenerationCode = pushModel.C_DevStoreCode; break;
case 2: GenerationCode = _claims.ApiUserId.ToString(); break;
case 3: GenerationCode = "6e864cbc-5252-11ec-8681-fa163e02b3e4"; break;
}
TSYS_Message message = new TSYS_Message
{
C_ID = Guid.NewGuid().ToString(),
C_LicenseCode = "SYSTEM",
C_Content = JsonConvert.SerializeObject(pushModel),
C_MsgTypeCode = pushModel.C_MsgTypeCode,
C_Subject = Subject,
D_MsgCreateOn = Convert.ToDateTime(pushModel.CreateOn),
C_GenerationCode = GenerationCode,
I_GenerationType = pushModel.GenerationType,
I_MsgStatus = pushModel.msgStatus,
C_DevStoreCode = pushModel.C_DevStoreCode,
C_Remark = "",
C_CreateBy = createBy,
C_Creator = "Api",
D_CreateOn = DateTime.Now,
C_Status = "1"
};
List FileList = null;
if (messageFiles != null)
{
FileList=new List();
foreach (var item in messageFiles)
{
TSYS_MessageFile mesFile = new TSYS_MessageFile
{
C_ID = Guid.NewGuid().ToString(),
C_MessageCode= message.C_ID,
C_Url=item.Url,
C_Text = item.Text,
C_Type = item.Type,
C_CreateBy = createBy,
D_CreateOn = DateTime.Now,
C_Status = "1"
};
FileList.Add(mesFile);
}
}
_messageRepository.Create(message);
bool messResult = await _messageRepository.SaveAsync();
if (messResult)
{
if (FileList != null && FileList.Count > 0)
{
int fileSaveResult = await _tsysMessageFileRepository.CreateRangeAsync(FileList);
}
string miniProgramAppId = "";//跳转小程序的Appid
//获取小程序页面
string miniProgramPagePath = DataDictionaryHelper.GetXCXPage(pushModel.C_MsgTypeCode, message.C_ID, UrlId, pushModel.C_DevStoreCode, status);
if (!string.IsNullOrEmpty(miniProgramPagePath))
{
miniProgramAppId = WXConstModel.XCXAppId;
}
if (sendUserWechatIDList.Any())
{
try
{
string typeName = tBDMCodeDetailList.Where(i => i.C_Code == pushModel.C_MsgTypeCode).Select(x => x.C_Name).FirstOrDefault();
#region 长期订阅 【2025-2-11】
//var content = new
//{
// character_string1 = new { value = devStore.C_NumberCode ?? "" },
// time2 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
// short_thing3 = new { value = typeName ?? "" }
//};
//new WeChatHelper(_httpClientFactory).PushMessageToUser(sendUserWechatIDList, content, WXConstModel.WatchHealthAlarm_TemplateId);
#endregion
#region 公众号模板【2025-3-5】
string msg = pushModel.Msg;
if (string.IsNullOrEmpty(msg))
{
msg = DataDictionaryHelper.GetValNameByCode(pushModel.C_MsgTypeCode);
}
if (msg.Length > 20)
{
msg = msg.Substring(0, 17) + "...";
}
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
if (!string.IsNullOrEmpty(pushModel.CreateOn))
{
time = Convert.ToDateTime(pushModel.CreateOn).ToString("yyyy-MM-dd HH:mm");
}
#region //_wP22WQxAlfYGfS8zlnHTl_-KgKS8j_FP5HDeqfsPtU
//设备编号{ { character_string2.DATA} }
//设备名称{ { thing1.DATA} }
//关闭状态{ { thing3.DATA} }
//关闭时间{ { time4.DATA} }
//var data = new
//{
// thing1 = new { value = devStore.C_Name }, //异常位置
// character_string2 = new { value = devStore.C_NumberCode },//异常点位
// thing3 = new { value = typeName }, //上报人
// time4 = new { value = pushModel.CreateOn}//上报时间
//};
#endregion
#region 7eGjzIBAyysTOLfcn-oqkpOCEL_My5ItXHkd_DdniGw
//设备名称{ { thing2.DATA} }
//设备编号{ { character_string20.DATA} }
//报警时间{ { time4.DATA} }
//报警内容{ { thing5.DATA} }
var data = new
{
thing2 = new { value = devStore.C_Name }, //设备名称
character_string20 = new { value = devStore.C_NumberCode },//设备编号
thing5 = new { value = msg }, //报警内容
time4 = new { value = time }//报警时间
};
#endregion
var row = new WeChatHelper(_httpClientFactory).PushGZHMessageToUser(sendUserWechatIDList, WXConstModel.GZHDevAlarmTemplateId, "", data, miniProgramAppId, miniProgramPagePath);
#endregion
}
catch (Exception ex)
{
log.Info($" 发送消息-WeChatHelper-发送异常【C_MsgTypeCode={pushModel.C_MsgTypeCode}】 异常信息:{ex.Message}");
throw;
}
}
if (pushMsgResultList.Any())
{
//await _tmtnPushMsgResultRepository.CreateRangeAsync(pushMsgResultList);
foreach (var content in pushMsgResultList)
{
try
{
content.C_MessageCode = message.C_ID;
_tmtnPushMsgResultRepository.Create(content);
bool bols = await _tmtnPushMsgResultRepository.SaveAsync();
}
catch (Exception ex)
{
log.Info($" 发送消息-pushMsgResultList-TMTN_PushMsgResult-保存异常【数据:{JsonConvert.SerializeObject(content)}】 异常信息:{ex.Message}");
Console.WriteLine(ex.Message);
}
}
//
if (pushModel.C_MsgTypeCode == "MSG_TYPE_012" && rabbitMQModel != null)
{
rabbitMQModel.msgStr = JsonConvert.SerializeObject(message);
bool bol = await RabbitMQHelper.SnedRabbitMQ_ExchangeDirect(rabbitMQModel);
if (!bol)
{
log.Info($" 发送消息-[MSG_TYPE_012]发送RabbitMQ消息失败【TMTN_PushMsgResult:{rabbitMQModel.msgStr}】");
}
}
}
}
else {
log.Info($"发送消息-TSYS_Message 数据添加失败【{JsonConvert.SerializeObject(message)}】");
}
log.Info($"发送消息-END");
return await Task.FromResult(true);
}
catch (Exception ex)
{
log.Info($"发送消息-Error【{ex.Message}】");
return await Task.FromResult(false);
}
}
public async Task PushRecordMsgAsync(string type,TispRecordItemAlarmDetailViewModel viewModel)
{
try
{
IEnumerable users = await _tsysUserRepository.GetByRecordItemCodeAsync(viewModel.C_ID.ToString());
if (!users.Any())
{
return;
}
//List openIds = users.Where(u => u.C_WechatID != null).Select(i => i.C_WechatID).ToList();
//var content = new
//{
// thing2 = new { value = itemDetail.ReportUserName ?? "" },
// time4 = new { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm") },
// thing5 = new { value = "巡检异常取消" ?? "" },
// thing6 = new { value = itemDetail.C_Name ?? "" },
// thing9 = new { value = itemDetail.SpotName ?? "" }
//};
//new WeChatHelper(_httpClientFactory).PushMessageToUser(openIds, content);
List openIds = users.Where(u => u.C_WxopenID != null).Select(i => i.C_WxopenID).ToList();
//var data = new
//{
// thing4 = new { value = viewModel.SpotName }, //异常位置
// thing6 = new { value = viewModel.C_Name },//异常点位
// thing2 = new { value = viewModel.ReportUserName }, //上报人
// time3 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm") }//上报时间
//};
string statusStr = "未知";
//1 = 正常; 0 = 异常; 2 = 恢复; 3 = 确认异常; 4 = 取消异常
switch (viewModel.SecurityStatus)
{
case "0": statusStr = "异常"; break;
case "1": statusStr = "正常"; break;
case "2": statusStr = "恢复"; break;
case "3": statusStr = "确认异常"; break;
case "4": statusStr = "取消异常"; break;
}
var data = new
{
thing1 = new { value = viewModel.SpotName }, //异常位置
character_string2 = new { value = viewModel.SpotNumber },//异常点位
thing3 = new { value = statusStr }, //上报人
time4 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm") }//上报时间
};
var row = new WeChatHelper(_httpClientFactory).PushGZHMessageToUser(openIds, null, "", data, "", "");
}
catch (Exception ex)
{
throw;
}
}
}
}