using Admin.NET.Core;
using Admin.NET.Core.Service;
using COSXML.Network;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Cms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Vistar.Application.SolidWorksManageService.Dto;
namespace Vistar.Application.SolidWorksManageService;
///
/// SolidWorksManage服务
///
public class SolidWorksManageService : IDynamicApiController, ITransient
{
private static readonly System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
private readonly SysConfigService _sysConfigService;
public SolidWorksManageService(SysConfigService sysConfigService)
{
_sysConfigService = sysConfigService;
}
///
/// 获取 token
///
/// 授权响应对象
[ApiDescriptionSettings(Name = "Authenticate", Description = "获取 token", Order = 1000), HttpGet]
[DisplayName("获取 token")]
[AllowAnonymous]
public async Task Authenticate()
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/Authentication/Authenticate";
var SolidWorksManageUserName = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageUserName);
var SolidWorksManagePassword = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManagePassword);
var SolidWorksManageLicenseId = "190";
var SolidWorksManageApiKey = "zesywsWf1dthwXoqd4DJKasEihcuOArxiImrvu8jOUB7oqryVhFAdydL1nPpC5/0gkhIWm6TdPBolBFx+V/FPgcoG370JXnRp/DZ350wi70=";
// 构建请求参数字典
var parameter = new Dictionary
{
["username"] = SolidWorksManageUserName,
["password"] = SolidWorksManagePassword,
["licenseId"] = SolidWorksManageLicenseId,
["apikey"] = SolidWorksManageApiKey
};
// 将请求参数格式化为 URL 格式的字符串
var formattingParameter = string.Join("&", parameter.Select(kvp => $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}"));
// 构建完整的请求 URL
var requestUrl = $"{url}?{formattingParameter}";
// 使用 using 语句确保 HttpResponseMessage 资源被正确释放
using (var response = await client.PostAsync(requestUrl, null))
{
if (response.IsSuccessStatusCode)
{
// 读取响应内容并反序列化为授权响应对象
string responseBody = await response.Content.ReadAsStringAsync();
AuthorizationResponse jsondata = JsonConvert.DeserializeObject(responseBody);
string value = jsondata.access_token;
await _sysConfigService.UpdateConfigValue(ConfigConst.SolidWorksManageAuthorization, value);
return JsonConvert.DeserializeObject(responseBody);
}
else
{
// 读取响应内容并反序列化为授权响应对象(通常表示请求失败,但这里也尝试反序列化以便进一步处理错误)
string responseBody = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseBody);
}
}
}
///
/// 创建记录
///
///
///
public async Task CreateRecord(CreateRecordInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/PropertyCard/CreateRecord";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 创建项目
///
///
/// Create Project(创建项目)
public async Task CreateProject(CreateProjectInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/PropertyCard/CreateProject";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 检出
///
///
///
public async Task CheckOut(CheckDataInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/PropertyCard/CheckOut";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 检入
///
///
///
public async Task CheckIn(CheckDataInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/PropertyCard/CheckIn";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 创建流程
///
///
///
public async Task CreateProcess(CreateProjectInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/PropertyCard/CreateProcess";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 导出相关文件(全部)
///
///
///
public async Task ExportRelatedFiles(ExportRelatedFilesInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/File/ExportRelatedFiles?object_id=" + input.object_id + "&record_id=" + input.record_id;
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
//// 将参数对象序列化为 JSON 字符串
//string jsonParameters = JsonConvert.SerializeObject(input);
//// 设置请求内容
//var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.GetAsync(url);
var output = new ExportRelatedFilesOutput();
// 处理响应
if (response.IsSuccessStatusCode)
{
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
string fileName;
string fileContentBase64;
// 将字节数据加载到内存流
using (var memoryStream = new MemoryStream(bytes))
using (var zipInputStream = new ZipInputStream(memoryStream))
{
ZipEntry entry;
while ((entry = zipInputStream.GetNextEntry()) != null)
{
fileName = entry.Name;
output.FileName = fileName;
// 读取解压后的文件内容
using (var decompressedStream = new MemoryStream())
{
zipInputStream.CopyTo(decompressedStream);
byte[] fileData = decompressedStream.ToArray();
// 将解压后的文件内容转为 Base64
fileContentBase64 = Convert.ToBase64String(fileData);
output.FileBate = fileContentBase64;
}
}
}
output.State = "成功";
}
else
{
output.State = "失败";
}
return output;
}
///
/// 添加相关文件
///
///
///
public async Task AddRelatedFiles(AddRelatedFilesInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/File/AddRelatedFileToFolder";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
///
/// 保存物料清单
///
///
///
public async Task AddItemsInBom(AddItemsInBomInput input)
{
// 获取 SolidWorksManage 地址
string apiUrl = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageApiUrl);
// 拼接接口地址
string url = $"{apiUrl}/api/BOM/AddItemsInBom";
//获取token
var token = await _sysConfigService.GetConfigValueByCode(ConfigConst.SolidWorksManageAuthorization);
// 将参数对象序列化为 JSON 字符串
string jsonParameters = JsonConvert.SerializeObject(input);
// 设置请求内容
var content = new StringContent(jsonParameters, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Remove("Authorization");
// 添加 Authorization 到请求头
client.DefaultRequestHeaders.Add("Authorization", token);
// 发送 POST 请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
// 解析 JSON 数据
var result = JsonConvert.DeserializeObject(responseBody);
return result;
}
else
{
string responseBody = await response.Content.ReadAsStringAsync();
var errorResponse = new ManageResponse()
{
Success = false,
Message = responseBody,
Data = "",
CustomAction = "",
CustomAttributes = ""
};
return errorResponse;
}
}
}