ibms-dome/z01_WinAPP/Service/getDeviceSvc.cs

583 lines
32 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using tpDomeWinAPP.Models;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using Repository.Helper;
using Repository.BackendRepository.Interface;
using Dapper;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using FrontendWebApi.Models;
using Autodesk.Forge.Model;
using MySql.Data.MySqlClient;
using System.Data.SqlTypes;
namespace tpDomeWinAPP.Service
{
public class getDeviceSvc
{
string Connection1 = string.Empty;
protected readonly IDatabaseHelper _databaseHelper;
protected string UseDB;
protected IDbConnection con;
private readonly IBackendRepository backendRepository;
public getDeviceSvc(string Connection_parame = null)
{
if (!string.IsNullOrEmpty(Connection_parame))
{
Connection1 = Connection_parame;
}
else
{
Connection1 = ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString;
}
}
public IDbConnection GetDbConnection()
{
IDbConnection conn;
//if (UseDB == "MSSQL")
//{
// conn = new SqlConnection(Connection1);
//}
//else
//{
//conn = new MySqlConnection(this._databaseHelper.GetMySqlConnectionString());
conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString);
//}
return conn;
}
//public List<NiagaraTags> getNiagaraPara()
//{
// var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
// List<NiagaraTags> result;
// //using (MySqlConnection conn = new MySqlConnection(Connection1))
// //{
// // //CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
// // conn.Open();
// // StringBuilder sb = new StringBuilder();
// // sb.Append(sql);
// // result = conn.Query<NiagaraTags>(sb.ToString()).ToList<NiagaraTags>();
// //}
// //var variableObix = backendRepository.GetAllAsync<Backend.Models.KeyValue>(sqlObix).Result;
// //var obixApiConfig = new Backend.Models.ObixApiConfig();
// //EDFunction ed = new EDFunction();
// //obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault();
// //obixApiConfig.UserName = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault();
// //obixApiConfig.Password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault();
// ////obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault();
// //webRequestService svc = new webRequestService();
// //var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "",
// // obixApiConfig.UserName, obixApiConfig.Password);
// //// ds.AddRange(data);
// return result;
//}
public List<FrontendWebApi.Models.HydroMeterOutput> test_bgWork_sql()
{
string jwt_str = null;
string tableType = "day";
string startTime = "2023-07";
string endTime = "2023-07-21";
List<HydroMeterOutput> apiResult = new List<HydroMeterOutput>();
try
{
//using (IDbConnection conn = GetDbConnection())
//{
// try
// {
// var sql = sqlString;
// result = await conn.QueryFirstOrDefaultAsync<A>(sql, param);
// }
// catch (Exception exception)
// {
// throw exception;
// }
// return result;
//}
using (IDbConnection conn = GetDbConnection())
{
//CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
startTime = tableType == "day" || tableType == "week"
? startTime + "-01"
: tableType == "month" || tableType == "year" ? startTime + "-01-01"
: null;
endTime = tableType == "day" || tableType == "week"
? startTime.Split("-")[0] + "-" + (Int32.Parse(startTime.Split("-")[1]) + 1).ToString().PadLeft(2, '0') + "-01"
: tableType == "month" ? (Int32.Parse(startTime.Split("-")[0]) + 1) + "-01-01"
: tableType == "year" ? (Int32.Parse(endTime) + 1).ToString() + "-01-01"
: null;
string sqlWhere = "";
string sqlGroup = "";
string sqlAvgRawData = "";
string building_tag = "G6";
string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0');
string buildingSql = "";
conn.Open();
//string tag_quantity = await backendRepository.GetOneAsync<string>("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0");
string tag_quantity = conn.Query<string>("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0").FirstOrDefault().ToString();
if (tag_quantity == "5")
buildingSql = " and SUBSTRING_INDEX(device_number, '_', 1) = @building_tag ";
else
buildingSql = " and SUBSTRING_INDEX(SUBSTRING_INDEX(device_number, '_', 2), '_', -1) = @building_tag ";
//if (input.floor_tag.Count > 0)
//{
// if (tag_quantity == "5")
// sqlWhere = $@" and substring_index(substring_index(device_number, '_', 3), '_', -1) in @floor_tag ";
// else
// sqlWhere = $@" and substring_index(substring_index(device_number, '_', 5), '_', -1) in @floor_tag ";
//}
if (tableType == "year")
{
sqlGroup = $@" group by year(start_timestamp), year(end_timestamp), device_number ";
sqlAvgRawData = " round(avg(avg_rawdata), 2) as avg_rawdata, year(start_timestamp) as start_timestamp, year(end_timestamp) as end_timestamp ";
}
else
sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp ";
var table = tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + tableType + (tableType == "day" ? "_" + dbDateName : "");
var schema = conn.Query<string>($"select system_value from variable where system_type = 'project_name'").FirstOrDefault();
var isTable = conn.Query<string>($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'").FirstOrDefault();
if (string.IsNullOrEmpty(isTable)) //check for has table or not
{
//MessageBox.Show("Empty");
}
var dateFormat = tableType == "day" || tableType == "week" ? "%Y-%m-%d" : tableType == "month" ? "%Y-%m" : tableType == "year" ? "%Y" : null;
var aemmEndDate = tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {tableType})";
var aemmStaDate = tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1;
select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then 0.00 else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from (
select *
from (
(
SELECT DATE(ADDDATE(@startTime, INTERVAL @i:=@i+1 day)) AS date
FROM {table}
HAVING @i < TIMESTAMPDIFF({tableType}, @startTime, ADDDATE(@endTime, INTERVAL -1 DAY))
) d,
(
select device_number
from {table}
where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'KWH' {buildingSql}
{sqlWhere}
group by device_number
) dn
)
) fd
left join (
select device_number, {sqlAvgRawData}
from {table}
where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'KWH' {buildingSql}
{sqlWhere} {sqlGroup}
) aemm on aemm.start_timestamp >= {aemmStaDate} and aemm.end_timestamp < {aemmEndDate} and aemm.device_number = fd.device_number
order by fd.device_number, fd.date";
var rawData = conn.Query<FrontendWebApi.Models.HydroMeterRawDataOutput> (sql,
new { startTime = startTime, endtime = endTime, building_tag = building_tag, dateFormat = dateFormat });
List<HydroMeterOutput> list = new List<HydroMeterOutput>();
if (tag_quantity == "5")
{
list = rawData
.GroupBy(x => new { building_tag = x.device_number.Split("_")[0], floor_tag = x.device_number.Split("_")[2], device_serial_tag = x.device_number.Split("_")[4], device_number = x.device_number })
.Select(x => new FrontendWebApi.Models.HydroMeterOutput { building_tag = x.Key.building_tag, floor_tag = x.Key.floor_tag, device_serial_tag = x.Key.device_serial_tag, device_number = x.Key.device_number })
.ToList();
}
else
{
list = rawData
.GroupBy(x => new { building_tag = x.device_number.Split("_")[1], floor_tag = x.device_number.Split("_")[4], device_master = x.device_number.Split("_")[5], device_serial_tag = x.device_number.Split("_")[7], device_number = x.device_number })
.Select(x => new FrontendWebApi.Models.HydroMeterOutput { building_tag = x.Key.building_tag, floor_tag = x.Key.floor_tag, device_serial_tag = x.Key.device_serial_tag, device_master = x.Key.device_master, device_number = x.Key.device_number })
.ToList();
}
foreach (var l in list)
{
l.rawData = new List<HydroMeterRawDataOutput>();
l.device_full_name = conn.Query<string>($"select full_name from device where device_number = '{l.device_number}'").FirstOrDefault();
if (tag_quantity == "5")
{
l.rawData.AddRange(
rawData.Where(x => x.device_number.Split("_")[0] == l.building_tag && x.device_number.Split("_")[2] == l.floor_tag && x.device_number.Split("_")[4] == l.device_serial_tag)
);
}
else
{
l.rawData.AddRange(
rawData.Where(x => x.device_number.Split("_")[1] == l.building_tag && x.device_number.Split("_")[4] == l.floor_tag && x.device_number.Split("_")[5] == l.device_master && x.device_number.Split("_")[7] == l.device_serial_tag)
);
}
l.building_name = conn.Query<string>("select full_name from building where building_tag = @building_tag and deleted = 0",
new { building_tag = l.building_tag }).FirstOrDefault();
l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => decimal.Parse(x.avg_rawdata ?? "0", System.Globalization.NumberStyles.Float)).ToString();
//l.price = input.price.HasValue
// ? (Math.Round(input.price.Value, 2)).ToString()
// : Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'ElectricPrice' and deleted = 0")), 2).ToString();
l.price = "5";
l.total_price = Math.Round((Decimal.Parse(l.total) * Decimal.Parse(l.price)), 2).ToString();
}
//apiResult.Code = "0000";
//apiResult.Data = list;
return list;
}
}
catch (Exception exception)
{
throw exception.InnerException;
//apiResult.Code = "9999";
//apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
//string json = System.Text.Json.JsonSerializer.Serialize(input);
//Logger.LogError("【" + controllerName + "/" + actionName + "】" + json);
//Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
}
}
public List<tpDomeWinAPP.Models.Device> getDevices()
{
using (SqlConnection conn = new SqlConnection(Connection1))
{
//CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
conn.Open();
var sql = $@"SELECT
d.*,
d.full_name AS Device_full_name,
b.full_name AS Building_full_name,
ms.full_name AS Main_system_full_name,
ss.full_name AS Sub_system_full_name,
f.full_name AS Floor_full_name,
dk.device_image,
device_image AS device_image_url,
dk.device_close_color,
dk.device_normal_color,
dk.device_error_color,
dk.device_normal_flashing,
dk.device_close_flashing,
dk.device_error_flashing,
(SELECT
STRING_AGG( ISNULL(system_key, ' '), ',')
FROM device_disaster dd
JOIN variable v ON v.deleted = 0 AND v.system_type = 'disaster' AND v.system_value = dd.device_system_value
WHERE dd.device_guid = d.device_guid
) AS Device_disaster_type_text
FROM (
SELECT *
FROM device d
WHERE
-- d.building_guid = @Building_guid
-- AND d.main_system_guid = @Main_system_guid
-- AND d.sub_system_guid = @Sub_system_guid
-- AND d.floor_guid = @Floor_guid AND
d.deleted = 0
) d
JOIN building b ON d.building_guid = b.building_guid
JOIN main_system ms ON d.main_system_guid = ms.main_system_guid
JOIN sub_system ss ON d.sub_system_guid = ss.sub_system_guid
JOIN floor f ON d.floor_guid = f.floor_guid
LEFT JOIN device_kind dk ON dk.device_building_tag = d.device_building_tag
AND dk.device_system_tag = d.device_system_tag
-- AND dk.device_floor_tag = d.device_floor_tag
AND dk.device_name_tag = d.device_name_tag
ORDER BY d.priority ASC, d.device_number ASC
";
var devices = conn.Query<tpDomeWinAPP.Models.Device>(sql).AsList<tpDomeWinAPP.Models.Device>();
return devices;
//var sql_node = $@"SELECT
// dn.device_node_guid,
// dn.device_guid,
// dn.full_name AS Device_node_full_name,
// dn.device_node_coordinate,
// dn.priority
// FROM device_node dn
// WHERE dn.deleted = 0 AND dn.device_guid = @device_guid
// ORDER BY dn.priority ASC";
//foreach (var device in devices)
//{
// device.Device_nodes = await backendRepository.GetAllAsync<DeviceNode>(sql_node, new { device_guid = device.Device_guid });
//}
}
}
#region insert DB
public bool clearTb_importData()
{
bool result = false;
using (SqlConnection conn = new SqlConnection(Connection1))
{
//CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
conn.Open();
StringBuilder sb = new StringBuilder();
int i = 0;
sb.Append($@" truncate table importExcel;
truncate table importData_batch;");
try
{
conn.Execute(sb.ToString());
}
catch (Exception ex)
{
throw ex;
}
}
return result;
}
public bool insertDB(DataTable dt)
{
bool result = false;
using (SqlConnection conn = new SqlConnection(Connection1))
{
//CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
conn.Open();
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (DataRow row in dt.Rows)
{
sb.Append($@" insert importExcel(intro, old_tags, new_tags, floor, device_name, device_note, device_type, device_number, atDateTime) values('" +
row["tag_name_zh"].ToString() + "', '" +
row["old_tags"].ToString() + "', '" +
row["new_tags"].ToString() + "', '" +
row["floor"].ToString() + "', '" +
row["device_name"].ToString() + "', '" +
row["device_note"].ToString() + "', '" +
row["device_type"].ToString() + "', '" +
row["device_number"].ToString() + "' , getdate());");
i++;
try
{
if (i >= 100)
{
conn.Execute(sb.ToString());
sb.Clear();
i = 0;
}
}
catch (Exception ex)
{
throw ex;
}
}
if (sb.Length > 0)
{
conn.Execute(sb.ToString());
}
}
return result;
}
public bool insertDB_batch() {
bool result = false;
using (SqlConnection conn = new SqlConnection(Connection1))
{
//CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url,
conn.Open();
StringBuilder sb = new StringBuilder();
sb.Append($@" select old_tags, new_tags, tag_no5, serial, tagName from
(
select old_tags, new_tags, tagName tag_no5
from importExcel a CROSS APPLY [Func_StringSplit](a.new_tags, '_')
where serial = 5 and new_tags like '%~%'
) b CROSS APPLY [Func_StringSplit](b.tag_no5, '~')
where serial = 2;");
var batchData = conn.Query<Device_batch>(sb.ToString());
int i = 0;
sb.Clear();
foreach (var row in batchData)
{
var ss = row.tag_no5.Split('~');
int start_num = int.Parse(ss[0]);
int end_num = int.Parse(ss[1]);
var ss_old = row.old_tags.Split('_');
var ss_new = row.new_tags.Split('_');
string vv5 = string.Empty;
//if (row.new_tags == "H_M10_B4F_FCU_001~108")
//{
// Console.WriteLine("here");
//}
for (int j = 1; j <= end_num; j++)
{
switch (ss[0].Length)
{
case 2: vv5 = (j <= 9) ? "0" + j.ToString() : j.ToString(); break;
case 3:
if (j <= 9)
// vv5 = "00" + j.ToString();
vv5 = "0" + j.ToString();
else if (j <= 99)
// vv5 = "0" + j.ToString();
vv5 = j.ToString();
else vv5 = j.ToString();
break;
}
string old_tag = ss_old[0] + "_" + ss_old[1] + "_" + ss_old[2] + "_" + ss_old[3] + "_" + vv5;
string new_tag = ss_new[0] + "_" + ss_new[1] + "_" + ss_new[2] + "_" + ss_new[3] + "_" + vv5;
sb.Append($@" insert importData_batch(old_tags, new_tags) values('" +
old_tag +"', '" +
new_tag + "'); ");
}
try
{
if (sb.Length > 0)
{
conn.Execute(sb.ToString());
sb.Clear();
result = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
try
{
#region web excel
sb.Append($@" update device set device_number_old = device_number where device_number_old is null");
conn.Execute(sb.ToString());
sb.Clear();
//1.2.更新欄位 device_number_old
sb.Append($@" update device set device_system_tag_old = b.tagName
from (select device_number, device_number_old, serial, tagName
from device a CROSS APPLY [Func_StringSplit](a.device_number, '_')
where serial = 2 and device_system_tag_old is null)b
where device.device_number_old = b.device_number_old and device_system_tag_old is null");
conn.Execute(sb.ToString());
sb.Clear();
#endregion
sb.Append("delete from importExcel where new_tags like '%~%'");
conn.Execute(sb.ToString());
sb.Clear();
sb.Append(@"insert importExcel(new_tags, old_tags)
select new_tags, old_tags from importData_batch");
conn.Execute(sb.ToString());
sb.Clear();
#region tableimport_dbTag_niagaraTag
#region table
string s1 = @" CREATE TABLE [dbo].[import_dbTag_niagaraTag](
[device_guid] [varchar](36) NOT NULL,
[full_name] [varchar](50) NOT NULL,
[device_number] [varchar](50) NOT NULL,
[niagaraTag] [varchar](50) NOT NULL,
[device_coordinate] [varchar](50) NULL,
[device_number_old] [varchar](50) NULL,
[device_building_tag] [varchar](50) NOT NULL,
[device_system_tag] [varchar](50) NOT NULL,
[device_system_tag_old] [varchar](50) NULL,
[device_floor_tag] [varchar](50) NOT NULL,
[device_name_tag] [varchar](50) NOT NULL,
[device_serial_tag] [varchar](50) NOT NULL,
[atDateTime] [smalldatetime] NULL,
CONSTRAINT [PK_import_dbTag_niagaraTag] PRIMARY KEY CLUSTERED
(
[device_guid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY];";
//string ss = @"IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'import_dbTag_niagaraTag'))
// BEGIN
// drop table import_dbTag_niagaraTag;
// END";
sb.Append("truncate table import_dbTag_niagaraTag");
conn.Execute(sb.ToString());
sb.Clear();
#endregion
sb.Append($@" insert import_dbTag_niagaraTag(device_guid, full_name, device_number, niagaraTag, device_coordinate, device_number_old, device_building_tag, device_system_tag, device_system_tag_old, device_floor_tag, device_name_tag, device_serial_tag, atDateTime)
select device_guid, full_name, device_number, '', device_coordinate, device_number_old, device_building_tag, device_system_tag, device_system_tag_old, device_floor_tag, device_name_tag, device_serial_tag, getDate()
from device where deleted = 0;");
conn.Execute(sb.ToString());
sb.Clear();
#region update niagara_tags
sb.Clear();
sb.Append($@"update import_dbTag_niagaraTag set niagaraTag = b.niagara_tags
from [dbo].[import_niagara_tag] b
where import_dbTag_niagaraTag.device_number = b.niagara_tags ");
conn.Execute(sb.ToString());
#endregion
#endregion tableimport_dbTag_niagaraTag
sb.Append(@"update import_dbTag_niagaraTag set device_number = b.new_tags,
device_system_tag = b.device_system_tag
from (
select old_tags, new_tags, serial, tagName as device_system_tag
from importExcel a CROSS APPLY [Func_StringSplit](a.new_tags, '_')
where serial = 2) b
where [import_dbTag_niagaraTag].device_number_old = b.old_tags");
conn.Execute(sb.ToString());
sb.Clear();
sb.Append(@"update [dbo].[device] set device.device_number = b.new_tags,
device_system_tag = b.device_system_tag
from (
select old_tags, new_tags, serial, tagName as device_system_tag
from importExcel a CROSS APPLY [Func_StringSplit](a.new_tags, '_')
where serial = 2) b
where [device].device_number_old = b.old_tags");
conn.Execute(sb.ToString());
sb.Clear();
sb.Append(@"update device_import_ckeck_temp set device_system_tag = b.device_system_tag,
device_number = b.device_number
from device b
where device_import_ckeck_temp.device_building_tag = b.device_building_tag and
device_import_ckeck_temp.device_system_tag_old = b.device_system_tag_old and
device_import_ckeck_temp.device_number_old = b.device_number_old
and device_import_ckeck_temp.device_number <> b.device_number");
conn.Execute(sb.ToString());
sb.Clear();
sb.Append(@"update device_kind set device_system_tag = b.device_system_tag
from device b
where device_kind.device_building_tag = b.device_building_tag and
device_kind.device_system_tag_old = b.device_system_tag_old and
device_kind.device_name_tag = b.device_name_tag");
conn.Execute(sb.ToString());
sb.Clear();
result = true ;
}
catch (Exception ex)
{
throw ex;
}
}
return result;
}
#endregion
}
}