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 { 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>>> GetDeviceList() { ApiResult> apiResult = new ApiResult>(jwt_str); if (!jwtlife) { apiResult.Code = "5000"; return BadRequest(apiResult); } try { List buildingMenus = new List(); var buildmenusql = await backendRepository.GetAllAsync(@$"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(@" 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() }; 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() }; 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>> GetOneDevice(string device_number) { ApiResult apiResult = new ApiResult(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(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); } /// /// 取得L型選單的alarm的報警設備 /// 由原本的obix打API方式改為此action /// /// [HttpPost] [Route("api/Device/MenuAlarm")] public async Task>>> MenuAlarm(string account) { ApiResult> apiResult = new ApiResult>(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(sql); List alarmDevices = new List(); 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(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); } /// /// 取得報警設備 /// /// [HttpPost] [Route("api/Device/Getalarm")] public async Task>> Alarm() { ApiResult apiResult = new ApiResult(jwt_str); if (!jwtlife) { apiResult.Code = "5000"; return BadRequest(apiResult); } try { AlarmObj alarmObj = new AlarmObj() { alarmorion = new List(), buildingAlarmDeviceAmount = new List() }; // 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(sql); // old寫法 //List Alarmorions = new List(); //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(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); } /// /// 修改設備名稱(打後台API) /// /// /// [HttpPost] [Route("api/Device/SaveChangeName")] public async Task>> SaveChangeName(ChangeName change) { ApiResult apiResult = new ApiResult(jwt_str); if (!jwtlife) { apiResult.Code = "5000"; return BadRequest(apiResult); } try { string authHeader = HttpContext.Request.Headers["Authorization"]; var websiteurl = await frontendRepository.GetOneAsync("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>> GetHaveChangeNameRole(ChangeNameRole role) { ApiResult apiResult = new ApiResult(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(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); } } }