ibms-dome/FrontendWebApi/ApiControllers/DeviceManageController.cs
2022-10-14 16:08:54 +08:00

439 lines
19 KiB
C#

using FrontendWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FrontendWebApi.ApiControllers
{
public class DeviceManageController : MyBaseApiController<DeviceManageController>
{
private readonly IBackendRepository backendRepository;
private readonly IFrontendRepository frontendRepository;
public DeviceManageController
(
IBackendRepository backendRepository,
IFrontendRepository frontendRepository
)
{
this.backendRepository = backendRepository;
this.frontendRepository = frontendRepository;
}
[HttpPost]
[Route("api/Device/GetDeviceList")]
public async Task<ActionResult<ApiResult<List<Device>>>> GetDeviceList()
{
ApiResult<List<Building>> apiResult = new ApiResult<List<Building>>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
List<Building> buildingMenus = new List<Building>();
var buildmenusql = await backendRepository.GetAllAsync<BuildMenuSql>(@$"select
me.* , b.full_name bfull_name,b.ip_address,b.priority bpriority,
ma.full_name mafull_name,ma.priority mapriority,ma.code,
sub.full_name subfull_name,sub.priority subpriority
from building_menu me
left join building b on b.building_guid = me.building_guid
left join main_system ma on ma.main_system_guid = me.main_system_guid
left join sub_system sub on sub.sub_system_guid = me.sub_system_guid");
var floorsql = await backendRepository.GetAllAsync<Floorsql>(@"
select * from (select * from sub_system_floor ssf where ssf.deleted = 0 and ssf.status = 0) a
left join floor on floor.floor_guid = a.floor_guid");
var building = buildmenusql.GroupBy(a => a.building_guid).ToList();
foreach (var menu in building)
{
Building building1 = new Building()
{
building_guid = menu.Select(a => a.building_guid).FirstOrDefault(),
full_name = menu.Select(a => a.bfull_name).FirstOrDefault(),
ip_address = menu.Select(a => a.ip_address).FirstOrDefault(),
priority = menu.Select(a => a.bpriority).FirstOrDefault(),
main_system = new List<Main_system>()
};
var mainsystem = menu.GroupBy(a => a.main_system_guid).ToList();
foreach (var ma in mainsystem)
{
Main_system main_System = new Main_system()
{
code = ma.Select(a => a.code).FirstOrDefault(),
main_system_guid = ma.Select(a => a.main_system_guid).FirstOrDefault(),
full_name = ma.Select(a => a.mafull_name).FirstOrDefault(),
priority = ma.Select(a => a.mapriority).FirstOrDefault(),
Sub_system = new List<Sub_systemGuid>()
};
var subsystem = ma.GroupBy(a => a.sub_system_guid).ToList();
foreach (var sub in subsystem)
{
Sub_systemGuid sub_System = new Sub_systemGuid()
{
sub_system_guid = sub.Select(a => a.sub_system_guid).FirstOrDefault(),
full_name = sub.Select(a => a.subfull_name).FirstOrDefault(),
priority = sub.Select(a => a.subpriority).FirstOrDefault()
};
main_System.Sub_system.Add(sub_System);
}
building1.main_system.Add(main_System);
}
buildingMenus.Add(building1);
}
apiResult.Data = buildingMenus;
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
[HttpPost]
[Route("api/Device/GetOneDevice")]
public async Task<ActionResult<ApiResult<Device>>> GetOneDevice(string device_number)
{
ApiResult<Device> apiResult = new ApiResult<Device>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
string 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
FROM (
SELECT *
FROM device d
WHERE
d.device_number = @Device_number
AND d.deleted = @Deleted
) 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
";
object param = new { Deleted = 0, Device_number = device_number };
var device = await backendRepository.GetOneAsync<Device>(sql, param);
apiResult.Data = device;
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
/// <summary>
/// 取得L型選單的alarm的報警設備
/// 由原本的obix打API方式改為此action
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("api/Device/MenuAlarm")]
public async Task<ActionResult<ApiResult<List<OntimeAlarmRawData>>>> MenuAlarm(string account)
{
ApiResult<List<OntimeAlarmRawData>> apiResult = new ApiResult<List<OntimeAlarmRawData>>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
//取得發生異常的設備
string sql = $@"
SELECT
unicode_decode(value) device_point
FROM alarmorion_orionalarmrecord a
JOIN alarmorion_orionalarmfacetvalue b on a.id = b.alarm
WHERE a.sourceState = 1 and b.facetName = 9";
var alarmDevicePoints = await frontendRepository.GetAllAsync<string>(sql);
List<string> alarmDevices = new List<string>();
foreach (var alarmDevicePoint in alarmDevicePoints)
{
var alarmDevicePointSplit = alarmDevicePoint.Split("_");
var alarmDevice = string.Join("_", alarmDevicePointSplit.SkipLast(1));
if (!alarmDevices.Contains(alarmDevice))
{
alarmDevices.Add(alarmDevice);
}
}
var sqlDevice = $@"
SELECT
d.building_guid,
d.main_system_guid,
d.sub_system_guid,
d.floor_guid,
d.device_number
FROM Device d
INNER JOIN (
SELECT
ap.building_guid,
ap.ShowView AS sub_system_guid
FROM
(
SELECT *
FROM role_auth ra
WHERE ra.role_guid = (SELECT ui.role_guid FROM userinfo ui WHERE account = @Account)
) ra
LEFT JOIN auth_page ap ON ra.AuthCode = ap.AuthCode
WHERE ap.AuthType = 1
) shower ON d.building_guid = shower.building_guid AND d.sub_system_guid = shower.sub_system_guid
WHERE d.deleted = 0 AND d.device_number IN @DeviceNumbers
";
var menuAlarmDevices = await frontendRepository.GetAllAsync<OntimeAlarmRawData>(sqlDevice, new { Account = account, DeviceNumbers = alarmDevices });
apiResult.Data = menuAlarmDevices;
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
/// <summary>
/// 取得報警設備
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("api/Device/Getalarm")]
public async Task<ActionResult<ApiResult<AlarmObj>>> Alarm()
{
ApiResult<AlarmObj> apiResult = new ApiResult<AlarmObj>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
AlarmObj alarmObj = new AlarmObj()
{
alarmorion = new List<AlarmorionString>(),
buildingAlarmDeviceAmount = new List<BuildingAlarmDeviceAmount>()
};
// old寫法
//string sql = $@"SELECT sl.source device_number,from_unixtime(amc.timestamp/1000,'%Y-%m-%d %H:%i:%s') alarm_timestamp FROM alarmorion_orionalarmrecord amc
// JOIN (
// SELECT MAX(amc.alarm) ad,m.source FROM alarmorion_orionalarmsourceorder amc
// JOIN (SELECT * FROM alarmorion_orionalarmsource a WHERE substring(a.source,23,5) ='Arena') m ON amc.alarmSource = m.id
// GROUP BY m.source
// ) sl ON amc.id = sl.ad
// WHERE amc.sourceState = 1
// ";
string sql = $@"
select * from
(
SELECT a.* ,from_unixtime(a.timestamp/1000,'%Y-%m-%d %H:%i:%s') alarm_timestamp, errmsg device_point,
substring( errmsg, 1,
LENGTH(errmsg) -
LENGTH(SUBSTRING_INDEX(errmsg, '_', -1) -1) -- 最後一段的長度
-1 -- 減掉最後的 _ ex:D3_B_B1F_CO_
) device_tag
FROM alarmorion_orionalarmrecord a
JOIN alarmorion_orionalarmfacetvalue b on a.id = b.alarm
WHERE a.sourceState = 1 and b.facetName = 9
) a
left join device b on a.device_tag = b.device_number AND b.deleted = 0
left join device_disaster c on b.device_guid = c.device_guid
WHERE c.device_system_value IS NOT NULL";
var alarms = await frontendRepository.GetAllAsync<AlarmorionString>(sql);
// old寫法
//List<AlarmorionString> Alarmorions = new List<AlarmorionString>();
//foreach (var alarm in alarms)
//{
// var source = alarm.device_number.Split('/');
// //if(source[2] != "H")
// //{
// // continue;
// //}
// alarm.device_number = source[6];
// Alarmorions.Add(alarm);
//}
//alarmObj.alarmorion = Alarmorions.GroupBy(a => new { a.device_number, a.alarm_timestamp }).Select(a => a.First()).ToList();
foreach(var alarm in alarms)
{
var temp_alarm = alarmObj.alarmorion.Find(x => x.device_number == alarm.device_number);
if (temp_alarm == null)
{
alarmObj.alarmorion.Add(alarm);
}
}
var device_amount_sql = $@"SELECT
d.building_guid,
COUNT(*) AS device_amount
FROM device d
WHERE d.deleted = 0
AND d.device_number IN @devices
GROUP BY d.building_guid";
alarmObj.buildingAlarmDeviceAmount = await frontendRepository.GetAllAsync<BuildingAlarmDeviceAmount>(device_amount_sql, new { devices = alarmObj.alarmorion.Select(x => x.device_number).ToList() });
apiResult.Data = alarmObj;
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
/// <summary>
/// 修改設備名稱(打後台API)
/// </summary>
/// <param name="change"></param>
/// <returns></returns>
[HttpPost]
[Route("api/Device/SaveChangeName")]
public async Task<ActionResult<ApiResult<string>>> SaveChangeName(ChangeName change)
{
ApiResult<string> apiResult = new ApiResult<string>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
string authHeader = HttpContext.Request.Headers["Authorization"];
var websiteurl = await frontendRepository.GetOneAsync<string>("select system_value from variable where system_type = 'website_config' and system_key = 'website_url' ");
//傳送到後台API
HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{websiteurl}api/Device/SaveChangeName");
request.Method = "POST";
request.Headers.Add("Authorization", authHeader);
request.ContentType = "application/x-www-form-urlencoded";
request.PreAuthenticate = true;
NameValueCollection postParams = System.Web.HttpUtility.ParseQueryString(string.Empty);
postParams.Add("TagName", change.TagName);
postParams.Add("ChangeN", change.ChangeN);
postParams.Add("ChooseTable", change.ChooseTable.ToString());
byte[] postData = Encoding.UTF8.GetBytes(postParams.ToString());
using (Stream st = request.GetRequestStream())
{
st.Write(postData, 0, postData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var statusNumber = (int)response.StatusCode;
if (statusNumber != 200)
{
throw new NotImplementedException(responseString);
}
else
{
//解析回傳內容
var final = JObject.Parse(responseString);
apiResult.Code = final["code"].ToString();
apiResult.Data = final["data"].ToString();
}
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
[HttpPost]
[Route("api/Device/GetHaveChangeNameRole")]
public async Task<ActionResult<ApiResult<bool>>> GetHaveChangeNameRole(ChangeNameRole role)
{
ApiResult<bool> apiResult = new ApiResult<bool>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
var sql = $@"
select * from userinfo u
join role_auth a on a.role_guid = u.role_guid
join auth_page p on p.AuthCode = a.AuthCode
where u.account = N'{role.Account}'
and p.SubName = N'編輯設備名稱'
and p.building_guid = N'{role.Building_guid}'";
var have = await backendRepository.GetOneAsync<string>(sql);
if (have == null)
{
apiResult.Data = false;
}
else
{
apiResult.Data = true;
}
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
}
}