using Backend.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.OpenXml4Net.OPC;
using Quartz;
using Repository.BackendRepository.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace BackendWorkerService.Quartz.Jobs
{
///
/// 停車場管理
///
[DisallowConcurrentExecution]
class ParkingJob : IJob
{
private readonly ILogger logger;
private readonly IBackgroundServiceRepository backgroundServiceRepository;
private readonly IBackendRepository backendRepository;
private readonly ILogger loggers;
public ParkingJob(
ILogger logger,
IBackgroundServiceRepository backgroundServiceRepository, ILogger loggers, IBackendRepository backendRepository)
{
this.logger = logger;
this.backgroundServiceRepository = backgroundServiceRepository;
this.backendRepository = backendRepository;
this.loggers = loggers;
}
public async Task Execute(IJobExecutionContext context)
{
Task_Detail task_Detail = new Task_Detail(loggers, backendRepository);
try
{
if(await task_Detail.GetNeedWorkTask("ParkingJob", "All"))
{
await task_Detail.InsertWorkTime("ParkingJob", "All", "任務開始");
EDFunction ed = new EDFunction();
var parkingConfig = new ParkingConfig();
var sqlParking = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'parkingConfig'";
var variable = await backgroundServiceRepository.GetAllAsync(sqlParking);
parkingConfig.Host = variable.Where(x => x.Name == "Host").Select(x => x.Value).FirstOrDefault();
parkingConfig.Prefix = variable.Where(x => x.Name == "Prefix").Select(x => x.Value).FirstOrDefault();
parkingConfig.ApiBase = variable.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault();
parkingConfig.UserName = ed.AESDecrypt(variable.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault());
parkingConfig.Password = ed.AESDecrypt(variable.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault());
parkingConfig.VendorId = variable.Where(x => x.Name == "X-VENDOR-ID").Select(x => x.Value).FirstOrDefault();
parkingConfig.VendorToken = variable.Where(x => x.Name == "X-VENDOR-TOKEN").Select(x => x.Value).FirstOrDefault();
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(parkingConfig.UserName + ":" + parkingConfig.Password));
#region 取得停車場資訊
if (await task_Detail.GetNeedWorkTask("ParkingJob", "Parking"))
{
try
{
await task_Detail.InsertWorkTime("ParkingJob", "Parking", "開始執行停車場剩餘車位Job");
HttpWebRequest spaceRequest = (HttpWebRequest)WebRequest.Create($"{parkingConfig.Host}{parkingConfig.Prefix}/api/space/details");
spaceRequest.Method = "GET";
//request.Headers.Add("Authorization", "Basic " + encoded);
spaceRequest.Headers.Add("X-VENDOR-ID", parkingConfig.VendorId);
spaceRequest.Headers.Add("X-VENDOR-TOKEN", parkingConfig.VendorToken);
spaceRequest.PreAuthenticate = true;
spaceRequest.Timeout = System.Threading.Timeout.Infinite;
spaceRequest.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
//Stopwatch stopWatch = new Stopwatch();
//stopWatch.Start();
HttpWebResponse spaceResponse = (HttpWebResponse)spaceRequest.GetResponse();
var spaceResponseContent = new StreamReader(spaceResponse.GetResponseStream()).ReadToEnd();
//logger.LogInformation("【ParkingJob】【取得成功停車場車位資訊】");
//stopWatch.Stop();
//logger.LogInformation("【ParkingJob】【取得停車場車位資訊】【效能檢驗】[取得資料花費時間]{0} 毫秒", stopWatch.ElapsedMilliseconds);
var spaceResponseResult = JsonConvert.DeserializeObject(spaceResponseContent);
//取得停車場車位對應表
var sqlSapceMapping = $@"SELECT * FROM variable WHERE deleted = 0 AND system_type = 'parkingSapceMapping'";
var parkingSapceMapping = await backgroundServiceRepository.GetAllAsync(sqlSapceMapping);
if (spaceResponseResult != null && spaceResponseResult.Code == "20000")
{
foreach (var area in spaceResponseResult.Payload.Areas)
{
//找出對定的設備代碼
var selectedMapping = parkingSapceMapping.Where(x => x.System_key == area.Name).FirstOrDefault();
if (selectedMapping != null)
{
var tagName = selectedMapping.system_value;
var apiFormat = @"{0}obix/config/Arena/{1}/{2}/{3}/{4}/{5}/CV/set";
var tagNameSplit = tagName.Split("_");
var parames = new List