using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SWS.Commons;
using SWS.Model;
using System.Collections;
using System.Runtime.InteropServices.ComTypes;
namespace SWS.Service
{
public class WireGroupService : HttpService
{
public WireGroupService() : base()
{
}
///
/// 获取所有的信号
///
///
///
///
public async Task> GetSignals(string projId, bool Assigned)
{
var res = await this.GetAsync>($"WireGroupApi/GetSignals?projId={projId}&Assigned={Assigned}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 获取当前组可用的编码
///
///
///
public async Task GetNextAvailableSeq(string group)
{
var res = await this.GetAsync($"WireGroupApi/GetNextAvailableSeq?projId={GlobalObject.curProject?.ProjectId}&group={group}");
if (res.code == 200)
{
return res.info;
}
else
{
}
return null;
}
///
/// 验证是否可以保存
///
///
///
public async Task CanSaveSignals(WireGroups entity ,Share.Action ActionType)
{
var res = await this.PostBodyAsync, WireGroups>($"WireGroupApi/CanSaveSignals?projId={GlobalObject.curProject?.ProjectId}&ActionType={ActionType}", entity);
if (res.code == 200)
{
return "OK";
}
else
{
return res.info;
}
}
///
/// 保存
///
///
///
public async Task SaveSignals(WireGroups entity)
{
var res = await this.PostBodyAsync, WireGroups>($"WireGroupApi/SaveSignals?projId={GlobalObject.curProject?.ProjectId}&mode=0", entity);
//if (res.code == 200)
//{
// return res.data;
//}
//else if (res.code ==400)
//{
// return res.info;
//}
return res;
}
///
/// 查询信号信息
///
///
///
public async Task> GetNotification()
{
var res = await this.GetAsync>($"WireGroupApi/GetNotification?projId={GlobalObject.curProject?.ProjectId}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 查询信号历史
///
/// 项目ID
/// 信号ID,多个用都逗号隔开
///
public async Task> GetSignalPropertyhis(string wireGroupIds)
{
var res = await this.GetAsync>($"WireGroupApi/GetSignalPropertyhis?projId={GlobalObject.curProject?.ProjectId}&wireGroupIds={wireGroupIds}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 查询信号日志
///
/// 项目ID
/// 信号ID,多个用都逗号隔开
///
public async Task> GetSignalLogs(string wireGroupIds)
{
var res = await this.GetAsync>($"WireGroupApi/GetSignalLogs?projId={GlobalObject.curProject?.ProjectId}&wireGroupIds={wireGroupIds}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 读信号通知
///
///
///
public async Task> ReadNotification(List NoticeIds)
{
var res = await this.PostBodyAsync,List>($"WireGroupApi/ReadNotification?projId={GlobalObject.curProject?.ProjectId}", NoticeIds);
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 获取全部输出信号的情况
///
///
public async Task> GetGroupInfo()
{
var res = await this.GetAsync>($"WireGroupApi/GetGroupInfo?projId={GlobalObject.curProject?.ProjectId}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
///
/// 下载指定时间范围内的信号历史记录的excel
///
///
///
///
///
public async Task> Exportchanges(DateTime start, DateTime end, bool delete = false)
{
var res = await this.GetAsync>($"WireGroupApi/Exportchanges?projId={GlobalObject.curProject?.ProjectId}&start={start}&end={end}&delete={delete}");
if (res.code == 200)
{
return res.data;
}
else
{
}
return null;
}
public async Task Exportchanges(
string savePath,
DateTime start, DateTime end, bool delete = false,
IProgress progress = null,
CancellationToken cancellationToken = default)
{
try
{
string startValue = start.ToString("yyyy-MM-dd");
string endValue = end.ToString("yyyy-MM-dd");
var p = Path.GetDirectoryName(savePath);
if (!Directory.Exists(p))
Directory.CreateDirectory(p);
string url = $"WireGroupApi/ExportChanges?projectId={GlobalObject.curProject?.ProjectId}&start={startValue}&end={endValue}&delete={delete}";
//url = Uri.EscapeDataString(url);
// 发送请求并获取响应
using (var response = await GlobalObject.client.GetAsync(
url,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken))
{
if (response.StatusCode != HttpStatusCode.OK)
{
string errorMsg = $"服务器地址 [{url}] 文件下载失败, 返回HTTP代码:" + response.StatusCode;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
response.EnsureSuccessStatusCode(); // 确保响应成功
var result = await response.Content.ReadAsStringAsync();
learunHttpRes resultObj = null;
try
{
resultObj = JsonConvert.DeserializeObject>(result);
}
catch (JsonException)
{
//对下载文件来说,如果正常的话,这里反而是合理的,因为返回的就是stream的东西,不能被解析为learunHttpRes
await HandleStreamAsync();
return "";
}
if (resultObj.code != 200)
{
switch (resultObj.code)
{
case 400:
case 500:
return resultObj.info.ToString(); //业务错误,不是http本质错误
default:
string errorMsg = $"服务器地址 [{url}] Get失败, 返回自定义代码:" + resultObj.code;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
}
else
{
await HandleStreamAsync();
return "";
}
async Task HandleStreamAsync()
{
#region core
// 获取文件总大小(可能为 null)
var totalBytes = response.Content.Headers.ContentLength;
// 创建文件流
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(
savePath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 8192,
useAsync: true))
{
var buffer = new byte[8192];
var totalBytesRead = 0L;
var bytesRead = 0;
// 分块读取并写入文件
while ((bytesRead = await contentStream.ReadAsync(
buffer,
0,
buffer.Length,
cancellationToken)) > 0)
{
await fileStream.WriteAsync(
buffer,
0,
bytesRead,
cancellationToken);
totalBytesRead += bytesRead;
// 报告进度(如果有总大小)
if (totalBytes.HasValue)
{
var percent = (double)totalBytesRead / totalBytes.Value * 100;
progress?.Report(percent);
}
}
}
#endregion
}
}
}
catch (HttpRequestException ex)
{
return ex.Message;
//throw new Exception($"下载请求失败: {ex.Message}");
}
catch (TaskCanceledException ex2)
{
return ex2.Message;
// 取消操作时删除已下载的部分文件
//if (File.Exists(savePath)) File.Delete(savePath);
//throw;
}
catch (Exception ex3)
{
return ex3.Message;
//throw new Exception($"下载失败: {ex.Message}");
}
}
}
}