You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Application/Service/BookingOrderSF/BookingOrderSFService.cs

439 lines
17 KiB
C#

using Myshipping.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq;
using System.Threading.Tasks;
using Myshipping.Application.Entity;
using Microsoft.AspNetCore.Authorization;
using Furion;
using Microsoft.AspNetCore.Http;
using Furion.DataEncryption;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Furion.FriendlyException;
using Furion.Logging;
using System;
using Microsoft.Extensions.Logging;
using System.Reflection;
using System.ComponentModel;
using Myshipping.Application.Service.BookingOrder.Dto;
using Myshipping.Application.ConfigOption;
using System.IO;
using Yitter.IdGenerator;
using Myshipping.Core.Entity;
using Furion.RemoteRequest.Extensions;
using System.Net.Http;
using Myshipping.Core.Service;
using Myshipping.Application.EDI;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;
using Myshipping.Core.Helper;
using Myshipping.Application.Enum;
using Org.BouncyCastle.Asn1.X500;
using System.Drawing.Drawing2D;
using StackExchange.Profiling.Internal;
using Myshipping.Application;
using Myshipping.Application.EDI.PIL;
using Newtonsoft.Json;
using Myshipping.Application.EDI.TSL;
using Myshipping.Application.EDI.WY;
using Myshipping.Application.EDI.YML;
using Myshipping.Application.EDI.YT;
using System.Runtime.InteropServices;
using System.Threading;
using Furion.JsonSerialization;
using System.Xml.Linq;
using Myshipping.Application.Helper;
using System.Net;
using Furion.DistributedIDGenerator;
using System.Linq.Expressions;
using Myshipping.Core.Extension;
using System.Text.RegularExpressions;
using MathNet.Numerics.Distributions;
using Microsoft.IdentityModel.Tokens;
using Myshipping.Application.EDI.ESL;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.HPSF;
using MimeKit;
using NPOI.SS.Formula;
using NPOI.Util;
using System.Collections.Specialized;
using System.Net.Http.Headers;
using MySqlX.XDevAPI.Common;
using Ubiety.Dns.Core;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;
using System.Security.Cryptography;
using Myshipping.Application.Service.DataSync.Dto;
using RabbitMQ.Client;
using System.Configuration;
using System.Collections;
using System.Security.Principal;
using Myshipping.Application.Service.BookingOrderSF.Dto;
namespace Myshipping.Application
{
/// <summary>
/// 顺丰服务
/// </summary>
[ApiDescriptionSettings("Application", Name = "BookingOrderSF", Order = 20)]
public class BookingOrderSFService : IBookingOrderSFService, IDynamicApiController, ITransient
{
private readonly SqlSugarRepository<BookingOrderSFExpressDelivery> _rep;
private readonly SqlSugarRepository<BookingOrderSFExpressdeliveryBusiness> _business;
private readonly SqlSugarRepository<BookingOrderSFExpressdeliveryDetail> _detail;
private readonly ILogger<BookingOrderSFService> _logger;
private readonly ISysCacheService _cache;
public BookingOrderSFService(SqlSugarRepository<BookingOrderSFExpressDelivery> rep, SqlSugarRepository<BookingOrderSFExpressdeliveryBusiness> business,
SqlSugarRepository<BookingOrderSFExpressdeliveryDetail> detail,
ILogger<BookingOrderSFService> logger, ISysCacheService cache)
{
this._logger = logger;
this._cache = cache;
this._rep = rep;
this._business = business;
this._detail = detail;
}
/// <summary>
/// 分页查询快递主表
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpGet("/BookingOrderSF/Page")]
public async Task<dynamic> Page([FromQuery] BookingOrderSFInput input)
{
var entities = await _rep.AsQueryable().Filter(null, true)
.Where(x => x.TenantId == UserManager.TENANT_ID && x.IsDeleted == false)
.WhereIF(!string.IsNullOrWhiteSpace(input.KDNO), u => u.KDNO.Contains(input.KDNO))
.WhereIF(!string.IsNullOrWhiteSpace(input.SJCompany), u => u.KDNO.Contains(input.SJCompany))
.WhereIF(!string.IsNullOrWhiteSpace(input.SJPeople), u => u.KDNO.Contains(input.SJPeople))
.WhereIF(!string.IsNullOrWhiteSpace(input.SJTel), u => u.KDNO.Contains(input.SJTel))
.WhereIF(!string.IsNullOrWhiteSpace(input.FJCompany), u => u.KDNO.Contains(input.FJCompany))
.WhereIF(!string.IsNullOrWhiteSpace(input.FJPeople), u => u.KDNO.Contains(input.FJPeople))
.WhereIF(!string.IsNullOrWhiteSpace(input.FJTel), u => u.KDNO.Contains(input.FJTel))
.WhereIF(!string.IsNullOrWhiteSpace(input.VESSEL), u => u.KDNO.Contains(input.VESSEL))
.WhereIF(!string.IsNullOrWhiteSpace(input.VOYNO), u => u.KDNO.Contains(input.VOYNO))
.WhereIF(!string.IsNullOrWhiteSpace(input.State), u => u.State == input.State)
.WhereIF(input.BDate != null, u => u.Date >= input.BDate)
.WhereIF(input.EDate != null, u => u.Date <= input.EDate)
.OrderBy(PageInputOrder.OrderBuilder(input.SortField, input.DescSort))
.ToPagedListAsync(input.PageNo, input.PageSize);
var list = entities.Adapt<SqlSugarPagedList<BookingOrderSFDto>>();
foreach (var item in list.Items)
{
item.Business = await _business.AsQueryable().Filter(null, true).Where(x => x.PId == item.Id).ToListAsync();
item.detail = await _detail.AsQueryable().Filter(null, true).Where(x => x.PId == item.Id).ToListAsync();
}
return list;
}
/// <summary>
/// 保存并返回数据
/// </summary>
/// <returns></returns>
[HttpPost("/BookingOrderSF/Save")]
public async Task<dynamic> Save(BookingOrderSFDto input)
{
if (string.IsNullOrEmpty(input.KDNO))
{
throw Oops.Bah("快递单号不能为空!");
}
if (string.IsNullOrEmpty(input.SJPeople))
{
throw Oops.Bah("收件人不能为空!");
}
if (string.IsNullOrEmpty(input.SJTel))
{
throw Oops.Bah("收件人电话不能为空!");
}
if (string.IsNullOrEmpty(input.SJAddress))
{
throw Oops.Bah("收件人地址不能为空!");
}
if (string.IsNullOrEmpty(input.FJPeople))
{
throw Oops.Bah("发件人不能为空!");
}
if (string.IsNullOrEmpty(input.FJTel))
{
throw Oops.Bah("发件人电话不能为空!");
}
if (string.IsNullOrEmpty(input.FJAddress))
{
throw Oops.Bah("发件人地址不能为空!");
}
var entity = input.Adapt<BookingOrderSFExpressDelivery>();
if (input.Id == 0)
{
await _rep.InsertAsync(entity);
if (input.Business != null && input.Business.Count > 0)
{
foreach (var item in input.Business)
{
var buentity = item.Adapt<BookingOrderSFExpressdeliveryBusiness>();
buentity.PId = entity.Id;
await _business.InsertAsync(buentity);
}
}
if (input.detail != null && input.detail.Count > 0)
{
foreach (var item in input.detail)
{
var dentity = item.Adapt<BookingOrderSFExpressdeliveryDetail>();
dentity.PId = entity.Id;
await _detail.InsertAsync(dentity);
}
}
}
else
{
await _rep.AsUpdateable(entity).IgnoreColumns(it => new
{
it.TenantId,
it.CreatedTime,
it.CreatedUserId,
it.CreatedUserName
}).ExecuteCommandAsync();
await _business.DeleteAsync(x => x.PId == input.Id);
await _detail.DeleteAsync(x => x.PId == input.Id);
if (input.Business != null && input.Business.Count > 0)
{
foreach (var item in input.Business)
{
var buentity = item.Adapt<BookingOrderSFExpressdeliveryBusiness>();
buentity.PId = entity.Id;
await _business.InsertAsync(buentity);
}
}
if (input.detail != null && input.detail.Count > 0)
{
foreach (var item in input.detail)
{
var dentity = item.Adapt<BookingOrderSFExpressdeliveryDetail>();
dentity.PId = entity.Id;
await _detail.InsertAsync(dentity);
}
}
}
return Get(entity.Id);
}
/// <summary>
/// 删除单据
/// </summary>
/// <param name="Ids"></param>
/// <returns></returns>
[SqlSugarUnitOfWork]
[HttpPost("/BookingOrderSF/Delete")]
public async Task Delete(string Ids)
{
var arr = Ids.Split(",");
if (arr.Count() > 0)
{
foreach (var ar in arr)
{
long Id = Convert.ToInt64(ar);
await _rep.UpdateAsync(x => x.Id == Id, x => new BookingOrderSFExpressDelivery { IsDeleted = true });
await _detail.DeleteAsync(x => x.PId == Id);
await _business.DeleteAsync(x => x.PId == Id);
}
}
else
{
throw Oops.Bah("请上传正确参数");
}
}
/// <summary>
/// 获取详情
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[HttpPost("/BookingOrderSF/Get")]
public async Task<dynamic> Get(long Id)
{
BookingOrderSFDto ordOut = new BookingOrderSFDto();
var main = await _rep.FirstOrDefaultAsync(u => u.Id == Id);
if (main != null)
{
ordOut = main.Adapt<BookingOrderSFDto>();
var detail = await _detail.AsQueryable().Where(x => x.PId == Id).ToListAsync();
ordOut.detail = detail;
var business = await _business.AsQueryable().Where(x => x.PId == Id).ToListAsync();
ordOut.Business = business;
}
return ordOut;
}
/// <summary>
/// 发送快递
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
[HttpPost("/BookingOrderSF/SendBooking")]
public async Task<dynamic> SendBooking(long Id)
{
var rt = String.Empty;
SFSendBooking sFSend = new SFSendBooking();
var Delivery = _rep.FirstOrDefault(x => x.Id == Id);
if (Delivery==null) {
throw Oops.Bah("请选择正确数据!");
}
sFSend.orderId = Id.ToString();
sFSend.language = "zh_CN";
List<CargoDetailsItem> cargo = new List<CargoDetailsItem>();
cargo.Add(new CargoDetailsItem
{
count = (int)Delivery.KDNum,
name = Delivery.GOODSNAME
});
List<ContactInfoListItem> contactList = new List<ContactInfoListItem>();
contactList.Add(new ContactInfoListItem
{
address = $"{Delivery.FJProvince}{Delivery.FJCity}{Delivery.FJAddress}",
contact = Delivery.FJPeople,
contactType = 1,
country = "CN",
postCode = Delivery.FJPostCode,
tel = Delivery.FJTel,
});
contactList.Add(new ContactInfoListItem
{
address = $"{Delivery.SJProvince}{Delivery.SJCity}{Delivery.SJAddress}",
contact = Delivery.SJPeople,
contactType = 2,
country = "CN",
postCode = Delivery.SJPostCode,
tel = Delivery.SJTel,
});
sFSend.contactInfoList = contactList;
sFSend.cargoDetails = cargo;
var json= sFSend.ToJson();
long timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds();
//获取url
var dict = _cache.GetAllDictData().Result;
var url = dict.Where(x => x.Code == "SFSendBooking").Select(x => x.Value).FirstOrDefault();
var partnerID = dict.Where(x => x.Code == "customercode").Select(x => x.Value).FirstOrDefault();//顾客编码:
var requestID = dict.Where(x => x.Code == "CheckCode").Select(x => x.Value).FirstOrDefault();//沙箱校验码
if (!_cache.Exists($"SFToken{UserManager.TENANT_ID}")) {
await GetToken();
}
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("Post"), url))
{
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("partnerID"), partnerID);
multipartContent.Add(new StringContent("serviceCode"), "EXP_RECE_CREATE_ORDER");
multipartContent.Add(new StringContent("requestID"), requestID);
multipartContent.Add(new StringContent("timestamp"), timeStamp.ToString());
multipartContent.Add(new StringContent("accessToken"), _cache.Get($"SFToken{UserManager.TENANT_ID}"));
multipartContent.Add(new StringContent("msgData"), json);
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var strRtn = response.Content.ReadAsStringAsync().Result;
var jobj = strRtn.ToJObject();
if (jobj.GetStringValue("apiResultCode") == "A1000")
{
rt = "下单成功!";
}
else
{
throw Oops.Bah(jobj.GetStringValue("apiErrorMsg"));
}
}
}
}
return rt;
}
/// <summary>
/// 获取顺丰token
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<dynamic> GetToken()
{
var rt = String.Empty;
//获取url
var dict = _cache.GetAllDictData().Result;
var url = dict.Where(x => x.Code == "SFToken").Select(x => x.Value).FirstOrDefault();
var partnerID = dict.Where(x => x.Code == "customercode").Select(x => x.Value).FirstOrDefault();//顾客编码:
var secret = dict.Where(x => x.Code == "CheckCode").Select(x => x.Value).FirstOrDefault();//沙箱校验码
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("Post"), url))
{
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("partnerID"), partnerID);
multipartContent.Add(new StringContent("grantType"), "password");
multipartContent.Add(new StringContent("secret"), secret);
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var strRtn = response.Content.ReadAsStringAsync().Result;
var jobj = strRtn.ToJObject();
if (jobj.GetStringValue("apiResultCode") == "A1000")
{
rt = jobj.GetStringValue("accessToken");
await _cache.SetTimeoutAsync($"SFToken{UserManager.TENANT_ID}", rt, TimeSpan.FromHours(3));
}
else
{
throw Oops.Bah(jobj.GetStringValue("apiErrorMsg"));
}
}
}
}
return rt;
}
}
}