using Admin.NET.Core;
using COSXML.Model.Tag;
using DocumentFormat.OpenXml.Drawing.Diagrams;
using Elastic.Clients.Elasticsearch;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NewLife.Remoting;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Vistar.Application.Const;
using Vistar.Application.Entity;
using Vistar.Application.Service.MaterialManagement.Dto;
using System.Net.Security;
using Org.BouncyCastle.Ocsp;
using System.Net.Http;
using NewLife.Configuration;
using Furion;
using Admin.NET.Core.Service;
using Vistar.Application.Util;
namespace Vistar.Application.Service.MaterialManagement;
///
/// 产品管理服务
///
[ApiDescriptionSettings(ApplicationConst.GroupName, Name = "ProductManagement", Order = 100)]
public class ProductManagementService : IDynamicApiController, ITransient
{
private readonly SqlSugarRepository _obj110Rep;
private readonly SqlSugarRepository _configurationsRep;
private readonly SysConfigService _sysConfigService;
private readonly SqlSugarRepository _configurationDataRep;
public ProductManagementService(
SqlSugarRepository obj110Rep,
SqlSugarRepository configurationsRep,
SysConfigService sysConfigService,
SqlSugarRepository configurationDataRep)
{
_obj110Rep = obj110Rep;
_configurationsRep = configurationsRep;
_sysConfigService = sysConfigService;
_configurationDataRep = configurationDataRep;
}
///
/// 分页查询产品管理
///
///
///
[ApiDescriptionSettings(Name = "page", Description = "分页查询", Order = 1000), HttpPost]
[DisplayName("分页查询产品管理")]
//[Authorize(AuthenticationSchemes = SignatureAuthenticationDefaults.AuthenticationScheme)]
public async Task> Page(PageProductManagementInput input)
{
var query = _obj110Rep.AsQueryable()
.Where(x => x.CheckedStatus == false && x.deleted == false && x.IsLatestVersion == true)
.WhereIF(!string.IsNullOrWhiteSpace(input._System_objNBS), u => u._System_objNBS.Contains(input._System_objNBS.Trim()))
.WhereIF(!string.IsNullOrWhiteSpace(input.fld004484), u => u.fld004484.Contains(input.fld004484.Trim()))
.WhereIF(input.fld004494Range != null && input.fld004494Range.Length == 2, u => u.fld004494 >= input.fld004494Range[0] && u.fld004494 <= input.fld004494Range[1])
.Select();
return await query.ToPagedListAsync(input.Page, input.PageSize);
}
///
/// 获取BOM类型
///
///
[HttpGet]
public async Task> BomType()
{
var BomType = await _configurationsRep.AsQueryable().Where(x => x.ObjectId == 110).ToListAsync();
var BomTypeData = new List();
for (int i = 0; i < BomType.Count; i++)
{
var data = new ProductManagementBomTypeOutput()
{
Id = BomType[i].ConfigID,
Name = BomType[i].ConfigLabel
};
BomTypeData.Add(data);
}
return BomTypeData;
}
///
/// 产品管理-同步到 SAP
///
///
[ApiDescriptionSettings(Name = "syncToSAP"), HttpPost]
[DisplayName("产品管理-同步到 SAP")]
public async Task SyncToSAP(ProductManagementBaseInput input)
{
const string lengthError = "物料编码长度大于40,请检查!";
// 验证物料描述长度
if (input.fld004484.Length > 40)
{
await _obj110Rep.AsUpdateable()
.SetColumns(it => new Obj110
{
fld004629 = DateTime.Now,
fld004312 = "N",
fld004313 = lengthError
})
.Where(it => it.idRecord == input.idRecord)
.ExecuteCommandAsync().ConfigureAwait(false);
return new SapMaterialOutput
{
code = "失败",
msg = lengthError,
result = lengthError
};
}
try
{
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true,
ClientCertificateOptions = ClientCertificateOption.Manual
};
// 使用 HttpClientHandler 创建 HttpClient
using (var httpClient = new HttpClient(httpClientHandler))
{
// 设置基本身份验证信息
var username = await _sysConfigService.GetConfigValueByCode(ConfigConst.SapUserName);
var password = await _sysConfigService.GetConfigValueByCode(ConfigConst.SapPassword);
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
// 定义命名空间
XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
XNamespace urn = "urn:sap-com:document:sap:soap:functions:mc-style";
//获取时间戳精确到毫秒,sap要求每次调用生成不重复guid
string millisecondTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
// 创建 SOAP 请求的 XML 内容
XElement envelope = new XElement(soapenv + "Envelope",
new XElement(soapenv + "Header"),
new XElement(soapenv + "Body",
new XElement(urn + "Zmmfm012",
new XElement("IsReq",
new XElement("Reqkeyid"),
new XElement("Businessid"),
new XElement("Messageid"),
new XElement("Sndprn", "plm"),
new XElement("Rcvprn", "sap"),
new XElement("Requser", "111"),
new XElement("Note1"),
new XElement("Note2"),
new XElement("Note3")
),
new XElement("ItData",
new XElement("item",
new XElement("Zwbid", millisecondTimestamp),
new XElement("Matnr", input._System_objNBS),
new XElement("Mbrsh", input.fld004323),
new XElement("Mtart", input.fld004324),
new XElement("Maktx", input.fld004484),
new XElement("Meins", input.fld004861),
new XElement("Matkl", input.fld004485),
new XElement("Bismt", input.fld004880),
new XElement("Groes", input.fld004879),
new XElement("Normt", input.fld004887),
new XElement("Ferth", input.fld004882),
new XElement("Zeinr", input.fld004881),
new XElement("Mstae", input.fld004699),
new XElement("Raube", input.fld004877),
new XElement("Mhdrz", input.fld004876),
new XElement("Mhdhb", input.fld004895),
new XElement("PlantView",
new XElement("item",
new XElement("Werks", input.fld004325),
new XElement("Beskz", input.fld004490),
new XElement("Sobsl", input.fld004491),
new XElement("Schgt", input.fld004873),
new XElement("Rgekz", input.fld004872),
new XElement("Zbom", input.fld004698)
)
)
)
)
)
)
);
// 将 XML 内容转换为字符串并设置请求内容类型为 text/xml
var content = new StringContent(envelope.ToString(), Encoding.UTF8, "text/xml");
content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
// 设置 SAP Web 服务的 URL
var url = "https://vhjqeds4ci.sap.vistar-eq.com:44300/sap/bc/srt/rfc/sap/zmmfm012/120/zmmfm012/zmmfm012";
// 发起 POST 请求到 SAP Web 服务
var response = await httpClient.PostAsync(url, content);
// 处理响应结果
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
XDocument doc = XDocument.Parse(result);
var item = doc.Descendants("item").FirstOrDefault();
var zwbid = item?.Element("Zwbid")?.Value;
var matnr = item?.Element("Matnr")?.Value;
var code = item?.Element("Code")?.Value;
var msg = item?.Element("Msg")?.Value;
string codeVal = code == "S" ? "成功" : "失败";
await _obj110Rep.AsUpdateable()
.SetColumns(it => new Obj110
{
fld004629 = DateTime.Now,
fld004311 = codeVal,
fld004312 = "N",
fld004313 = msg
})
.Where(it => it.idRecord == input.idRecord)
.ExecuteCommandAsync();
var output = new SapMaterialOutput()
{
code = codeVal,
msg = msg,
result = result
};
return output;
}
else
{
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine("调用失败,状态码: " + response.StatusCode);
var output = new SapMaterialOutput()
{
code = "失败",
msg="",
result = result
};
return output;
}
}
}
catch (Exception ex)
{
// 记录错误日志
Console.WriteLine("发生错误: " + ex.Message);
var output = new SapMaterialOutput()
{
code = "失败",
msg = "发生错误",
result = "发生错误"
};
return output;
}
}
}