FIC_Solar/SolarPower/Repository/Implement/OverviewRepository.cs
2021-07-06 20:12:00 +08:00

122 lines
4.4 KiB
C#

using Dapper;
using SolarPower.Helper;
using SolarPower.Models;
using SolarPower.Models.PowerStation;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace SolarPower.Repository.Implement
{
public class OverviewRepository : RepositoryBase<Overview>, IOverviewRepository
{
public OverviewRepository(IDatabaseHelper databaseHelper) : base(databaseHelper)
{
tableName = "power_station";
}
public async Task<List<int>> GetAllCityIdAsync()
{
List<int> result;
using (IDbConnection conn = this._databaseHelper.GetConnection())
{
try
{
var sql = $"SELECT Id FROM city";
result = (await conn.QueryAsync<int>(sql)).ToList();
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
public async Task<Overview> GetOverviewByPowerStationIds(List<int> powerStationIds)
{
Overview result;
using (IDbConnection conn = this._databaseHelper.GetConnection())
{
try
{
var sql = @$"SELECT
SUM(ps.Today_kwh) AS Today_kwh,
SUM(ps.Total_kwh) AS Total_kwh,
AVG(ps.Today_irradiance) AS today_irradiance,
AVG(ps.avg_irradiance) AS avg_irradiance,
AVG(ps.today_PR) AS today_PR,
AVG(ps.avg_PR) AS avg_PR,
AVG(ps.today_kwhkwp) AS today_kwhkwp,
AVG(ps.avg_kwhkwp) AS avg_kwhkwp,
SUM(ps.today_carbon) AS today_carbon,
SUM(ps.total_carbon) AS total_carbon
FROM power_station ps
WHERE ps.Id IN @PowerStationIds
";
result = await conn.QueryFirstOrDefaultAsync<Overview>(sql, new { PowerStationIds = powerStationIds });
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
public async Task<List<CapacityDataTable>> GetCapacityDataTableByPowerStationIds(List<int> powerStationIds)
{
List<CapacityDataTable> result;
using (IDbConnection conn = this._databaseHelper.GetConnection())
{
try
{
var sql = @$"SELECT
ps.CityId,
c.Name AS CityName,
COUNT(*) AS SubPowerStationCount,
SUM(ps.GeneratingCapacity) AS SubTotalCapacity
FROM power_station ps
LEFT JOIN city c ON ps.CityId = c.Id
WHERE ps.Id IN @PowerStationIds
GROUP BY ps.CityId
";
result = (await conn.QueryAsync<CapacityDataTable>(sql, new { PowerStationIds = powerStationIds })).ToList();
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
public async Task<List<PowerStation>> GetListPowerStationByPowerStationIds(List<int> powerStationIds)
{
List<PowerStation> result;
using (IDbConnection conn = this._databaseHelper.GetConnection())
{
try
{
var sql = @$"SELECT * FROM power_station ps WHERE ps.Id IN @PowerStationIds
";
result = (await conn.QueryAsync<PowerStation>(sql, new { PowerStationIds = powerStationIds })).ToList();
}
catch (Exception exception)
{
throw exception;
}
return result;
}
}
}
}