using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Info.Entity;
using DS.WMS.Core.Map.Entity;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.EDI;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Sys.Entity;
using Mapster;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Ocsp;
namespace DS.WMS.Core.Op.Method
{
///
/// 海运出口VGM接口
///
public partial class SeaExportService
{
#region VGM及VMG链接
///
/// 获取VGM、VGM SI链接
///
/// 业务Id
///
public async Task> VgmLink(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var bookingId = long.Parse(id);
var order = tenantDb.Queryable().First(x => x.Id == bookingId);
if (order == null)
{
return await Task.FromResult(DataResult.Failed("海运出口信息不存在!", MultiLanguageConst.SeaExportNotExist));
}
var orderUrl = tenantDb.Queryable().First(x => x.BusinessId == bookingId);
if (orderUrl == null)
{
orderUrl = new BookingOrderUrl()
{
BusinessId = bookingId
};
await tenantDb.Insertable(orderUrl).ExecuteCommandAsync();
}
if (!string.IsNullOrEmpty(orderUrl.UrlVgm))
{
return await Task.FromResult(DataResult.Success(new string[] { orderUrl.UrlVgm, orderUrl.UrlVgmSi }));
}
//校验船公司
if (string.IsNullOrEmpty(order.Carrier) || order.CarrierId == 0 || order.CarrierId.IsNull())
{
return await Task.FromResult(DataResult.Failed("船公司未正确填写!"));
}
var ctns = tenantDb.Queryable().Where(x => x.BSNO == id).ToList();
//判断船公司是否支持
//db.Queryable().Where(x => x.TypeId == 1790194688729419776).Select(x => x.Value).ToList();
var allowCarrier = db.Queryable()
.InnerJoin((a, b) => a.TypeId == b.Id).Where((a, b) => b.Code == "vgm_carrier_list").Select((a, b) => a.Value).ToList();
var carrCode = seaComService.GetClientCode(order.CarrierId, tenantDb);
if (!allowCarrier.Contains(carrCode))
return await Task.FromResult(DataResult.Failed("不支持的船公司"));
//船公司网站账号
var carrWebAccMap = db.Queryable()
.InnerJoin((a, b) => a.TypeId == b.Id).Where((a, b) => b.Code == "carrier_web_account_mapping" && a.Name == carrCode)
.Select((a, b) => new { Value = a.Value, Name = a.Name }).First();
//x.CustomerId == order.CarrierId &&
var webacc = seaComService.GetCodeThirdParty(carrWebAccMap.Value, user.UserId, tenantDb);
if (webacc == null)
return await Task.FromResult(DataResult.Failed("船公司VGM网站账号未配置"));
//场站转换
var yardset = tenantDb.Queryable().Where(x => x.Status == StatusEnum.Enable && x.Module == "BookingVgm" && x.LinkId == order.YardId).First();
if (yardset == null)
{
return await Task.FromResult(DataResult.Failed(String.Format("场站EDI配置未找到:{0}", $"{order.Yard}(VGM)")));
}
//校验箱子数据录入
if (ctns.Where(c => string.IsNullOrEmpty(c.CtnAll) || !c.CtnNum.HasValue).Count() > 0)
{
return await Task.FromResult(DataResult.Failed("所有箱型箱量必须录入完整!"));
}
//箱型映射
var ctnMapping = tenantDb.Queryable().Where(x => x.Module == "BookingVgm").ToList();
//if (ctnMapping.Count == 0)
//{
// throw Oops.Bah(BookingErrorCode.BOOK122);
//}
var expCode = ctns.Select(x => x.CtnCode).Distinct().Except(ctnMapping.Select(y => y.Code)).ToList();
if (expCode.Count > 0)
{
return await Task.FromResult(DataResult.Failed(String.Format("箱型EDI配置未找到:{0}", $"{string.Join(',', expCode)}(VGM)")));
}
////接收反馈地址 TODO 0626注释
//var dicUrlVgmResp = db.Queryable().Filter(null, true).Where(x => x.Code == "vgm_si_post_reponse" && x.TenantId == 1288018625843826688).First();
//var dicUrlSiResp = db.Queryable().Filter(null, true).Where(x => x.Code == "si_post_response" && x.TenantId == 1288018625843826688).First();
var userInfo = await db.Queryable().Filter(null, true).FirstAsync(x => x.Id == long.Parse(user.UserId));
var tenant = db.Queryable().Filter(null, true).First(x => x.Id == long.Parse(user.TenantId));
var destinationCode = seaComService.GetPortCode(order.DestinationId, tenantDb);
var loadPortCode = seaComService.GetPortCode(order.LoadPortId, tenantDb);
var dischargePortCode = seaComService.GetPortCode(order.DischargePortId, tenantDb);
//调用vgm链接服务
var postUrl = db.Queryable().Filter(null, true).Where(x => x.Code == "vgm_link_service" && x.TenantId == 1288018625843826688).First().Value;
var postObj = new
{
SystemCode = "djy_hechuan",
billOrderId = order.Id.ToString(),
sendOrderCode = order.MBLNO,
customerName = $"{tenant.Name}+{userInfo.UserName}", //公司名称+用户姓名
customerId = order.CustomerId.ToString(),
agentName = string.IsNullOrEmpty(order.Forwarder) ? tenant.Name : order.Forwarder,
carrierCode = carrCode,
userName = webacc.AppKey,
userPassword = webacc.AppSecret,
depotCode = yardset.MapCode,
depotName = yardset.MapName,
linkName = userInfo.UserName,
linkMobile = userInfo.Phone,
linkEmail = userInfo.Email,
//userId = userInfo.DjyUserId,
userId = order.SaleId,
signatory = userInfo.NickName,
//returnUrl = dicUrlVgmResp?.Value,
shipName = order.Vessel,
voyNo = order.Voyno,
etdstr = order.ETD.HasValue ? order.ETD.Value.ToString("yyyy-MM-dd") : string.Empty,
potrSend = order.LoadPort,
potrGoal = order.DischargePort,
boxinfoStr = order.CntrTotal.Replace("'", ""),
vgmEndTimeStr = order.CloseVgmDate.HasValue ? order.CloseVgmDate.Value.ToString("yyyy-MM-dd") : string.Empty,
returnOkUrl = "",
//SiReturnUrl = dicUrlSiResp?.Value,
DataInfoJson = new
{
order.Shipper,
order.Consignee,
order.NotifyParty,
order.Marks,
order.Description,
order.MBLFrt,
order.Service,
order.IssueType,
order.Transport,
order.TransportCode,
order.Destination,
//order.DestinationId,
destinationCode,
order.KindPkgs,
order.ThirdPayAt,
order.LoadPort,
//order.LoadPortId,
loadPortCode,
order.DischargePort,
//order.DischargePortId
dischargePortCode
}
};
string strPostObj = postObj.ToJsonString();
_logger.Info($"调用VGM链接接口 {postUrl} 传递数据:{strPostObj}");
var result = RequestHelper.Post(strPostObj, postUrl);
_logger.Info($"调用VGM链接接口返回:{result}");
var jobjResp = JObject.Parse(result);
int respCode = jobjResp.GetIntValue("code");
if (respCode != 200)
{
return await Task.FromResult(DataResult.Failed(jobjResp.GetStringValue("message")));
}
//保存url
var memoData = jobjResp.GetJObjectValue("memoData");
orderUrl.UrlVgm = memoData.GetStringValue("vgmUrl");
orderUrl.UrlVgmSi = memoData.GetStringValue("vgmAndSiUrl");
await tenantDb.Updateable(orderUrl).ExecuteCommandAsync();
//货运动态
var bookingStatus = new BookingStatusLog()
{
BusinessId = bookingId,
Status = $"生成VGM链接",
Group = "ship",
OpTime = DateTime.Now,
MBLNO = order.MBLNO
};
await tenantDb.Insertable(bookingStatus).ExecuteCommandAsync();
return await Task.FromResult(DataResult.Success(new string[] { orderUrl.UrlVgm, orderUrl.UrlVgmSi }));
}
///
/// 发送VGM
///
/// 业务Id
///
public async Task> VgmSend(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var bookingId = long.Parse(id);
var order = tenantDb.Queryable().First(x => x.Id == bookingId);
var ctns = tenantDb.Queryable().Where(x => x.BSNO == id).ToList();
//船公司
if (order.CarrierId == 0 || order.CarrierId.ToString().IsNull())
return await Task.FromResult(DataResult.Failed("船公司未正确填写!"));
//提单号不能为空
if (string.IsNullOrEmpty(order.MBLNO))
return await Task.FromResult(DataResult.Failed("主提单号不能为空!"));
var vgmApiSendCarrierIdStr = db.Queryable().Where(x => x.Code == "VgmApiSendCarrierId").First();
//if (config == null)
// return await Task.FromResult(DataResult.Failed("请配置租户的VGM直发船司参数!配置名称:[VgmDirectSendCarrierCode]"));
var arrCarr = vgmApiSendCarrierIdStr.IsNull()
? new string[0] : vgmApiSendCarrierIdStr.Value.Split(",", StringSplitOptions.RemoveEmptyEntries);
var carrCode = seaComService.GetClientCode(order.CarrierId, tenantDb);
// VGM发送方式1:通过API发送
if (arrCarr.Contains(carrCode))
{
if (!carrCode.Equals("MSK", StringComparison.OrdinalIgnoreCase))
{
return await Task.FromResult(DataResult.Failed($"[{carrCode}]船公司暂不支持通过API发送VGM"));
}
var urlConfig = db.Queryable().Filter(null, true).Where(x => x.Code == "VgmSendMskApiUrl" && x.TenantId == 1288018625843826688).First().Value;
var userKey = db.Queryable().Filter(null, true).Where(x => x.Code == "MSKAPIDjyUserKey" && x.TenantId == 1288018625843826688).First().Value;
var userPwd = db.Queryable().Filter(null, true).Where(x => x.Code == "MSKAPIDjyUserSecret" && x.TenantId == 1288018625843826688).First().Value;
var env = db.Queryable().Filter(null, true).Where(x => x.Code == "MSKAPIOPEnvironment" && x.TenantId == 1288018625843826688).First().Value;
if (userKey.IsNull() || userPwd.IsNull() || env.IsNull())
return await Task.FromResult(DataResult.Failed("通过MSKAPI发送VGM所需的Key或Secret或Environment未配置,请联系管理员!"));
if (urlConfig.IsNull())
return await Task.FromResult(DataResult.Failed("通过MSKAPI发送VGM所需的Url未配置,请联系管理员,配置名称:[VgmSendMskApiUrl]"));
var webAccount = seaComService.GetCodeThirdParty("MSKApi", user.UserId, tenantDb);
if (webAccount.IsNull())
return await Task.FromResult(DataResult.Failed("未配置第三方账户,类型:MSKApi"));
var vgmSendMskCustomerCode = db.Queryable().Where(x => x.Code == "VgmSendMskCustomerCode").First().Value;
if (webAccount.IsNull())
return await Task.FromResult(DataResult.Failed("通过MSKAPI发送VGM所需的[客户编号],请联系管理员,配置名称:[VgmSendMskCustomerCode]"));
var userInfo = await db.Queryable().Filter(null, true).FirstAsync(x => x.Id == long.Parse(user.UserId));
var param = new
{
userKey,
userPwd,
operatingEnvironment = env,
mskAppKey = webAccount.AppKey,
mskAppSecret = webAccount.AppSecret,
shipmentNumber = order.MBLNO,
brandCode = "MAEU",
customerCode = vgmSendMskCustomerCode,
terminalCode = "",
containerList = new List