From 8dd6c4c4c35dbc6838c7d766286c39927bdeb8f3 Mon Sep 17 00:00:00 2001 From: "jay.chang" Date: Mon, 6 May 2024 10:58:38 +0800 Subject: [PATCH] =?UTF-8?q?[WebApi]=E6=AD=B7=E5=8F=B2=E8=B3=87=E6=96=99?= =?UTF-8?q?=E6=9B=B4=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ApiControllers/DeviceManageController.cs | 46 +- .../ApiControllers/HistoryController.cs | 1208 ++++++++++++++++- FrontendWebApi/Models/HistoryClass.cs | 77 +- FrontendWebApi/Models/MyBase.cs | 1 + 4 files changed, 1313 insertions(+), 19 deletions(-) diff --git a/FrontendWebApi/ApiControllers/DeviceManageController.cs b/FrontendWebApi/ApiControllers/DeviceManageController.cs index eb24c3c..83fdfb8 100644 --- a/FrontendWebApi/ApiControllers/DeviceManageController.cs +++ b/FrontendWebApi/ApiControllers/DeviceManageController.cs @@ -51,17 +51,42 @@ namespace FrontendWebApi.ApiControllers apiResult.Code = "5000"; return BadRequest(apiResult); } - else if (string.IsNullOrEmpty(fd.building_tag)) + List dbsub = new List(); + string sWhere = @$"where c.account = @account"; + var is_Binding = await backendRepository.GetOneAsync("select system_value from variable where system_type = 'AuthPageBindingSubsystem' and system_key = 'is_Binding' and deleted = 0"); + if (is_Binding == "0") { - apiResult.Code = "0002"; - apiResult.Msg = "必須選擇東別"; - return apiResult; + sWhere = string.Empty; } - try { - var dbsub = await frontendRepository.GetAllAsync( - @$"select distinct v1.system_key main_name, v1.system_value main_system_tag, v2.system_key sub_name, v2.system_value sub_system_tag, v1.system_priority, v2.system_priority, + if (string.IsNullOrEmpty(fd.building_tag)) + { + dbsub = await frontendRepository.GetAllAsync( + @$"select distinct v1.system_key main_name, v1.system_value main_system_tag, v2.system_key sub_name, v2.system_value sub_system_tag, v1.system_priority, v2.system_priority, bm.priority, + dk.device_normal_color, dk.device_close_color, dk.device_error_color,dk.device_normal_flashing, dk.device_close_flashing, dk.device_error_flashing, + dk.device_normal_text, dk.device_close_text, dk.device_error_text,dk.device_normal_point_name, dk.device_close_point_name, dk.device_error_point_name, + dk.device_normal_point_value, dk.device_close_point_value, dk.device_error_point_value + -- di.full_name as device_item_name, di.points as device_item_points, di.unit as device_item_unit, di.is_show_riserDiagram as device_item_is_show_riserDiagram, + -- di.is_controll as device_item_is_controll, di.is_bool as device_item_is_bool, di.is_link as device_item_is_link + from role_auth a + join auth_page b on a.AuthCode = b.AuthCode + join userinfo c on c.role_guid = a.role_guid + join variable v2 on b.ShowView = v2.id and v2.system_type = @sub_system_type + join variable v1 on v1.id = v2.system_parent_id and v1.system_type = @main_system_type + join device d on v1.system_value = d.device_system_tag and v2.system_value = d.device_name_tag and d.deleted = 0 + left join device_kind dk on v1.system_value = dk.device_system_tag and v2.system_value = dk.device_name_tag + -- left join device_item di on v2.system_value = di.device_name_tag and v1.system_value = di.device_system_tag and di.deleted = 0 + join ( + select distinct main_system_tag, sub_system_tag, priority from building_menu where is_link = 1 + ) as bm on v2.system_value = bm.sub_system_tag and v1.system_value = bm.main_system_tag + {sWhere} + order by v2.system_priority, bm.priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type }); + } + else + { + dbsub = await frontendRepository.GetAllAsync( + @$"select distinct v1.system_key main_name, v1.system_value main_system_tag, v2.system_key sub_name, v2.system_value sub_system_tag, v1.system_priority, v2.system_priority, bm.priority, dk.device_normal_color, dk.device_close_color, dk.device_error_color,dk.device_normal_flashing, dk.device_close_flashing, dk.device_error_flashing, dk.device_normal_text, dk.device_close_text, dk.device_error_text,dk.device_normal_point_name, dk.device_close_point_name, dk.device_error_point_name, dk.device_normal_point_value, dk.device_close_point_value, dk.device_error_point_value @@ -76,10 +101,11 @@ namespace FrontendWebApi.ApiControllers left join device_kind dk on v1.system_value = dk.device_system_tag and v2.system_value = dk.device_name_tag and dk.device_building_tag = @building_tag -- left join device_item di on v2.system_value = di.device_name_tag and v1.system_value = di.device_system_tag and di.deleted = 0 join ( - select distinct main_system_tag, sub_system_tag from building_menu where building_tag = @building_tag and is_link = 1 + select distinct main_system_tag, sub_system_tag, priority from building_menu where building_tag = @building_tag and is_link = 1 ) as bm on v2.system_value = bm.sub_system_tag and v1.system_value = bm.main_system_tag - where c.account = @account - order by v2.system_priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type, @building_tag = fd.building_tag }); + {sWhere} + order by v2.system_priority, bm.priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type, @building_tag = fd.building_tag }); + } var mains = dbsub.GroupBy(a => a.main_system_tag).ToList(); apiResult.Data = new History_MainSubBuildFloor(); apiResult.Data.history_Main_Systems = new List(); diff --git a/FrontendWebApi/ApiControllers/HistoryController.cs b/FrontendWebApi/ApiControllers/HistoryController.cs index bea7cee..76c4d6c 100644 --- a/FrontendWebApi/ApiControllers/HistoryController.cs +++ b/FrontendWebApi/ApiControllers/HistoryController.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using NPOI.HPSF; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using Repository.BackendRepository.Interface; @@ -19,7 +18,7 @@ using System.Net; using System.Text; using System.Threading.Tasks; using System.Xml; -using Decimal = System.Decimal; +using System.Diagnostics; namespace FrontendWebApi.ApiControllers @@ -340,6 +339,497 @@ namespace FrontendWebApi.ApiControllers return File(ms, "application/vnd.ms-excel", fileName); } + /// + /// 匯出excel + /// + /// + /// + [HttpPost] + [Route("api/ExportHistoryExcel")] + public IActionResult ExportHistoryExcel([FromBody] PostHistoryDataFilter post) + { + ApiResult apiResult = new ApiResult(); + var fileDateName = post.Type == 1 ? $@"{post.Start_date}T{post.Start_time}~{post.End_date}T{post.End_time}" : $@"{post.Start_date}~{post.End_date}&T{post.Start_time}~T{post.End_time}"; + var fileName = "歷史資料_" + fileDateName + ".xlsx"; + + XSSFWorkbook workbook = new XSSFWorkbook(); + try + { + #region 取得obix 設定 + EDFunction ed = new EDFunction(); + var obixApiConfig = new ObixApiConfig(); + var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; + var variableObix = backendRepository.GetAllAsync(sqlObix).Result; + obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); + obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault()); + obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault()); + String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password)); + #endregion 取得obix 設定 + #region get device and device_item(point) + var device = backendRepository.GetAllAsync($"select * from device where deleted = 0 and is_link = 1 and device_number in @Device_list", new { Device_list = post.Device_list }).Result; + var devicePoint = backendRepository.GetAllAsync($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag in @building_tag", new { building_tag = post.Building_tag_list }).Result; + #endregion + var building = backendRepository.GetAllAsync("select * from building where deleted = 0").Result; + List listDevicePoint = new List(); + List he = new List(); + List jd = new List(); + #region combine device and point + foreach (var Device in post.Device_list) + { + foreach (var point in post.Points) + { + DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint(); + deviceNumberPoint.DeviceNumber = Device; + deviceNumberPoint.Point = point; + deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", Device, point); + + listDevicePoint.Add(deviceNumberPoint); + } + } + #endregion + + #region get data from niagara + if (post.Type == 1) + { + #region Niagara抓資料依據日期 + + //轉換日期格式 + var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time); + var end = string.Format("{0}T{1}:01.000+08:00", post.End_date, post.End_time); + + var historyQueryFilter = $@" + + + "; + + XmlDocument xmlDocument = new XmlDocument(); + List errorPoints = new List(); //錯誤的設備點位 + if (listDevicePoint.Count > 0) + { + foreach (var d in listDevicePoint) + { + var station = backendRepository.GetOneAsync($@"select parent_path from import_niagara_item_history where device_building_tag = '{d.FullDeviceNumberPoint.Split("_")[1].Replace("$3", "")}' and + device_system_tag = '{d.FullDeviceNumberPoint.Split("_")[2]}' and device_name_tag = '{d.FullDeviceNumberPoint.Split("_")[3]}' + and device_floor_tag = '{d.FullDeviceNumberPoint.Split("_")[4]}' and device_master_tag = '{d.FullDeviceNumberPoint.Split("_")[5]}' + and device_last_name_tag = '{d.FullDeviceNumberPoint.Split("_")[6]}' and device_serial_tag = '{d.FullDeviceNumberPoint.Split("_")[7]}' + and device_point_name = '{d.FullDeviceNumberPoint.Split("_")[8]}'").Result; + + if (!string.IsNullOrEmpty(station)) + { + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyQuery/"); + request.Method = "POST"; + request.Headers.Add("Authorization", "Basic " + encoded); + request.PreAuthenticate = true; + + byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter); + using (Stream reqStream = request.GetRequestStream()) + { + reqStream.Write(byteArray, 0, byteArray.Length); + } + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd(); + + xmlDocument.LoadXml(responseContent); + string responseContentJson = JsonConvert.SerializeXmlNode(xmlDocument); + JObject responseContentJsonResult = (JObject)JsonConvert.DeserializeObject(responseContentJson); + + if (responseContentJsonResult.ContainsKey("err")) //抓取錯誤 + { + errorPoints.Add(d.DeviceNumber); + continue; + } + + + if (responseContentJsonResult.ContainsKey("obj")) //表示可以讀取到內容 + { + var countObj = responseContentJsonResult["obj"]["int"]; + if (countObj != null && countObj["@name"].ToString() == "count") + { //判斷是否有資料筆數 + if (Convert.ToInt32(countObj["@val"].ToString()) > 0) + { + var dataList = responseContentJsonResult["obj"]["list"]; + if (dataList != null && dataList["obj"].HasValues) + { + //判斷單筆資料還是多筆 + if (Convert.ToInt32(countObj["@val"].ToString()) == 1) + { + + HistoryRawData historyRawData = new HistoryRawData(); + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + string buildingTag = d.DeviceNumber.Split("_")[1]; + //取得時間 + var abstime = dataList["obj"]["abstime"]["@val"].ToString(); + var val = dataList["obj"]["real"] != null ? + dataList["obj"]["real"]["@val"].ToString() : dataList["obj"]["bool"]["@val"].ToString(); + + HistoryExport hed = new HistoryExport(); + hed.device_number = device_number; + hed.type = devicePoint.Where(x => x.device_building_tag == buildingTag && x.points == point).Select(x => x.full_name).FirstOrDefault(); + hed.deviceName = device.Where(x => x.device_number == device_number).Select(x => x.full_name).FirstOrDefault(); + hed.value = val; + hed.timestamp = Convert.ToDateTime(abstime); + hed.building_tag = buildingTag; + he.Add(hed); + + } + else + { + //讀取資料 + foreach (var obj in dataList["obj"]) + { + + HistoryRawData historyRawData = new HistoryRawData(); + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + string buildingTag = d.DeviceNumber.Split("_")[1]; + //取得時間 + var abstime = obj["abstime"]["@val"].ToString(); + var val = obj["real"] != null ? + obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString(); + + HistoryExport hed = new HistoryExport(); + hed.device_number = device_number; + hed.type = devicePoint.Where(x => x.device_building_tag == buildingTag && x.points == point).Select(x => x.full_name).FirstOrDefault(); + hed.deviceName = device.Where(x => x.device_number == device_number).Select(x => x.full_name).FirstOrDefault(); + hed.value = val; + hed.timestamp = Convert.ToDateTime(abstime); + hed.building_tag = buildingTag; + he.Add(hed); + } + } + } + } + } + } + } + else + { + Logger.LogError("【Device GetWay Error】, device_number: " + d.FullDeviceNumberPoint); + } + } + } + + if (errorPoints.Count() > 0) + { + Logger.LogError("【Device GetWay Error】, device_number: " + errorPoints); + } + + #endregion + } + if (post.Type == 2) + { + #region Niagara抓資料依據時間段 + DateTime startday = DateTime.Parse(post.Start_date); + DateTime endtday = DateTime.Parse(post.End_date); + List dateRange = Enumerable.Range(0, (endtday - startday).Days + 1) + .Select(a => startday.AddDays(a)) + .ToList(); + foreach (var day in dateRange) + { + //轉換日期格式 + var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time); + var end = string.Format("{0}T{1}:01.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time); + + var historyQueryFilter = $@" + + + "; + + XmlDocument xmlDocument = new XmlDocument(); + List errorPoints = new List(); //錯誤的設備點位 + if (listDevicePoint.Count > 0) + { + foreach (var d in listDevicePoint) + { + var station = backendRepository.GetOneAsync($@"select parent_path from import_niagara_item_history where device_building_tag = '{d.FullDeviceNumberPoint.Split("_")[1].Replace("$3", "")}' and + device_system_tag = '{d.FullDeviceNumberPoint.Split("_")[2]}' and device_name_tag = '{d.FullDeviceNumberPoint.Split("_")[3]}' + and device_floor_tag = '{d.FullDeviceNumberPoint.Split("_")[4]}' and device_master_tag = '{d.FullDeviceNumberPoint.Split("_")[5]}' + and device_last_name_tag = '{d.FullDeviceNumberPoint.Split("_")[6]}' and device_serial_tag = '{d.FullDeviceNumberPoint.Split("_")[7]}' + and device_point_name = '{d.FullDeviceNumberPoint.Split("_")[8]}'").Result; + + if (!string.IsNullOrEmpty(station)) + { + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyQuery/"); + request.Method = "POST"; + request.Headers.Add("Authorization", "Basic " + encoded); + request.PreAuthenticate = true; + + byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter); + using (Stream reqStream = request.GetRequestStream()) + { + reqStream.Write(byteArray, 0, byteArray.Length); + } + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd(); + + xmlDocument.LoadXml(responseContent); + string responseContentJson = JsonConvert.SerializeXmlNode(xmlDocument); + JObject responseContentJsonResult = (JObject)JsonConvert.DeserializeObject(responseContentJson); + + if (responseContentJsonResult.ContainsKey("err")) //抓取錯誤 + { + errorPoints.Add(d.DeviceNumber); + continue; + } + + + if (responseContentJsonResult.ContainsKey("obj")) //表示可以讀取到內容 + { + var countObj = responseContentJsonResult["obj"]["int"]; + if (countObj != null && countObj["@name"].ToString() == "count") + { //判斷是否有資料筆數 + if (Convert.ToInt32(countObj["@val"].ToString()) > 0) + { + var dataList = responseContentJsonResult["obj"]["list"]; + if (dataList != null && dataList["obj"].HasValues) + { + //判斷單筆資料還是多筆 + if (Convert.ToInt32(countObj["@val"].ToString()) == 1) + { + + HistoryRawData historyRawData = new HistoryRawData(); + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + string buildingTag = d.DeviceNumber.Split("_")[1]; + //取得時間 + var abstime = dataList["obj"]["abstime"]["@val"].ToString(); + var val = dataList["obj"]["real"] != null ? + dataList["obj"]["real"]["@val"].ToString() : dataList["obj"]["bool"]["@val"].ToString(); + + HistoryExport hed = new HistoryExport(); + hed.device_number = device_number; + hed.type = devicePoint.Where(x => x.device_building_tag == buildingTag && x.points == point).Select(x => x.full_name).FirstOrDefault(); + hed.deviceName = device.Where(x => x.device_number == device_number).Select(x => x.full_name).FirstOrDefault(); + hed.value = val; + hed.timestamp = Convert.ToDateTime(abstime); + hed.building_tag = buildingTag; + he.Add(hed); + + } + else + { + //讀取資料 + foreach (var obj in dataList["obj"]) + { + + HistoryRawData historyRawData = new HistoryRawData(); + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + string buildingTag = d.DeviceNumber.Split("_")[1]; + //取得時間 + var abstime = obj["abstime"]["@val"].ToString(); + var val = obj["real"] != null ? + obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString(); + + HistoryExport hed = new HistoryExport(); + hed.device_number = device_number; + hed.type = devicePoint.Where(x => x.device_building_tag == buildingTag && x.points == point).Select(x => x.full_name).FirstOrDefault(); + hed.deviceName = device.Where(x => x.device_number == device_number).Select(x => x.full_name).FirstOrDefault(); + hed.value = val; + hed.timestamp = Convert.ToDateTime(abstime); + hed.building_tag = buildingTag; + he.Add(hed); + } + } + } + } + } + } + } + else + { + Logger.LogError("【Device GetWay Error】, device_number: " + d.FullDeviceNumberPoint); + } + } + } + + if (errorPoints.Count() > 0) + { + Logger.LogError("【Device GetWay Error】, device_number: " + errorPoints); + } + + } + + #endregion + } + + + + #endregion + + #region export file progress + #region excel設定 + IFont font12 = workbook.CreateFont(); + font12.FontName = "新細明體"; + font12.FontHeightInPoints = 12; + ICellStyle style12 = workbook.CreateCellStyle(); + style12.SetFont(font12); + style12.Alignment = HorizontalAlignment.Center; + style12.VerticalAlignment = VerticalAlignment.Center; + IFont font12Times = workbook.CreateFont(); + font12Times.FontName = "Times New Roman"; + font12Times.FontHeightInPoints = 12; + IFont font18 = workbook.CreateFont(); + font18.FontName = "新細明體"; + font18.FontHeightInPoints = 18; + font18.IsBold = true; + ICellStyle styleTitle18 = workbook.CreateCellStyle(); + styleTitle18.SetFont(font18); + styleTitle18.Alignment = HorizontalAlignment.Center; + styleTitle18.VerticalAlignment = VerticalAlignment.Center; + ICellStyle styleLeft12 = workbook.CreateCellStyle(); + styleLeft12.SetFont(font12); + styleLeft12.Alignment = HorizontalAlignment.Left; + styleLeft12.VerticalAlignment = VerticalAlignment.Center; + ICellStyle styleLine12 = workbook.CreateCellStyle(); + styleLine12.SetFont(font12); + styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; + styleLine12.VerticalAlignment = VerticalAlignment.Center; + styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; + styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; + styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; + styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; + ICellStyle stylein12 = workbook.CreateCellStyle(); + stylein12.SetFont(font12Times); + stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; + stylein12.VerticalAlignment = VerticalAlignment.Center; + stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; + stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; + stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; + stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; + stylein12.WrapText = true; + #endregion + var data = he.OrderByDescending(x => x.deviceName).ThenBy(x => x.type).ToList(); + if (data.Count > 0) + { + string lastDeviceItem = string.Empty; + string lastDevice = string.Empty; + int RowPosition = 0; + IRow row; + ISheet sheet; + #region set cell + sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == data[0].device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + data[0].deviceName + "_" + data[0].type}"); + row = sheet.CreateRow(RowPosition); + sheet.SetColumnWidth(0, 4 * 160 * 12); + sheet.SetColumnWidth(1, 4 * 160 * 12); + sheet.SetColumnWidth(2, 4 * 160 * 12); + sheet.SetColumnWidth(3, 4 * 160 * 12); + ICell cell = row.CreateCell(0); + cell.SetCellValue("類型"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(1); + cell.SetCellValue("設備名稱"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(2); + cell.SetCellValue("數值"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(3); + cell.SetCellValue("記錄時間"); + cell.CellStyle = styleLine12; + #endregion + + foreach (var d in data) + { + if (RowPosition == 0 && lastDeviceItem == "" && lastDevice == "") + { + lastDeviceItem = d.type; //第一次不用建立 sheet; + lastDevice = d.deviceName; + } + if (d.type != lastDeviceItem || d.deviceName != lastDevice) + { + RowPosition = 0; + lastDeviceItem = d.type; + lastDevice = d.deviceName; + sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == d.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + d.deviceName + "_" + d.type}"); + //sheet = workbook.CreateSheet($"{d.deviceName}{"_" + d.type}"); + #region set cell + row = sheet.CreateRow(RowPosition); + sheet.SetColumnWidth(0, 4 * 160 * 12); + sheet.SetColumnWidth(1, 4 * 160 * 12); + sheet.SetColumnWidth(2, 4 * 160 * 12); + sheet.SetColumnWidth(3, 4 * 160 * 12); + cell = row.CreateCell(0); + cell.SetCellValue("類型"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(1); + cell.SetCellValue("設備名稱"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(2); + cell.SetCellValue("數值"); + cell.CellStyle = styleLine12; + cell = row.CreateCell(3); + cell.SetCellValue("記錄時間"); + cell.CellStyle = styleLine12; + #endregion + RowPosition = 1; + } + else + { + RowPosition += 1; + } + + row = sheet.CreateRow(RowPosition); + for (var i = 0; i < 4; i++) + { + cell = row.CreateCell(i); + if (i == 0) + { + cell.SetCellValue(d.type); + } + if (i == 1) + { + cell.SetCellValue(d.deviceName); + } + if (i == 2) + { + cell.SetCellValue(d.value); + } + if (i == 3) + { + cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm:ss")); + } + + cell.CellStyle = style12; + } + } + } + else + { + apiResult.Code = "0001"; + apiResult.Msg = "選擇的區間沒有資料,無法匯出。"; + return Json(apiResult); + } + #endregion + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + return Json(apiResult); + } + + var ms = new NpoiMemoryStream + { + AllowClose = false + }; + workbook.Write(ms); + ms.Flush(); + ms.Seek(0, SeekOrigin.Begin); + Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); + + return File(ms, "application/vnd.ms-excel", fileName); + } + /// /// 即時趨勢條件過濾條件面板 /// @@ -420,7 +910,7 @@ namespace FrontendWebApi.ApiControllers } } - var devices = dbsub.Where(x => x.main_system_tag == main.Select(m => m.main_system_tag).FirstOrDefault() && x.sub_system_tag == sub.Select(x => x.sub_system_tag).FirstOrDefault() && x.device_number != null).OrderBy(x=>x.device_full_name.Length).ThenBy(x=>x.device_full_name).ToList(); + var devices = dbsub.Where(x => x.main_system_tag == main.Select(m => m.main_system_tag).FirstOrDefault() && x.sub_system_tag == sub.Select(x => x.sub_system_tag).FirstOrDefault() && x.device_number != null).OrderBy(x => x.device_full_name.Length).ThenBy(x => x.device_full_name).ToList(); history_Sub_System.device = devices.Count > 0 ? new List() : null; foreach (var d in devices) { @@ -431,18 +921,18 @@ namespace FrontendWebApi.ApiControllers history_Sub_System.device.Add(device); } - if (history_Sub_System.is_show_history==1) + if (history_Sub_System.is_show_history == 1) { history_Main_System.History_Sub_systems.Add(history_Sub_System); } - + } - apiResult.Data.history_Main_Systems.Add(history_Main_System); + apiResult.Data.history_Main_Systems.Add(history_Main_System); } apiResult.Data.history_Builds = dbbuilding; apiResult.Code = "0000"; - + } catch (Exception exception) @@ -569,12 +1059,714 @@ namespace FrontendWebApi.ApiControllers return Ok(apiResult); } + /// + /// 依據小類過濾條件取得設備列表 + /// + /// + /// + [HttpPost] + [Route("api/History/GetDeviceInfo")] + public async Task>>> GetDeviceInfo([FromBody] History_Sub_system SelectSub) + { + ApiResult> apiResult = new ApiResult>(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + + try + { + List wheres = new List(); + wheres.Add("d.deleted = 0 and is_link = 1"); + + + if (SelectSub.sub_system_tag != null) + { + wheres.Add("d.device_name_tag = @syss"); + } + + var wheres_str = string.Join(" AND ", wheres); + + var Sql = $@"SELECT + b.full_name building_name, + b.building_tag, + a.device_guid, + a.full_name device_name, + a.device_number + from (SELECT * + FROM device d + WHERE {wheres_str}) a + join building b on b.building_tag = a.device_building_tag + join variable v1 on v1.system_value = a.device_system_tag and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' + join variable v2 on v2.system_value = a.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' + order by b.priority,v1.system_priority,v2.system_priority,a.priority,a.device_serial_tag"; + var data = await backendRepository.GetAllAsync(Sql, new { syss = SelectSub.sub_system_tag }); + var groupedData = data.GroupBy(x => x.building_tag); + List historyBuildingDevices = groupedData.Select(group => + new HistoryBuildingDevice + { + building_tag = group.Key, + building_name = group.First().building_name, + device_list = group.Select(item => new HistoryDevice + { + device_guid = item.device_guid, + device_number = item.device_number, + device_name = item.device_name + }).ToList() + }).ToList(); + + apiResult.Data = historyBuildingDevices; + apiResult.Code = "0000"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + /// /// 依據選得的設備,查看所有設備點位 /// /// /// [HttpPost] + [Route("api/History/GetAllDevPoi")] + public async Task>>> GetAllDevPoi([FromBody] PostHistoryDataFilter postDevice) + { + ApiResult> apiResult = new ApiResult>(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + try + { + var dbDevice = await backendRepository.GetAllAsync( + @$"select c.full_name building_name,b.device_number,b.full_name device_name,a.full_name item_name,a.points,a.unit + from device_item a + join device b on a.device_system_tag = b.device_system_tag + and a.device_building_tag COLLATE utf8mb4_unicode_ci = b.device_building_tag + and a.device_name_tag COLLATE utf8mb4_unicode_ci = b.device_name_tag + join building c on c.building_tag = b.device_building_tag + join variable v1 on v1.system_value = b.device_system_tag and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' + join variable v2 on v2.system_value = b.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' + where a.deleted = 0 and b.deleted = 0 and b.is_link = 1 and v2.deleted = 0 and v1.deleted = 0 and is_show_history = 1 and a.is_link = 1 + and b.device_number in @Device_number + GROUP BY points + order by c.priority,b.priority,a.is_bool;" + , new { Device_number = postDevice.Device_list } + ); + apiResult.Data = dbDevice; + apiResult.Code = "0000"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + + + /// + /// 取得歷史資料 + /// + /// + /// + [HttpPost] + [Route("api/History/GetHistoryData")] + public async Task>> GetHistoryData([FromBody] PostHistoryDataFilter post) + { + ApiResult> apiResult = new ApiResult>(jwt_str); + //if (!jwtlife) + //{ + // apiResult.Code = "5000"; + // return BadRequest(apiResult); + //} + //else if (post.Device_list == null || !post.Device_list.Any() || post.Points == null || !post.Points.Any()) + //{ + // apiResult.Code = "0001"; + // apiResult.Msg = "請選擇設備及點位。"; + // return apiResult; + //} + try + { + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + #region 取得obix 設定 + EDFunction ed = new EDFunction(); + var obixApiConfig = new ObixApiConfig(); + var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; + var variable = await frontendRepository.GetAllAsync(sqlObix); + obixApiConfig.ApiBase = variable.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); + obixApiConfig.UserName = ed.AESDecrypt(variable.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault()); + obixApiConfig.Password = ed.AESDecrypt(variable.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault()); + String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password)); + #endregion 取得obix 設定 + + List listDevicePoint = new List(); + List historyRawDatas = new List(); + int pageNumber = post.PageNumber; + int pageSize = 10; + int totalItems = 0; + #region combine device and point + foreach (var Device in post.Device_list) + { + foreach (var point in post.Points) + { + DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint(); + deviceNumberPoint.DeviceNumber = Device; + deviceNumberPoint.Point = point; + deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", Device, point); + + listDevicePoint.Add(deviceNumberPoint); + } + } + #endregion + + //依據被選擇的設備找出相對應資料 + var sqlDeviceItemInfo = $@"select + b.full_name as building_name, + v1.system_key as Main_system_name, + v2.system_key as Sub_system_name, + temp.device_number, + temp.device_name, + temp.full_name as item_name, + temp.points, + temp.device_building_tag, + temp.unit + from ( + select + di.*, + d.device_number, + d.full_name as device_name, + d.priority + from device_item di + inner join device d on di.device_building_tag COLLATE utf8mb4_unicode_ci = d.device_building_tag + and di.device_system_tag COLLATE utf8mb4_unicode_ci = d.device_system_tag + and di.device_name_tag COLLATE utf8mb4_unicode_ci = d.device_name_tag + and d.deleted = 0 + where di.deleted = 0 and d.device_number IN @Device_number + ) temp + inner join building b on temp.device_building_tag COLLATE utf8mb4_unicode_ci = b.building_tag and b.deleted = 0 + inner join variable v1 on temp.device_system_tag COLLATE utf8mb4_unicode_ci = v1.system_value and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' + inner join variable v2 on temp.device_name_tag COLLATE utf8mb4_unicode_ci = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' + order by b.priority, v1.system_priority, v2.system_priority, temp.priority;"; + + var device_item_infos = await frontendRepository.GetAllAsync(sqlDeviceItemInfo, new { Device_number = post.Device_list }); + + if (post.Type == 1) + { + #region Niagara抓資料依據日期 + + //轉換日期格式 + var start = string.Format("{0}T{1}:00.000+08:00", post.Start_date, post.Start_time); + var end = string.Format("{0}T{1}:01.000+08:00", post.End_date, post.End_time); + + var historyQueryFilter = $@" + + + "; + + XmlDocument xmlDocument = new XmlDocument(); + List errorPoints = new List(); //錯誤的設備點位 + if (listDevicePoint.Count > 0) + { + foreach (var d in listDevicePoint) + { + var station = backendRepository.GetOneAsync($@"select parent_path from import_niagara_item_history where device_building_tag = '{d.FullDeviceNumberPoint.Split("_")[1].Replace("$3", "")}' and + device_system_tag = '{d.FullDeviceNumberPoint.Split("_")[2]}' and device_name_tag = '{d.FullDeviceNumberPoint.Split("_")[3]}' + and device_floor_tag = '{d.FullDeviceNumberPoint.Split("_")[4]}' and device_master_tag = '{d.FullDeviceNumberPoint.Split("_")[5]}' + and device_last_name_tag = '{d.FullDeviceNumberPoint.Split("_")[6]}' and device_serial_tag = '{d.FullDeviceNumberPoint.Split("_")[7]}' + and device_point_name = '{d.FullDeviceNumberPoint.Split("_")[8]}'").Result; + + if (!string.IsNullOrEmpty(station)) + { + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyQuery/"); + request.Method = "POST"; + request.Headers.Add("Authorization", "Basic " + encoded); + request.PreAuthenticate = true; + + byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter); + using (Stream reqStream = request.GetRequestStream()) + { + reqStream.Write(byteArray, 0, byteArray.Length); + } + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd(); + + xmlDocument.LoadXml(responseContent); + string responseContentJson = JsonConvert.SerializeXmlNode(xmlDocument); + JObject responseContentJsonResult = (JObject)JsonConvert.DeserializeObject(responseContentJson); + + if (responseContentJsonResult.ContainsKey("err")) //抓取錯誤 + { + errorPoints.Add(d.DeviceNumber); + continue; + } + + + if (responseContentJsonResult.ContainsKey("obj")) //表示可以讀取到內容 + { + var countObj = responseContentJsonResult["obj"]["int"]; + totalItems += Convert.ToInt32(countObj["@val"].ToString()); + if (countObj != null && countObj["@name"].ToString() == "count") + { //判斷是否有資料筆數 + if (Convert.ToInt32(countObj["@val"].ToString()) > 0) + { + var dataList = responseContentJsonResult["obj"]["list"]; + if (dataList != null && dataList["obj"].HasValues) + { + //判斷單筆資料還是多筆 + if (Convert.ToInt32(countObj["@val"].ToString()) == 1) + { + HistoryRawData historyRawData = new HistoryRawData(); + + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + var device_item_info = device_item_infos.Where(x => x.Device_number == device_number && x.Points == point).FirstOrDefault(); + //取得時間 + var abstime = dataList["obj"]["abstime"]["@val"].ToString(); + historyRawData.Timestamp = Convert.ToDateTime(abstime).ToString("yyyy-MM-dd HH:mm:ss"); + //取得資料 + historyRawData.Value = dataList["obj"]["real"] != null ? + dataList["obj"]["real"]["@val"].ToString() : dataList["obj"]["bool"]["@val"].ToString(); + historyRawData.Device_number = device_item_info.Device_number; + historyRawData.Building_name = device_item_info.Building_name; + historyRawData.Device_name = device_item_info.Device_name; + historyRawData.Points = device_item_info.Points; + historyRawDatas.Add(historyRawData); + } + else + { + //讀取資料 + foreach (var obj in dataList["obj"]) + { + HistoryRawData historyRawData = new HistoryRawData(); + + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + var device_item_info = device_item_infos.Where(x => x.Device_number == device_number && x.Points == point).FirstOrDefault(); + //取得時間 + var abstime = obj["abstime"]["@val"].ToString(); + historyRawData.Timestamp = Convert.ToDateTime(abstime).ToString("yyyy-MM-dd HH:mm:ss"); + //取得資料 + historyRawData.Value = obj["real"] != null ? + obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString(); + historyRawData.Device_number = device_item_info.Device_number; + historyRawData.Building_name = device_item_info.Building_name; + historyRawData.Device_name = device_item_info.Device_name; + historyRawData.Points = device_item_info.Points; + historyRawDatas.Add(historyRawData); + } + } + + } + } + } + } + } + else + { + Logger.LogError("【Device GetWay Error】, device_number: " + d.FullDeviceNumberPoint); + } + } + } + + if (errorPoints.Count() > 0) + { + Logger.LogError("【Device GetWay Error】, device_number: " + errorPoints); + } + + #endregion + } + if (post.Type == 2) + { + #region Niagara抓資料依據時間段 + DateTime startday = DateTime.Parse(post.Start_date); + DateTime endtday = DateTime.Parse(post.End_date); + List dateRange = Enumerable.Range(0, (endtday - startday).Days + 1) + .Select(a => startday.AddDays(a)) + .ToList(); + foreach (var day in dateRange) + { + //轉換日期格式 + var start = string.Format("{0}T{1}:00.000+08:00", day.ToString("yyyy-MM-dd"), post.Start_time); + var end = string.Format("{0}T{1}:01.000+08:00", day.ToString("yyyy-MM-dd"), post.End_time); + + var historyQueryFilter = $@" + + + "; + + XmlDocument xmlDocument = new XmlDocument(); + List errorPoints = new List(); //錯誤的設備點位 + if (listDevicePoint.Count > 0) + { + foreach (var d in listDevicePoint) + { + var station = backendRepository.GetOneAsync($@"select parent_path from import_niagara_item_history where device_building_tag = '{d.FullDeviceNumberPoint.Split("_")[1].Replace("$3", "")}' and + device_system_tag = '{d.FullDeviceNumberPoint.Split("_")[2]}' and device_name_tag = '{d.FullDeviceNumberPoint.Split("_")[3]}' + and device_floor_tag = '{d.FullDeviceNumberPoint.Split("_")[4]}' and device_master_tag = '{d.FullDeviceNumberPoint.Split("_")[5]}' + and device_last_name_tag = '{d.FullDeviceNumberPoint.Split("_")[6]}' and device_serial_tag = '{d.FullDeviceNumberPoint.Split("_")[7]}' + and device_point_name = '{d.FullDeviceNumberPoint.Split("_")[8]}'").Result; + + if (!string.IsNullOrEmpty(station)) + { + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyQuery/"); + request.Method = "POST"; + request.Headers.Add("Authorization", "Basic " + encoded); + request.PreAuthenticate = true; + + byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter); + using (Stream reqStream = request.GetRequestStream()) + { + reqStream.Write(byteArray, 0, byteArray.Length); + } + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd(); + + xmlDocument.LoadXml(responseContent); + string responseContentJson = JsonConvert.SerializeXmlNode(xmlDocument); + JObject responseContentJsonResult = (JObject)JsonConvert.DeserializeObject(responseContentJson); + + if (responseContentJsonResult.ContainsKey("err")) //抓取錯誤 + { + errorPoints.Add(d.DeviceNumber); + continue; + } + + + if (responseContentJsonResult.ContainsKey("obj")) //表示可以讀取到內容 + { + var countObj = responseContentJsonResult["obj"]["int"]; + totalItems += Convert.ToInt32(countObj["@val"].ToString()); + if (countObj != null && countObj["@name"].ToString() == "count") + { //判斷是否有資料筆數 + if (Convert.ToInt32(countObj["@val"].ToString()) > 0) + { + var dataList = responseContentJsonResult["obj"]["list"]; + if (dataList != null && dataList["obj"].HasValues) + { + //判斷單筆資料還是多筆 + if (Convert.ToInt32(countObj["@val"].ToString()) == 1) + { + HistoryRawData historyRawData = new HistoryRawData(); + + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + var device_item_info = device_item_infos.Where(x => x.Device_number == device_number && x.Points == point).FirstOrDefault(); + //取得時間 + var abstime = dataList["obj"]["abstime"]["@val"].ToString(); + historyRawData.Timestamp = Convert.ToDateTime(abstime).ToString("yyyy-MM-dd HH:mm:ss"); + //取得資料 + historyRawData.Value = dataList["obj"]["real"] != null ? + dataList["obj"]["real"]["@val"].ToString() : dataList["obj"]["bool"]["@val"].ToString(); + historyRawData.Device_number = device_item_info.Device_number; + historyRawData.Building_name = device_item_info.Building_name; + historyRawData.Device_name = device_item_info.Device_name; + historyRawData.Points = device_item_info.Points; + historyRawDatas.Add(historyRawData); + } + else + { + //讀取資料 + foreach (var obj in dataList["obj"]) + { + HistoryRawData historyRawData = new HistoryRawData(); + + //取得設備基本資訊 + var device_number = d.DeviceNumber; + var point = d.Point; + var device_item_info = device_item_infos.Where(x => x.Device_number == device_number && x.Points == point).FirstOrDefault(); + //取得時間 + var abstime = obj["abstime"]["@val"].ToString(); + historyRawData.Timestamp = Convert.ToDateTime(abstime).ToString("yyyy-MM-dd HH:mm:ss"); + //取得資料 + historyRawData.Value = obj["real"] != null ? + obj["real"]["@val"].ToString() : obj["bool"]["@val"].ToString(); + historyRawData.Device_number = device_item_info.Device_number; + historyRawData.Building_name = device_item_info.Building_name; + historyRawData.Device_name = device_item_info.Device_name; + historyRawData.Points = device_item_info.Points; + historyRawDatas.Add(historyRawData); + } + } + + } + } + } + } + } + else + { + Logger.LogError("【Device GetWay Error】, device_number: " + d.FullDeviceNumberPoint); + } + } + } + + if (errorPoints.Count() > 0) + { + Logger.LogError("【Device GetWay Error】, device_number: " + errorPoints); + } + + } + + #endregion + } + + historyRawDatas.Reverse(); + var pagedDevices = historyRawDatas.Skip((pageNumber - 1) * pageSize).Take(pageSize); + stopwatch.Stop(); + double elapsedTime = stopwatch.Elapsed.TotalSeconds; + var result = new PageResultT + { + Items = historyRawDatas, + PageNumber = pageNumber, + PageSize = pageSize, + TotalItems = totalItems, + ElapsedTime = elapsedTime, + }; + apiResult.Code = "0000"; + apiResult.Data = result; + + return Ok(apiResult); + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.ToString()); + return Ok(apiResult); + } + } + + /// + /// 取得歷史資料常用組合 + /// + /// + /// + [HttpPost] + [Route("api/History/GetHistoryFavorite")] + public async Task>>> GetHistoryFavorite() + { + ApiResult> apiResult = new ApiResult>(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + try + { + var sql = $@"SELECT * from history_favorite WHERE userinfo_guid = @userinfo_guid and deleted = 0"; + var rawDatas = await frontendRepository.GetAllAsync(sql, new { userinfo_guid = myUser.userinfo_guid }); + foreach (var item in rawDatas) + { + var detailSql = $@"SELECT * from history_favorite_detail WHERE favorite_guid = @favorite_guid"; + var detailDatas = await frontendRepository.GetAllAsync(detailSql, new { favorite_guid = item.favorite_guid }); + foreach (var detailData in detailDatas) + { + if (detailData.key == "device") + { + item.device_list.Add(detailData.value); + } + else + { + item.Points.Add(detailData.value); + } + } + } + + apiResult.Data = rawDatas; + apiResult.Code = "0000"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + /// + /// 儲存歷史資料常用組合 + /// + /// + /// + [HttpPost] + [Route("api/History/SaveHistoryFavorite")] + public async Task>>> SaveHistoryFavorite([FromBody] HistoryFavorite post) + { + ApiResult> apiResult = new ApiResult>(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + try + { + //產生一組GUID + var guid = Guid.NewGuid(); //常用組合GUID + + Dictionary combination = new Dictionary(); + combination = new Dictionary() + { + { "@favorite_guid", guid}, + { "@favorite_name", post.favorite_name}, + { "@userinfo_guid", myUser.userinfo_guid}, + { "@device_name_tag", post.device_name_tag}, + { "@type", post.type}, + { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + await frontendRepository.AddOneByCustomTable(combination, "history_favorite"); + + List> detailDics = new List>(); + foreach (var device in post.device_list) + { + Dictionary detailDic = new Dictionary() + { + { "@favorite_guid", guid}, + { "@key", "device"}, + { "@value", device} + }; + + detailDics.Add(detailDic); + } + foreach (var point in post.Points) + { + Dictionary detailDic = new Dictionary() + { + { "@favorite_guid", guid}, + { "@key", "point"}, + { "@value", point} + }; + + detailDics.Add(detailDic); + } + + await frontendRepository.AddMutiByCustomTable(detailDics, "history_favorite_detail"); + + apiResult.Msg = "儲存成功"; + apiResult.Code = "0000"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + /// + /// 修改歷史資料常用組合名稱 + /// + /// + /// + [HttpPost] + [Route("api/History/EditHistoryFavorite")] + public async Task>> EditHistoryFavoriten([FromBody] HistoryFavorite post) + { + ApiResult apiResult = new ApiResult(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + try + { + var sWhere = $@"deleted = 0 AND favorite_guid = @favorite_guid"; + + var Combination = await frontendRepository.GetOneAsync("history_favorite", sWhere, new { favorite_guid = post.favorite_guid }); + + if (Combination == null) + { + apiResult.Code = "9998"; + apiResult.Msg = "查無該組合"; + return Ok(apiResult); + } + else + { + Dictionary CombinationDic = new Dictionary() + { + { "@favorite_name", post.favorite_name }, + { "@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + + await frontendRepository.UpdateOneByCustomTable(CombinationDic, "history_favorite", $@"favorite_guid = '{post.favorite_guid}'"); + + } + apiResult.Msg = "修改成功。"; + apiResult.Code = "0000"; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + /// + /// 刪除歷史資料常用組合名稱 + /// + /// + /// + [HttpPost] + [Route("api/History/DeleteHistoryFavorite")] + public async Task>> DeleteHistoryFavorite([FromBody] HistoryFavorite post) + { + ApiResult apiResult = new ApiResult(jwt_str); + if (!jwtlife) + { + apiResult.Code = "5000"; + return BadRequest(apiResult); + } + try + { + var sWhere = $@"deleted = 0 AND favorite_guid = @favorite_guid"; + + var Combination = await frontendRepository.GetOneAsync("history_favorite", sWhere, new { favorite_guid = post.favorite_guid }); + + if (Combination == null) + { + apiResult.Code = "9998"; + apiResult.Msg = "查無該組合"; + return Ok(apiResult); + } + else + { + await frontendRepository.DeleteOne(post.favorite_guid, "history_favorite", "favorite_guid"); + } + apiResult.Msg = "刪除成功。"; + apiResult.Code = "0000"; + + } + catch (Exception exception) + { + apiResult.Code = "9999"; + apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + return Ok(apiResult); + } + /// + /// 歷史資料依據選得的設備,查看所有設備點位 + /// + /// + /// + [HttpPost] [Route("api/History/LookRealTime")] public async Task>>> LookRealTime(itemlist postDevice) { @@ -1280,7 +2472,7 @@ namespace FrontendWebApi.ApiControllers /// [HttpPost] [Route("api/HistoryRealTime")] - public async Task>>> GetHistoryRealTime (PostHistoryRawDataFilter input) + public async Task>>> GetHistoryRealTime(PostHistoryRawDataFilter input) { ApiResult> apiResult = new ApiResult>(jwt_str); apiResult.Data = new List(); diff --git a/FrontendWebApi/Models/HistoryClass.cs b/FrontendWebApi/Models/HistoryClass.cs index c21b144..4a94438 100644 --- a/FrontendWebApi/Models/HistoryClass.cs +++ b/FrontendWebApi/Models/HistoryClass.cs @@ -263,19 +263,94 @@ namespace FrontendWebApi.Models public string End_timestamp { get; set; } public List HistoryItems { get; set; } } - public class HistoryItem { public string Device_number_point { get; set; } public string Device_number { get; set; } public string Unit { get; set; } } + public class GetHistoryBuildingDevice + { + public string building_tag { get; set; } + public string building_name { get; set; } + public string device_guid { get; set; } + + public string device_number { get; set; } + public string device_name { get; set; } + + } + public class HistoryBuildingDevice + { + public string building_tag { get; set; } + public string building_name { get; set; } + public List device_list { get; set; } + + } + public class HistoryDevice + { + public string device_guid { get; set; } + + public string device_number { get; set; } + public string device_name { get; set; } + } + public class PostHistoryDataFilter + { + public int Type { get; set; } + + public List Building_tag_list { get; set; } + public string Start_date { get; set; } + public string End_date { get; set; } + public string Start_time { get; set; } + public string End_time { get; set; } + public List Device_list { get; set; } + public List Points { get; set; } + public int PageNumber { get; set; } + } + public class PageResultT + { + public IEnumerable Items { get; set; } + public int PageNumber { get; set; } + public int PageSize { get; set; } + public int TotalItems { get; set; } + public int TotalPages => (int)Math.Ceiling((double)TotalItems / PageSize); + public double ElapsedTime { get; set; } + + } + public class HistoryFavorite + { + public string favorite_guid { get; set; } + public int deleted { get; set; } + + public string favorite_name { get; set; } + public string userinfo_guid { get; set; } + + public int type { get; set; } + public string device_name_tag { get; set; } + + public List device_list { get; set; } = new List(); + public List Points { get; set; } = new List(); + + public string created_at { get; set; } + + public string updated_at { get; set; } + + } + public class HistoryFavoriteDetail + { + public string favorite_guid { get; set; } + public string key { get; set; } + + public string value { get; set; } + + } public class DeviceItemInfo { public string Building_name { get; set; } public string Main_system_name { get; set; } public string Sub_system_name { get; set; } + public string Device_building_tag { get; set; } + public string Device_number { get; set; } public string Device_name { get; set; } public string Item_name { get; set; } diff --git a/FrontendWebApi/Models/MyBase.cs b/FrontendWebApi/Models/MyBase.cs index 51def45..13bfd11 100644 --- a/FrontendWebApi/Models/MyBase.cs +++ b/FrontendWebApi/Models/MyBase.cs @@ -52,6 +52,7 @@ namespace FrontendWebApi.Models public string System_type { get; set; } public string System_key { get; set; } public string system_value { get; set; } + public int? system_priority { get; set; } public int? system_parent_id { get; set; } } }