using Entity.Ammeter;
using Entity.Dto.Req;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Entity;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Repository.Ammeter;
using SqlSugar;
namespace Service.Ammeter
{
///
///
///
[Scope("SingleInstance")]
public class EmeterHourEnergyService: BaseServices
{
public EmeterHourEnergyService(EmeterHourEnergyRepository service)
{
this.BaseDal = service;
}
public async Task>> Page(PageAmmeterReq queryPageModel)
{
QueryPageModel queryPageModel1 = new QueryPageModel
{
PageNum = queryPageModel.PageNum,
PageSize = queryPageModel.PageSize,
};
if (!string.IsNullOrEmpty(queryPageModel.Code))
return Result>.Success(PageResult.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, u => u.Code == queryPageModel.Code)));
else
return Result>.Success(PageResult.ConvertPage(this.BaseDal.QueryIPageByCause(queryPageModel1, null)));
}
///
/// 获取直流电表实时数据
///
///
public async Task> GetEnergyMeterRealTime(string endTime, int type)
{
// 将传入的时间参数转换为 DateTime 类型
DateTime endDateTime = DateTime.Parse(endTime);
// 根据传入的时间参数计算 1 天前的时间
DateTime startDateTime = endDateTime.AddDays(-1);
// 构建 SQL 查询字符串并包含参数
string sql = @"
WITH latest_data AS (
SELECT
code,
MAX(time) AS latest_upload_time
FROM emeter_hour_energy
WHERE time >= @StartDateTime AND time <= @EndDateTime
AND type = @Type
GROUP BY code
),
max_value_data AS (
SELECT
e.*,
ROW_NUMBER() OVER (PARTITION BY e.code ORDER BY e.real_time_value DESC) AS rn
FROM emeter_hour_energy e
JOIN latest_data ld ON e.code = ld.code AND e.time = ld.latest_upload_time
WHERE e.type = @Type
)
SELECT
*
FROM max_value_data
WHERE rn = 1;
";
// 使用参数化查询防止 SQL 注入
var parameters = new List
{
new SugarParameter("@StartDateTime", startDateTime),
new SugarParameter("@EndDateTime", endDateTime),
new SugarParameter("@Type", type)
};
// 调用现有的 SqlQuery 方法
List emeterEnergyChanges = this.BaseDal.SqlQuery(sql, parameters);
return emeterEnergyChanges;
}
}
}