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 { /// /// 顺丰服务 /// [ApiDescriptionSettings("Application", Name = "BookingOrderSF", Order = 20)] public class BookingOrderSFService : IBookingOrderSFService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _rep; private readonly SqlSugarRepository _business; private readonly SqlSugarRepository _detail; private readonly ILogger _logger; private readonly ISysCacheService _cache; public BookingOrderSFService(SqlSugarRepository rep, SqlSugarRepository business, SqlSugarRepository detail, ILogger logger, ISysCacheService cache) { this._logger = logger; this._cache = cache; this._rep = rep; this._business = business; this._detail = detail; } /// /// 分页查询快递主表 /// /// /// [HttpGet("/BookingOrderSF/Page")] public async Task 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>(); 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; } /// /// 保存并返回数据 /// /// [HttpPost("/BookingOrderSF/Save")] public async Task 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(); 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(); 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(); 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(); 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(); dentity.PId = entity.Id; await _detail.InsertAsync(dentity); } } } return Get(entity.Id); } /// /// 删除单据 /// /// /// [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("请上传正确参数"); } } /// /// 获取详情 /// /// /// [HttpPost("/BookingOrderSF/Get")] public async Task Get(long Id) { BookingOrderSFDto ordOut = new BookingOrderSFDto(); var main = await _rep.FirstOrDefaultAsync(u => u.Id == Id); if (main != null) { ordOut = main.Adapt(); 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; } /// /// 发送快递 /// /// /// [HttpPost("/BookingOrderSF/SendBooking")] public async Task 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 cargo = new List(); cargo.Add(new CargoDetailsItem { count = (int)Delivery.KDNum, name = Delivery.GOODSNAME }); List contactList = new List(); 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(); } var dictParam = new Dictionary { { "partnerID", partnerID }, { "serviceCode", "EXP_RECE_CREATE_ORDER"}, { "requestID", requestID}, { "timestamp", timeStamp}, { "accessToken",_cache.Get($"SFToken{UserManager.TENANT_ID}")}, { "msgData", sFSend} }; var strRtn = await url.SetBody(dictParam, "application/x-www-form-urlencoded") .PostAsStringAsync(); _logger.LogInformation("发送快递SendBooking:" + strRtn); var jobj = strRtn.ToJObject(); if (jobj.GetStringValue("apiResultCode") == "A1000") { rt = "下单成功!"; } else { throw Oops.Bah(jobj.GetStringValue("apiErrorMsg")); } return rt; } /// /// 获取顺丰token /// /// [NonAction] public async Task 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();//沙箱校验码 _logger.LogInformation("顺丰partnerID" + partnerID); _logger.LogInformation("顺丰secret" + secret); var dictParam = new Dictionary { { "partnerID",partnerID }, { "grantType", "password"}, { "secret", secret}}; var strRtn = await url.SetBody(dictParam, "application/x-www-form-urlencoded") .PostAsStringAsync(); _logger.LogInformation("顺丰GetToken" + strRtn); 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; } /// /// 订单结果查询接口 /// /// /// [HttpPost("/BookingOrderSF/QueryKDSchedule")] public async Task QueryKDSchedule(long Id) { var rt = String.Empty; var json = new { orderId = Id.ToString() }; long timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds(); //获取url var dict = _cache.GetAllDictData().Result; var url = dict.Where(x => x.Code == "SFQueryKDSchedule").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(); } var dictParam = new Dictionary { { "partnerID", partnerID }, { "serviceCode", "EXP_RECE_SEARCH_ORDER_RESP"}, { "requestID", requestID}, { "timestamp", timeStamp}, { "accessToken",_cache.Get($"SFToken{UserManager.TENANT_ID}")}, { "msgData", json} }; var strRtn = await url.SetBody(dictParam, "application/x-www-form-urlencoded") .PostAsStringAsync(); _logger.LogInformation("查询快递QueryKDSchedule:" + strRtn); var jobj = strRtn.ToJObject(); if (jobj.GetStringValue("apiResultCode") == "A1000") { rt = jobj.GetStringValue("apiResultData").ToJsonString(); } else { throw Oops.Bah(jobj.GetStringValue("apiErrorMsg")); } return rt; } } }