using Entity.Ammeter;
using Entity.Dto.Req;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Entity;
using Repository.Ammeter;
namespace Service.Ammeter
{
///
///
///
[Scope("SingleInstance")]
public class EmeterMinutesEnergyService : BaseServices
{
EmeterMinutesEnergyRepository _emeterMinutesEnergyRepository1;
public EmeterMinutesEnergyService(EmeterMinutesEnergyRepository emeterMinutesEnergyRepository)
{
this.BaseDal = emeterMinutesEnergyRepository;
_emeterMinutesEnergyRepository1 = emeterMinutesEnergyRepository;
}
public async Task> Page(PageAmmeterReq queryPageModel)
{
QueryPageModel queryPageModel1 = new QueryPageModel
{
PageNum = queryPageModel.PageNum,
PageSize = queryPageModel.PageSize,
};
if (!string.IsNullOrEmpty(queryPageModel.Code))
return PageResult.ConvertPage(_emeterMinutesEnergyRepository1.QueryIPageByCause(queryPageModel1, u => u.Code == queryPageModel.Code));
else
return PageResult.ConvertPage(_emeterMinutesEnergyRepository1.QueryIPageByCause(queryPageModel1, null));
}
///
/// 根据分钟统计电量
///
///
public async Task> GetTodayMinutelyElectricalData(int type)
{
string sql = $@"
WITH minute_max_min AS (
SELECT
`code`,
DATE_FORMAT(`time`, '%Y-%m-%d %H:%i:00') AS `Minute`,
MAX(`real_time_value`) AS `MaxValue`,
MIN(`real_time_value`) AS `MinValue`,
COUNT(*) AS `record_count`
FROM
`emeter_minutes_energy`
WHERE
`time` >= NOW() - INTERVAL 1 HOUR
AND `type` = {type}
GROUP BY
`code`, DATE_FORMAT(`time`, '%Y-%m-%d %H:%i:00')
), previous_minute_max AS (
SELECT
`code`,
`Minute`,
LAG(`MaxValue`) OVER (PARTITION BY `code` ORDER BY `Minute`) AS `PreviousMaxValue`
FROM
minute_max_min
)
SELECT
m.`code`,
m.`Minute`,
CASE
WHEN m.`record_count` > 1 THEN m.`MaxValue` - m.`MinValue`
WHEN p.`PreviousMaxValue` IS NULL THEN 0
ELSE m.`MaxValue` - p.`PreviousMaxValue`
END AS `Value`
FROM
minute_max_min m
LEFT JOIN
previous_minute_max p ON m.`code` = p.`code` AND m.`Minute` = p.`Minute`
ORDER BY
m.`code`, m.`Minute`;
";
List emeterEnergies = await this.BaseDal.SqlQueryable(sql);
return emeterEnergies;
}
}
}