using Microsoft.Extensions.Logging; using NetTaste; using Newtonsoft.Json; using Org.BouncyCastle.Ocsp; using SqlSugar.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using WIDESEA_DTO.Basic; using WIDESEA_IBasicService; using WIDESEA_Model.Models; using WIDESEA_Model.Models.Basic; namespace WIDESEA_BasicService { public class ErpApiService : IErpApiService { private readonly IHttpClientFactory _httpClientFactory; private readonly ISupplierInfoService _supplierInfoService; private readonly IMaterialUnitService _materialUnitService; private readonly IMaterielInfoService _materielInfoService; private readonly ILogger _logger; public ErpApiService(IHttpClientFactory httpClientFactory, ISupplierInfoService supplierInfoService, IMaterialUnitService materialUnitService, IMaterielInfoService materielInfoService, ILogger logger) { _httpClientFactory = httpClientFactory; _supplierInfoService = supplierInfoService; _materialUnitService = materialUnitService; _materielInfoService = materielInfoService; _logger = logger; } /// /// 获取token /// /// public async Task GetTokenAsync() { try { //erp 测试环境 //var request = new TokenRequest { appId = "BG_SYSTEM", secretKey = "7e9239c1e132462a9cf03bfa342a044aMTcxODE5MzgxODI4Mw" }; ////erp 正式环境 var request = new TokenRequest { appId = "BG_SYSTEM", secretKey = "9a3d0b5a37Bfc6dAM4b34ODb8ebDOSb937106d1b19DS29098" }; var response = await PostAsync("auth/getAccessToken", request, includeToken: false); var _token = response?.data?.access_token; return _token ?? ""; } catch (Exception ex) { _logger.LogInformation("ErpApiService GetTokenAsync失败: " + ex.Message); return ""; } } /// /// 获取供应商信息 /// /// /// public async Task GetSuppliersAsync(string vendorCode = null) { try { var req = new SupplierRequest { vendorCode = vendorCode }; var result = await PostAsync("erp/getVendorInfo", req, includeToken: true); if (result != null && result.data != null && result.data.Any()) { var dblists = _supplierInfoService.Repository.QueryData(); var excepts = dblists.Select(O => O.SupplierCode).Except(result.data.Select(o => o.vendorCode)); foreach (var except in excepts) { var first = dblists.FirstOrDefault(o => o.SupplierCode == except); if (first != null) { _supplierInfoService.Repository.DeleteData(first); } } foreach (var item in result.data) { var first = dblists.FirstOrDefault(o => o.SupplierCode == item.vendorCode); if (first != null) { first.SupplierCode = item.vendorCode; first.SupplierName = item.vendorName; first.SupplierShortName = item.vendorShortName; first.Status = item.effective.ObjToInt(); first.CreateDate = item.createDate.ObjToDate(); first.ModifyDate = item.modifyDate.ObjToDate(); _supplierInfoService.Repository.UpdateData(first); } else { Dt_SupplierInfo dt_SupplierInfo = new() { SupplierCode = item.vendorCode, SupplierName = item.vendorName, SupplierShortName = item.vendorShortName, Status = item.effective.ObjToInt(), CreateDate = item.createDate.ObjToDate(), Creater = "ERP", Modifier = "ERP", ModifyDate = item.modifyDate.ObjToDate() }; _supplierInfoService.Repository.AddData(dt_SupplierInfo); } } } } catch (Exception ex) { _logger.LogInformation("ErpApiService GetSuppliersAsync失败: " + ex.Message); } } /// /// 获取物料单位转换 /// /// /// public async Task GetMaterialUnitAsync(string itemNo = null) { try { var req = new MaterialUnitRequest { itemNo = itemNo }; var result = await PostAsync("erp/getMaterialUnit", req, true); if (result != null && result.data != null && result.data.Any()) { var dblists = _materialUnitService.Repository.QueryData(); var excepts = dblists.Select(O => O.ItemNo).Except(result.data.Select(o => o.itemNo)); foreach (var except in excepts) { var first = dblists.FirstOrDefault(o => o.ItemNo == except); if (first != null) { _materialUnitService.Repository.DeleteData(first); } } foreach (var item in result.data) { var first = dblists.FirstOrDefault(o => o.ItemNo == item.itemNo); if (first != null) { first.ItemNo = item.itemNo; first.ProductName = item.productName; first.FromUom = item.fromUom; first.ToUom = item.toUom; first.Ratio = item.ratio.ObjToDecimal(); first.Creater = "ERP"; first.Modifier = "ERP"; first.CreateDate = item.createDate.ObjToDate(); first.ModifyDate = item.modifyDate.ObjToDate(); _materialUnitService.Repository.UpdateData(first); } else { Dt_MaterialUnit dt_MaterialUnit = new() { ItemNo = item.itemNo, ProductName = item.productName, FromUom = item.fromUom, ToUom = item.toUom, Ratio = item.ratio.ObjToDecimal(), CreateDate = item.createDate.ObjToDate(), Creater = "ERP", Modifier = "ERP", ModifyDate = item.modifyDate.ObjToDate() }; _materialUnitService.Repository.AddData(dt_MaterialUnit); } } } } catch (Exception ex) { _logger.LogInformation("ErpApiService GetMaterialUnitAsync 失败: " + ex.Message); } } public async Task GetMaterialInfoAsync(MaterialRequest materialRequest) { try { var first = WIDESEA_Core.Helper.AppSettings.GetValue("FirstMaterialSync").ObjToBool(); if (first) { var _token = await GetTokenAsync(); for (int i = 1; i < 400; i++) { materialRequest.pageNum = i; materialRequest.pageSize = 5000; var result = await PostAsync("erp/getMaterialInfo", materialRequest, _token, true); if (result != null && result.data != null && result.data.Any()) { foreach (var item in result.data) { Dt_MaterielInfo dt_MaterielInfo = new Dt_MaterielInfo() { MaterielModel = item.productModel, MaterielCode = item.itemNo, MaterielName = item.productName, MaterielSpec = item.spec, productTypeDesc = item.productTypeDesc, productFamilyName = item.productFamilyName, productFamilyShortName = item.productFamilyShortName, plcode = item.plcode, pl = item.pl, drawingNo = item.drawingNo, mversion = item.mversion, warehouseName = item.warehouseName, usageUOM = item.usageUOM, purchaseUOM = item.purchaseUOM, inventoryUOM = item.inventoryUOM, CreateDate = item.createDate.ObjToDate(), ModifyDate = item.modifyDate.ObjToDate(), }; _materielInfoService.Repository.AddData(dt_MaterielInfo); } } } } else { //materialRequest.modifyDateStart = DateTime.Now.AddDays(-1).Date.ToString("yyyy-MM-dd") + " 00:00:01"; //materialRequest.modifyDateEnd = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + ":01"; //materialRequest.pageNum = 1; //materialRequest.pageSize = 5000; var result = await PostAsync("erp/getMaterialInfo", materialRequest, true, true); if (result != null && result.data != null && result.data.Any()) { foreach (var item in result.data) { var dbfirst = _materielInfoService.Repository.QueryData(x => x.MaterielModel == item.productModel && x.MaterielCode == item.itemNo).FirstOrDefault(); if (dbfirst != null) { dbfirst.MaterielModel = item.productModel; dbfirst.MaterielCode = item.itemNo; dbfirst.MaterielName = item.productName; dbfirst.MaterielSpec = item.spec; dbfirst.productTypeDesc = item.productTypeDesc; dbfirst.productFamilyName = item.productFamilyName; dbfirst.productFamilyShortName = item.productFamilyShortName; dbfirst.plcode = item.plcode; dbfirst.pl = item.pl; dbfirst.drawingNo = item.drawingNo; dbfirst.mversion = item.mversion; dbfirst.warehouseName = item.warehouseName; dbfirst.usageUOM = item.usageUOM; dbfirst.purchaseUOM = item.purchaseUOM; dbfirst.inventoryUOM = item.inventoryUOM; dbfirst.CreateDate = item.createDate.ObjToDate(); dbfirst.ModifyDate = item.modifyDate.ObjToDate(); _materielInfoService.Repository.UpdateData(dbfirst); } else { Dt_MaterielInfo dt_MaterielInfo = new Dt_MaterielInfo() { MaterielModel = item.productModel, MaterielCode = item.itemNo, MaterielName = item.productName, MaterielSpec = item.spec, productTypeDesc = item.productTypeDesc, productFamilyName = item.productFamilyName, productFamilyShortName = item.productFamilyShortName, plcode = item.plcode, pl = item.pl, drawingNo = item.drawingNo, mversion = item.mversion, warehouseName = item.warehouseName, usageUOM = item.usageUOM, purchaseUOM = item.purchaseUOM, inventoryUOM = item.inventoryUOM, CreateDate = item.createDate.ObjToDate(), ModifyDate = item.modifyDate.ObjToDate(), }; _materielInfoService.Repository.AddData(dt_MaterielInfo); } } } } } catch (Exception ex) { _logger.LogInformation("ErpApiService GetMaterialInfoAsync 失败: " + ex.Message); } } private async Task PostAsync(string url, TRequest request, string _token, bool isNullSerialize = false) { var json = ""; if (isNullSerialize) { json = JsonConvert.SerializeObject(request, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); } else { json = JsonConvert.SerializeObject(request); } var content = new StringContent(json, Encoding.UTF8, "application/json"); var _client = _httpClientFactory.CreateClient("ERPUrl"); _client.DefaultRequestHeaders.Clear(); string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string base64Header = Convert.ToBase64String(Encoding.UTF8.GetBytes(timestamp)); _client.DefaultRequestHeaders.Add("X-Custom-Header", base64Header); _client.DefaultRequestHeaders.Add("ACCESS-TOKEN", _token); _client.DefaultRequestHeaders.Add("Accept", "application/json"); using var response = await _client.PostAsync(url, content); string body = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new HttpRequestException(body); } return JsonConvert.DeserializeObject(body); } private async Task PostAsync(string url, TRequest request, bool includeToken = true, bool isNullSerialize = false) { var json = ""; if (isNullSerialize) { json = JsonConvert.SerializeObject(request, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); } else { json = JsonConvert.SerializeObject(request); } var content = new StringContent(json, Encoding.UTF8, "application/json"); var _client = _httpClientFactory.CreateClient("ERPUrl"); _client.DefaultRequestHeaders.Clear(); string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string base64Header = Convert.ToBase64String(Encoding.UTF8.GetBytes(timestamp)); _client.DefaultRequestHeaders.Add("X-Custom-Header", base64Header); if (includeToken) { var _token = await GetTokenAsync(); _client.DefaultRequestHeaders.Add("ACCESS-TOKEN", _token); } _client.DefaultRequestHeaders.Add("Accept", "application/json"); using var response = await _client.PostAsync(url, content); string body = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new HttpRequestException(body); } return JsonConvert.DeserializeObject(body); } } }