You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

122 lines
3.5 KiB

using Entity.Ammeter;
using Entity.Dto.Req;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Entity;
using Repository.Ammeter;
using SqlSugar;
namespace Service.Ammeter
{
/// <summary>
///
/// </summary>
[Scope("SingleInstance")]
public class EmeterDayEnergyService : BaseServices<EmeterDayEnergy>
{
public EmeterDayEnergyService(EmeterDayEnergyRepository service)
{
this.BaseDal = service;
}
public async Task<PageResult<EmeterDayEnergy>> Page(PageAmmeterReq queryPageModel)
{
QueryPageModel queryPageModel1 = new QueryPageModel
{
PageNum = queryPageModel.PageNum,
PageSize = queryPageModel.PageSize,
};
if (!string.IsNullOrEmpty(queryPageModel.Code))
return PageResult<EmeterDayEnergy>.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, u => u.Code == queryPageModel.Code));
else
return PageResult<EmeterDayEnergy>.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, null));
}
/// <summary>
/// 获取七天用电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterDayEnergy>> SevenDaysElectrical(int type)
{
// 根据code分组,取最近7天数据,每天最大值-最小值=当日用电量,如果当天目前只有一条数据,取当天最大值-前一天最大值=当天耗电量
string sql = $@"
WITH daily_max_min AS (
SELECT
`code`,
DATE(`time`) AS `UploadTime`,
MAX(`real_time_value`) AS `MaxValue`,
MIN(`real_time_value`) AS `MinValue`,
COUNT(*) AS `Count`
FROM
`emeter_day_energy`
WHERE
`time` >= NOW() - INTERVAL 8 DAY
AND `type` = {type}
GROUP BY
`code`, DATE(`time`)
), previous_day_max AS (
SELECT
`code`,
`UploadTime`,
`MaxValue`,
`MinValue`,
`Count`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `UploadTime`) AS `PreviousMaxValue`
FROM
daily_max_min
), daily_consumption AS (
SELECT
d.`code`,
d.`UploadTime`,
CASE
WHEN d.`Count` > 1 THEN d.`MaxValue` - d.`MinValue`
WHEN d.`Count` = 1 AND d.`PreviousMaxValue` IS NOT NULL THEN d.`MaxValue` - d.`PreviousMaxValue`
ELSE 0
END AS `DailyValue`
FROM
previous_day_max d
WHERE
d.`UploadTime` >= NOW() - INTERVAL 7 DAY
)
SELECT
`UploadTime`,
SUM(`DailyValue`) AS `Value`
FROM
daily_consumption
GROUP BY
`UploadTime`
ORDER BY
`UploadTime`;
";
List<EmeterDayEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
/// <summary>
/// 获取全部用电量
/// </summary>
/// <returns></returns>
public async Task<List<EmeterDayEnergy>> GetAllElectricalData(int type)
{
string sql = $@"
SELECT
code,
MAX(real_time_value) - MIN(real_time_value) AS Value
FROM
emeter_day_energy
WHERE
time >= DATE_FORMAT(NOW(), '%Y-%m-01')
AND type = {type}
GROUP BY
code
ORDER BY
code;
";
List<EmeterDayEnergy> emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
}
}