using DotNetCore.CAP;
using Furion;
using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.RemoteRequest.Extensions;
using Furion.TaskScheduler;
using Mapster;
using Nirvana.Common;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Waste.Application.SubscribeInfo;
using Waste.Domain;
namespace Waste.Application
{
///
/// 投放记录管理
///
public class ResultService : BaseInfoService, IResultService, ITransient
{
private readonly ISqlSugarRepository repository;
private readonly SqlSugarClient dbClient;
private readonly ILoggerService _loggerService;
private readonly ICapPublisher _capBus;
public ResultService(ISqlSugarRepository sqlSugarRepository, ILoggerService loggerService, ICapPublisher capPublisher)
{
repository = sqlSugarRepository;
dbClient = repository.Context;
_loggerService = loggerService;
_capBus = capPublisher;
}
///
/// 获取投放记录
///
///
///
public async Task> GetListAsync(QueryParams param)
{
RefAsync totalnum = 0;
var temquery = dbClient.Queryable();
if (param.queryParam != null && param.queryParam.Count > 0)
{
List conModels = new List();
param.queryParam.ForEach(x =>
{
var val = x.Value.ToStrEmpty();
if (!string.IsNullOrEmpty(val))
{
if (x.Name.ToStr().ToLower() == "facecode")
{
temquery = temquery.Where(t => SqlFunc.Subqueryable().Where(e => e.FacEcode.Contains(val) && t.DeviceId == e.Id).Any());
}
else if (x.Name.ToStr().ToLower() == "name")
{
temquery = temquery.Where(t => SqlFunc.Subqueryable().Where(e => e.Name.Contains(val) && t.DeviceId == e.Id).Any());
}
else
{
conModels.Add(new ConditionalModel()
{
FieldName = x.Name,
ConditionalType = (ConditionalType)x.Type,
FieldValue = val
});
}
}
});
if (conModels.Count > 0)
{
temquery = temquery.Where(conModels);
}
}
//针对非平台类型,则可以查看下面所有的子账户设备
if (currentUser.AccountType != (int)AccountType.platform)
{
var sql = $"code like '{currentUser.BusinessCode}'+'%' and id = x.businessid";
temquery = temquery.Where(x => SqlFunc.Subqueryable().Where(sql).Any());
}
string sorts = string.Format("{0} {1}", param.sort, param.order);
var query = await temquery.OrderBy(sorts)
.Select(x => new ResultList
{
Id = x.Id,
BusinessId = x.BusinessId,
DeviceId = x.DeviceId,
WasteType = x.WasteType,
Tare = x.Tare,
GrossWeight = x.GrossWeight,
NetWeight = x.NetWeight,
Registration = x.Registration,
CreateTime = x.CreateTime,
PostStatus = -1
})
.Mapper((it, cache) =>
{
var allbus = cache.Get(list =>
{
var ids = list.Where(e => e.BusinessId != Guid.Empty).Select(e => e.BusinessId).ToList();
return dbClient.Queryable().Where(e => ids.Contains(e.Id)).ToList();
});
it.BusinessName = allbus.FirstOrDefault(e => e.Id == it.BusinessId)?.Name;
var alldev = cache.Get(list =>
{
var ids = list.Where(e => e.DeviceId != Guid.Empty).Select(e => e.DeviceId).ToList();
return dbClient.Queryable().Where(e => ids.Contains(e.Id)).ToList();
});
var dev = alldev.FirstOrDefault(e => e.Id == it.DeviceId);
if (dev != null)
{
it.DeviceName = dev.Name;
it.DeviceFacEcode = dev.FacEcode;
it.DeviceEcode = dev.Ecode;
it.DeviceAddress = dev.Address;
}
var allres = cache.Get(list =>
{
var ids = list.Select(e => e.Id).ToList();
return dbClient.Queryable().Where(e => ids.Contains(e.ResultId)).ToList();
});
var res = allres.FirstOrDefault(e => e.ResultId == it.Id);
if (res != null)
{
it.PostStatus = res.Status;
}
var allext = cache.Get(list =>
{
var ids = list.Select(e => e.Id).ToList();
return dbClient.Queryable().Where(e => ids.Contains(e.ResultId)).ToList();
});
var ext = allext.FirstOrDefault(e => e.ResultId == it.Id);
it.WasteType = ext != null && !ext.WasteSType.IsEmpty() ? $"{ext.WasteSType}【{it.WasteType}】" : it.WasteType;
})
.ToPageListAsync(param.offset, param.limit, totalnum);
return new PageParms
{
page = param.offset,
Items = query,
totalnum = totalnum,
limit = param.limit
};
}
///
/// wifi模块测量结果增加
///
///
///
public async Task InsertResultByWifiAsync(WifiPackage data)
{
//查找设备
var device = await dbClient.Queryable().FirstAsync(x => data.sn == x.Ecode);
// _loggerService.AddLogger($"接收到的数据,参数:{myPackage.ToJson()}", 3);
if (device == null)
{
//记录日志
_loggerService.AddLogger($"设备未找到,参数:{data.ToJson()}", 3);
return;
}
//计算净重,毛重-皮重=净重,如果净重小于等于0则不上报保存
decimal weight = (data.Weight.ToDecimal() - device.Tare).ToDecimal(2);
if (weight <= 0)
{
//记录日志
_loggerService.AddLogger($"净重为0不上报,参数:{data.ToJson()}", 3);
return;
}
var devicedata = await dbClient.Queryable().FirstAsync(x => x.DeviceId == device.Id);
var resultid = IDGen.NextID();
DateTime time = DateTime.Now;
//检查设备是否为今天第一次上报
bool isfrist = false;
if (device.LastHeartTime.HasValue && device.LastHeartTime.Value.Date != DateTime.Now.Date)
{
isfrist = true;
}
decimal currentweight = data.Weight.IsEmpty() ? 0 : data.Weight.ToDecimal();
//记录数据
await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("Proc_InsertResult", new
{
deviceid = device.Id,
businessid = device.Businessid,
resultid = resultid,
imei = devicedata != null ? devicedata.IMSI : "",
iccid = devicedata != null ? devicedata.ICCID : "",
imsi = devicedata != null ? devicedata.IMSI : "",
time = time,
latitude = "",
longitude = "",
sign = "",
city = "",
area = data.trashcode,
wastetype = data.WasteType,
weigth = currentweight,
isheart = data.IsHeart,
tare = device.Tare,
isfrist = isfrist
});
if (!data.IsHeart)
{
await SendMessageToThird(new SendThirdMessageSubscribeS2SDto
{
DeviceId = device.Id,
Time = time,
TrashCode = data.trashcode,
WasteType = data.WasteType,
Weight = currentweight
});
}
}
///
/// 新的4G模块测量结果增加
///
///
///
public async Task InsertResultBy4GAsync(nMyPackage myPackage)
{
//查找设备
var device = await dbClient.Queryable().FirstAsync(x => myPackage.IMEI == x.Ecode);
// _loggerService.AddLogger($"接收到的数据,参数:{myPackage.ToJson()}", 3);
if (device == null)
{
//记录日志
_loggerService.AddLogger($"设备未找到,参数:{myPackage.ToJson()}", 3);
return;
}
var devicedata = await dbClient.Queryable().FirstAsync(x => x.DeviceId == device.Id);
var resultid = IDGen.NextID();
DateTime time = DateTime.Now;
if (myPackage.IsHeart)
{
if (string.IsNullOrEmpty(myPackage.Longitude) || myPackage.Longitude.ToDecimal() == 0) myPackage.Longitude = devicedata != null ? devicedata.Longitude : "0";
if (string.IsNullOrEmpty(myPackage.Latitude) || myPackage.Latitude.ToDecimal() == 0) myPackage.Latitude = devicedata != null ? devicedata.Latitude : "0";
}
else
{
if (string.IsNullOrEmpty(myPackage.IMSI)) myPackage.IMSI = devicedata != null ? devicedata.IMSI : "";
if (string.IsNullOrEmpty(myPackage.IMEI)) myPackage.IMEI = devicedata != null ? devicedata.IMEI : "";
if (string.IsNullOrEmpty(myPackage.ICCID)) myPackage.ICCID = devicedata != null ? devicedata.ICCID : "";
if (!string.IsNullOrEmpty(myPackage.Time) && myPackage.Time.Length == 14)
{
time = $"{myPackage.Time.Substring(0, 4)}-{myPackage.Time.Substring(4, 2)}-{myPackage.Time.Substring(6, 2)} {myPackage.Time.Substring(8, 2)}:{myPackage.Time.Substring(10, 2)}:{myPackage.Time.Substring(12, 2)}".ToDate();
}
}
//检查设备是否为今天第一次上报
bool isfrist = false;
if (device.LastHeartTime.HasValue && device.LastHeartTime.Value.Date != DateTime.Now.Date)
{
isfrist = true;
}
var Weight = myPackage.Weight.IsEmpty() ? 0 : myPackage.Weight.ToDecimal();
//记录数据
await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("Proc_InsertResult", new
{
deviceid = device.Id,
businessid = device.Businessid,
resultid = resultid,
imei = myPackage.IMEI,
iccid = myPackage.ICCID,
imsi = myPackage.IMSI,
time = time,
latitude = myPackage.Latitude,
longitude = myPackage.Longitude,
sign = myPackage.GSLQ,
city = "",
area = myPackage.trashcode,
wastetype = myPackage.WasteType,
weigth = Weight,
isheart = myPackage.IsHeart,
tare = device.Tare,
isfrist = isfrist
});
if (!myPackage.IsHeart)
{
await SendMessageToThird(new SendThirdMessageSubscribeS2SDto
{
DeviceId = device.Id,
Time = time,
TrashCode = myPackage.trashcode,
WasteType = myPackage.WasteType,
Weight = Weight
});
}
}
///
/// 新的A8 4G模块测量结果增加
///
///
///
public async Task InsertResultByA84GAsync(A8MyPackage myPackage)
{
//如果uuid不为空,并且以存在记录,则忽略
//if (!myPackage.IsHeart && !myPackage.UUID.IsEmpty() && await dbClient.Queryable().AnyAsync(x => x.UUID == myPackage.UUID))
//{
// _loggerService.AddLogger($"A8记录重复,内容:{myPackage.ToJson()}", 1);
// return;
//}
//查找设备
var device = await dbClient.Queryable().FirstAsync(x => myPackage.IMEI == x.Ecode);
// _loggerService.AddLogger($"接收到的数据,参数:{myPackage.ToJson()}", 3);
if (device == null)
{
//记录日志
_loggerService.AddLogger($"设备未找到,参数:{myPackage.ToJson()}", 3);
return;
}
var devicedata = await dbClient.Queryable().FirstAsync(x => x.DeviceId == device.Id);
var resultid = IDGen.NextID();
DateTime time = DateTime.Now;
if (myPackage.IsHeart)
{
if (string.IsNullOrEmpty(myPackage.Longitude) || myPackage.Longitude.ToDecimal() == 0) myPackage.Longitude = devicedata != null ? devicedata.Longitude : "0";
if (string.IsNullOrEmpty(myPackage.Latitude) || myPackage.Latitude.ToDecimal() == 0) myPackage.Latitude = devicedata != null ? devicedata.Latitude : "0";
}
else
{
if (string.IsNullOrEmpty(myPackage.IMSI)) myPackage.IMSI = devicedata != null ? devicedata.IMSI : "";
if (string.IsNullOrEmpty(myPackage.IMEI)) myPackage.IMEI = devicedata != null ? devicedata.IMEI : "";
if (string.IsNullOrEmpty(myPackage.ICCID)) myPackage.ICCID = devicedata != null ? devicedata.ICCID : "";
if (!string.IsNullOrEmpty(myPackage.Time) && myPackage.Time.Length == 14)
{
time = $"{myPackage.Time.Substring(0, 4)}-{myPackage.Time.Substring(4, 2)}-{myPackage.Time.Substring(6, 2)} {myPackage.Time.Substring(8, 2)}:{myPackage.Time.Substring(10, 2)}:{myPackage.Time.Substring(12, 2)}".ToDate();
}
}
//检查设备是否为今天第一次上报
bool isfrist = false;
if (device.LastHeartTime.HasValue && device.LastHeartTime.Value.Date != DateTime.Now.Date)
{
isfrist = true;
}
var Weight = myPackage.Weight.IsEmpty() ? 0 : myPackage.Weight.ToDecimal();
decimal price = myPackage.Price.IsEmpty() ? 0 : myPackage.Price.ToDecimal();
decimal amount = myPackage.Amount.IsEmpty() ? 0 : myPackage.Amount.ToDecimal();
string wastestype = myPackage.WasteSType.ToStr();
//记录数据
await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("Proc_InsertResult", new
{
deviceid = device.Id,
businessid = device.Businessid,
resultid = resultid,
imei = myPackage.IMEI,
iccid = myPackage.ICCID,
imsi = myPackage.IMSI,
time = time,
latitude = myPackage.Latitude,
longitude = myPackage.Longitude,
sign = myPackage.GSLQ,
city = "",
area = myPackage.trashcode,
wastetype = myPackage.WasteType,
weigth = Weight,
isheart = myPackage.IsHeart,
tare = device.Tare,
isfrist = isfrist
});
if (!myPackage.IsHeart)
{
//记录价格数据
if (!myPackage.UUID.IsEmpty())
{
await dbClient.Insertable(new W_MeasureResult
{
ResultId = resultid,
WasteSType = wastestype,
Amount = amount,
OpUser = myPackage.OpUser.ToStr(),
Price = price,
UUID = myPackage.UUID
}).ExecuteCommandAsync();
}
await SendMessageToThird(new SendThirdMessageSubscribeS2SDto
{
DeviceId = device.Id,
Time = time,
TrashCode = myPackage.trashcode,
WasteType = myPackage.WasteType,
Weight = Weight,
WasteSType = wastestype
});
}
}
///
/// 给第三方推送消息
///
///
///
private async Task SendMessageToThird(SendThirdMessageSubscribeS2SDto input)
{
if (input.Weight <= 0)
{
return;
}
var configdata = await dbClient.Queryable().Where(x => x.DeviceId == input.DeviceId).Select(x => new W_DeviceConfig
{
Body = x.Body,
Url = x.Url
}).FirstAsync();
if (configdata != null && !configdata.Url.IsEmpty())
{
var senddata = input.Adapt();
senddata.Body = configdata.Body.ToStr();
senddata.Url = configdata.Url.ToStr();
await _capBus.PublishAsync("third.service.sendmessage", senddata);
}
}
///
/// 增加测量记录
///
///
///
public async Task InsertResultAsync(MyPackage myPackage)
{
//查找设备
var device = await dbClient.Queryable().FirstAsync(x => myPackage.IMEI == x.Ecode);
// _loggerService.AddLogger($"接收到的数据,参数:{myPackage.ToJson()}", 3);
if (device == null)
{
//记录日志
_loggerService.AddLogger($"设备未找到,参数:{myPackage.ToJson()}", 3);
return new ResultInfo(ResultState.FAIL, "设备未找到");
}
var devicedata = await dbClient.Queryable().FirstAsync(x => x.DeviceId == device.Id);
var resultid = IDGen.NextID();
DateTime time = DateTime.Now;
if (myPackage.IsHeart)
{
if (string.IsNullOrEmpty(myPackage.Longitude) || myPackage.Longitude.ToDecimal() == 0) myPackage.Longitude = devicedata != null ? devicedata.Longitude : "0";
if (string.IsNullOrEmpty(myPackage.Latitude) || myPackage.Latitude.ToDecimal() == 0) myPackage.Latitude = devicedata != null ? devicedata.Latitude : "0";
}
else
{
if (string.IsNullOrEmpty(myPackage.IMSI)) myPackage.IMSI = devicedata != null ? devicedata.IMSI : "";
if (string.IsNullOrEmpty(myPackage.IMEI)) myPackage.IMEI = devicedata != null ? devicedata.IMEI : "";
if (string.IsNullOrEmpty(myPackage.ICCID)) myPackage.ICCID = devicedata != null ? devicedata.ICCID : "";
if (!string.IsNullOrEmpty(myPackage.Time) && myPackage.Time.Length == 14)
{
time = $"{myPackage.Time.Substring(0, 4)}-{myPackage.Time.Substring(4, 2)}-{myPackage.Time.Substring(6, 2)} {myPackage.Time.Substring(8, 2)}:{myPackage.Time.Substring(10, 2)}:{myPackage.Time.Substring(12, 2)}".ToDate();
}
}
//检查设备是否为今天第一次上报
bool isfrist = false;
if (device.LastHeartTime.HasValue && device.LastHeartTime.Value.Date != DateTime.Now.Date)
{
isfrist = true;
}
if (myPackage.IsChecked && !string.IsNullOrEmpty(myPackage.Area) && myPackage.Area.Length > 0)
{
//新的协议中此字段为垃圾桶编号
var areaBytes = Encoding.Default.GetBytes(myPackage.Area);
//长度为5个字节,后三位为垃圾桶编号(16进制)
if (areaBytes.Length == 5)
{
var typeBytes = new byte[3];
for (var i = 0; i < 3; i++)
{
typeBytes[i] = areaBytes[i + 2];
}
var typeHex = Convert.ToHexString(typeBytes);
myPackage.Area = Convert.ToInt32(typeHex, 16).ToString();
}
//000F000002.16进制
// var areaHex = Convert.ToHexString(areaBytes);
}
decimal weight = myPackage.Weight.IsEmpty() ? 0 : myPackage.Weight.ToDecimal();
//记录数据
await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("Proc_InsertResult", new
{
deviceid = device.Id,
businessid = device.Businessid,
resultid = resultid,
imei = myPackage.IMEI,
iccid = myPackage.ICCID,
imsi = myPackage.IMSI,
time = time,
latitude = myPackage.Latitude,
longitude = myPackage.Longitude,
sign = myPackage.GSLQ,
city = myPackage.City,
area = myPackage.Area,
wastetype = myPackage.WasteType,
weigth = weight,
isheart = myPackage.IsHeart,
tare = device.Tare,
isfrist = isfrist
});
//上传垃圾数据
//if (myPackage.IsWeight && myPackage.Weight.ToDecimal() > 0)
//{
// var devicesecret = await repository.Change().Context.Queryable().FirstAsync(x => x.DeviceId == device.Id);
// if (devicesecret != null && !string.IsNullOrEmpty(devicesecret.Secret)
// && !string.IsNullOrEmpty(devicesecret.SecretHash)
// && !string.IsNullOrEmpty(devicesecret.DevId))
// {
// int timestamp = GetTimestamp(time);
// await _suZhouService.PostGarbagesAsync(new GarbagePltC2SDto
// {
// Weight = myPackage.Weight.ToDouble(),
// secret = devicesecret.Secret,
// secrethash = devicesecret.SecretHash,
// ScanningTime = timestamp,
// DStatus = 0,
// deviceid = devicesecret.DevId,
// Trash = myPackage.Area,
// Type = TrashType(myPackage.WasteType)
// });
// }
//}
if (!myPackage.IsHeart)
{
await SendMessageToThird(new SendThirdMessageSubscribeS2SDto
{
DeviceId = device.Id,
Time = time,
TrashCode = myPackage.Area,
WasteType = myPackage.WasteType,
Weight = weight
});
}
return new ResultInfo(ResultState.SUCCESS, "success");
}
///
/// byte转int
///
///
///
private static int ByteToInt(byte bt)
{
return Convert.ToInt32(((int)bt).ToString("X2"), 16);
}
private static int GetTimestamp(DateTime time)
{
DateTime dateTimeStart = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));
int timestamp = Convert.ToInt32((time - dateTimeStart).TotalSeconds);
return timestamp;
}
private int TrashType(string type)
{
if (type == "厨余垃圾") return 1;
else if (type == "可回收物") return 2;
else if (type == "有害垃圾") return 3;
else if (type == "其他垃圾") return 4;
else return 0;
}
}
}