ibms-dome/FrontendWebApi/ApiControllers/WarningValueController.cs

205 lines
8.9 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 FrontendWebApi.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Implement;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Ubiety.Dns.Core;
namespace FrontendWebApi.ApiControllers
{
/// <summary>
/// 告警紀錄
/// </summary>
public class WarningValueController : MyBaseApiController<WarningValueController>
{
private readonly IFrontendRepository frontendRepository;
public WarningValueController
(
IFrontendRepository frontendRepository
)
{
this.frontendRepository = frontendRepository;
}
/// <summary>
/// 取得警戒值
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
[Route("api/WarningValue/GetWarningValue")]
public async Task<ActionResult<ApiResult<List<WarningValueOutput>>>> GetWarningValue()
{
ApiResult<List<WarningValueOutput>> apiResult = new ApiResult<List<WarningValueOutput>>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
List<string> typeNames = Enum.GetNames(typeof(WarningValueType)).ToList();
apiResult.Data = new List<WarningValueOutput>();
var sqlString = $@"SELECT system_value FROM variable WHERE system_type = 'obixConfig' AND system_key = 'ApiBase' AND deleted = 0";
string baseApiUrl = await frontendRepository.GetOneAsync<string>(sqlString);
if (string.IsNullOrEmpty(baseApiUrl))
{
apiResult.Code = "9998";
apiResult.Msg = "未找到 obixConfig baseAPI請聯絡管理者。";
return BadRequest(apiResult);
}
foreach (var typeName in typeNames) {
WarningValueOutput result = new WarningValueOutput();
result.type = Enum.Parse<WarningValueType>(typeName);
sqlString = @$"SELECT system_value FROM variable WHERE system_type = 'warningValueApi' AND system_key = @type AND deleted = 0";
string apiUrl = await frontendRepository.GetOneAsync<string>(sqlString, new { type = $"get{typeName}" });
if (string.IsNullOrEmpty(apiUrl))
{
apiResult.Code = "9998";
apiResult.Msg = "未找到天氣警戒值 obix API請聯絡管理者。";
return BadRequest(apiResult);
}
using (HttpClient client = new HttpClient())
{
apiUrl = Path.Combine(baseApiUrl, "obix/config/", apiUrl);
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = frontendRepository.GetAllAsync<KeyValue>(sqlObix).Result;
string username = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault();
string password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault();
string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
var response = await client.GetAsync(apiUrl);
var resString = (await response.Content.ReadAsStringAsync()).ToString();
XDocument xmlDoc = XDocument.Parse(resString);
if (xmlDoc?.Root?.Name?.LocalName == "str" || xmlDoc?.Root?.Name?.LocalName == "bool")
{
result.targetValue = xmlDoc.Root.Attribute("val").Value;
}
}
apiResult.Data.Add(result);
}
apiResult.Msg = "讀取成功";
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
/// <summary>
/// 設定警戒值
/// </summary>
/// <param name="post"></param>
/// <returns></returns>
[HttpPost]
[Route("api/WarningValue/SetWarningValue")]
public async Task<ActionResult<ApiResult<string>>> SetWarningValue(List<WarningValueInput> wvs)
{
ApiResult<string> apiResult = new ApiResult<string>(jwt_str);
if (!jwtlife)
{
apiResult.Code = "5000";
return BadRequest(apiResult);
}
try
{
var sqlString = $@"SELECT system_value FROM variable WHERE system_type = 'obixConfig' AND system_key = 'ApiBase' AND deleted = 0";
string baseApiUrl = await frontendRepository.GetOneAsync<string>(sqlString);
if (string.IsNullOrEmpty(baseApiUrl))
{
apiResult.Code = "9998";
apiResult.Msg = "未找到 obixConfig baseAPI請聯絡管理者。";
return BadRequest(apiResult);
}
foreach (var wv in wvs) {
string typeName = wv.type.ToString();
sqlString = @$"SELECT system_value FROM variable WHERE system_type = 'warningValueApi' AND system_key = @type AND deleted = 0";
string apiUrl = await frontendRepository.GetOneAsync<string>(sqlString, new { type = $"set{typeName}" });
if (string.IsNullOrEmpty(wv.targetValue)) {
apiResult.Code = "9998";
apiResult.Msg = "請輸入欲設定警戒值";
return BadRequest(apiResult);
}
if (string.IsNullOrEmpty(apiUrl))
{
apiResult.Code = "9998";
apiResult.Msg = "未找到天氣警戒值 obix API請聯絡管理者。";
return BadRequest(apiResult);
}
using (HttpClient client = new HttpClient())
{
apiUrl = Path.Combine(baseApiUrl, "obix/config/", apiUrl);
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = frontendRepository.GetAllAsync<KeyValue>(sqlObix).Result;
string username = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault();
string password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault();
string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
// 建構 XML 數據
string xmlData = @$"<real val='{wv.targetValue}' />";
HttpContent content = new StringContent(xmlData, Encoding.UTF8, "application/xml");
var response = await client.PostAsync(apiUrl, content);
var resString = (await response.Content.ReadAsStringAsync()).ToString();
apiResult.Data = resString;
}
}
apiResult.Msg = "設定成功";
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
}
}