using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Api.Order.Model.Order;
using XYY.Common.Standard;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Core.Standard.Mvc;
using XYY.Service.Standard.Order;
using XYY.TaskTrack.Standard;
using XYY.Model.Standard.Channel;
using XYY.Service.Standard.ChannelApi.Base;
using Dapper;
using XYY.Authentication.Standard;
using Microsoft.AspNetCore.Authorization;
using XYY.Core.Standard.ExcelHelper.MSExcelHelper;
using XYY.Model.Standard.Dto.order;
using XYY.Service.Standard.ChannelApi.Itdida;
using XYY.Data.Standard.Order;
using XYY.Service.Standard.Channel;
using static XYY.Service.Standard.Finance.Charging.Express.ExpressFeeChargesService;
using XYY.Data.Standard.Channel;
using System.IO;

namespace XYY.Api.Order.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrderController : ApiControllerBase
    {
        private IOrderService _orderService;
        private IMQManager _mQManager;
        private IUnitOfWork _unitOfWork;
        //private FiddlerClient _fiddlerClient;
        private IEnumerable<IBaseApi> _baseApis;
        private IOrderRepository _orderRepository;
        private IChannelService _channelService;
        ICustomerLazyService customerLazyService;
        private IMoreThanOneTicketService _mpsService;
        private IOrderGoodsRepository _orderGoodsRepository;
        private ILogistics_ChannelRepository _ChannelRepository;
        IOrder_OrderPrintQtyRepository _order_OrderPrintQtyRepository;
        Microsoft.Extensions.Caching.Distributed.IDistributedCache _distributed;
        public OrderController(IOrderService orderService, IMQManager mQManager, IUnitOfWork unitOfWork
            //, FiddlerClient fiddlerClient
            , IEnumerable<IBaseApi> baseApis
, IOrderRepository orderRepository, Microsoft.Extensions.Caching.Distributed.IDistributedCache distributed, IChannelService channelService, IMoreThanOneTicketService mpsService, IOrderGoodsRepository orderGoodsRepository, ILogistics_ChannelRepository channelRepository, IOrder_OrderPrintQtyRepository order_OrderPrintQtyRepository, ICustomerLazyService customerLazyService)
        {
            _orderService = orderService;
            _mQManager = mQManager;
            _unitOfWork = unitOfWork;
            //_fiddlerClient = fiddlerClient;
            _baseApis = baseApis;
            _orderRepository = orderRepository;
            _distributed = distributed;
            _channelService = channelService;
            _mpsService = mpsService;
            _orderGoodsRepository = orderGoodsRepository;
            _ChannelRepository = channelRepository;
            _order_OrderPrintQtyRepository = order_OrderPrintQtyRepository;
            this.customerLazyService = customerLazyService;
        }


        public async Task<IActionResult> GetFP(FBRequest request)
        {
            ItdidaApi itdidaApi = new ItdidaApi(_orderRepository, _distributed);
            byte[] data = await itdidaApi.GetFP(request.Channel, request.TrackingNumber);
            string base64 = Convert.ToBase64String(data);
            return Ok(base64);
        }
        public async Task<IActionResult> GetK5FP(FPRequest request)
        {
            Service.Standard.ChannelApi.K5.Api k5 = new Service.Standard.ChannelApi.K5.Api(_order_OrderPrintQtyRepository);
            byte[] data = await k5.GetFP(request.Channel, request.order);
            string base64 = Convert.ToBase64String(data);
            return Ok(base64);
        }

        public async Task<IActionResult> PostManifest()
        {
            var channels = await _channelService.CacheGetAllChannel();
            var pbchannels = channels.Where(x => x.ServiceCode == "PitneyBowes");
            foreach (var channel in pbchannels)
            {
                XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api();
                var result = await api.Manifest(channel);
            }
            return Ok();
        }

        public async Task<IActionResult> GetPBTracking(PBTrackingRequest request)
        {
            XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api();
            var response = await api.GetTracking(request.TrackingNumber, new Logistics_Channel());
            return Ok(response);
        }

        public async Task<IActionResult> ContainerManifest(ContainerManifestRequest request)
        {
            if (request.Details.Count == 0)
                throw new Exception("必须传入明细");
            XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api();
            var result = await api.ContainerManifest(request.BoxNumber, request.Port, request.Channel, request.Details);
            var data = Convert.FromBase64String(result.labelData);
            return File(data, "application/pdf");
        }

        public async Task<IActionResult> GetTracking(TrackingRequest request)
        {
            XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api();
            var result = await api.GetTracking(request.TrackingNumber, request.Channel);
            return Ok(result);
        }

        public class TrackingRequest
        {
            public string TrackingNumber { get; set; }

            public Logistics_Channel? Channel { get; set; }
        }

        public class ContainerManifestRequest
        {
            public string BoxNumber
            {
                get; set;
            }

            public Logistics_Channel? Channel
            {
                get; set;
            }

            public List<string> Details
            {
                get; set;
            }

            public string Port
            {
                get; set;
            }
        }


        public async Task<IActionResult> GetUPSFee([FromBody] DataUploadRequest request)
        {

            var chanel = (await _channelService.CacheGetAllChannel()).Where(x => x.Id == 460).First();
            request.arg = new ExtendArg
            {
                Order = new XYY.Model.Standard.MpsOrder.Order_MpsOrder
                {
                    Boxs = new List<XYY.Model.Standard.MpsOrder.Order_MpsOrderBox>
                    {
                    }
                }
            };
            int vweight = (int)Math.Round(request.order.Width * request.order.Length * request.order.Height / 9.0m, MidpointRounding.AwayFromZero);

            request.order.CustomerWeight = vweight > request.order.CustomerWeight ? vweight : request.order.CustomerWeight;

            request.arg.Order.Boxs.Add(new XYY.Model.Standard.MpsOrder.Order_MpsOrderBox
            {
                OpInputWeight = request.order.CustomerWeight / 1000.0m,
                OpLength = request.order.Length,
                OpHeight = request.order.Height,
                OpWidth = request.order.Width,
                Goods = new List<XYY.Model.Standard.MpsOrder.Order_MpsOrderGoods>
                {
                    new XYY.Model.Standard.MpsOrder.Order_MpsOrderGoods
                    {
                        CnName = "试算",
                        EnName="test",
                        HsCode="000000000",
                        Quantity=1
                    }
                }
            });
            request.order.CustomerId = 698;
            XYY.Service.Standard.ChannelApi.dorje56.Api api = new Service.Standard.ChannelApi.dorje56.Api();
            var price = await api.SS(request.order, request.goods, chanel, request.arg);
            if (!string.IsNullOrEmpty(price.message))
            {
                throw new Exception(price.message);
            }
            bool IsResidential = price.warnings.Any(x => x.message.Contains("Ship To Address Classification is changed from Commercial to Residential"));
            string url = "http://api.smp.xingyunyi.cn/Compute";
            List<SMPCP> cp = new List<SMPCP>();
            cp.Add(new SMPCP
            {
                ZipCode = request.order.ReceiverZipCode,
                City = String.Empty,
                State = String.Empty,
                Stree = String.Empty,
                ComputeDate = DateTime.Now.ToString_yyyyMMdd(),
                CountryCode = request.order.ReceiverCountryCode,
                ExpenseItemId = 224,
                Length = request.order.Length.ToString(),
                Width = request.order.Width.ToString(),
                Height = request.order.Height.ToString(),
                GoodsDeclareValue = 0.ToString(),
                M3 = 0.ToString(),
                Port = "LAX",
                TrackingNumber = String.Empty,
                Weight = (request.order.CustomerWeight).ToString(),
                OrderQty = 1.ToString(),
                IsResidential = IsResidential,
                Zone = ""
            });
            RestSharp.RestClient client = new RestSharp.RestClient(url);

            RestSharp.RestRequest restRequest = new RestSharp.RestRequest(RestSharp.Method.POST);
            restRequest.AddJsonBody(cp.ToArray());
            var response = client.Execute(restRequest);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var model = Newtonsoft.Json.JsonConvert.DeserializeObject<SMPCR>(response.Content);
                if (model.success)
                {
                    var shopFee = model.data.FirstOrDefault(x => x.ExpenseName == "UPS运费");
                    if (shopFee == null)
                        return Error("未返回UPS运费");
                    if (!shopFee.IsSuccess)
                        return Error("运费计算失败:" + shopFee.Message);

                    //原币种结算
                    var fee = new
                    {
                        Fee = model.data.Sum(x => x.AmountinOriginalCurrency),
                        FeeCurrency = model.data.FirstOrDefault().BillCurrency,
                        Weight = Math.Ceiling(request.order.CustomerWeight / 453.59237m),
                        WeightUnit = "磅",
                        FeeDetail = model.data.Where(x => x.IsSuccess && x.AmountinOriginalCurrency > 0)
                        .Select(x => new
                        {
                            x.ExpenseName,
                            x.BillCurrency,
                            Amountin = (decimal)Math.Round(x.AmountinOriginalCurrency, 4, MidpointRounding.AwayFromZero)
                        })
                    };
                    return Ok(fee);
                }
                else
                {
                    return Error(model.message);
                }
            }
            return Ok();
        }


        public async Task<IActionResult> GetUPSAddreeIsResidential([FromBody] DataUploadRequest request)
        {

            //州名处理


            XYY.Service.Standard.ChannelApi.dorje56.Api api = new Service.Standard.ChannelApi.dorje56.Api();
            var price = await api.SS(request.order, request.goods, request.channel, request.arg);
            if (price.success)
            {
                return Ok(price.warnings.Any(x => x.message.Contains("Ship To Address Classification is changed from Commercial to Residential")));
            }
            else
            {
                if (price.message == "无效的产品代码")
                {
                    return Ok(true);
                }
                return Error("获取计费信息失败：" +
                     price.message);
            }
        }

        public async Task<IActionResult> AsyncCustomerLastTrackingNumber()
        {
            var s= await customerLazyService.AsyncLastTrackingNumber();
            return Ok(s);
        }

        public async Task<IActionResult> AsyncCustomerFirstESBTracking()
        {
            var e = await customerLazyService.AsyncFirstESBTracking();
            return Ok(e);
        }
        public async Task<IActionResult> DataUpload([FromBody] DataUploadRequest request)
        {
            return Ok(await _orderService.DataUpload(request.order, request.goods, request.channel, request.arg));
        }
        //        #region Api调试代码
        //        // 测试 DataUpload 接口后续
        //        public async Task<IActionResult> TestDataUpload()
        //        {
        //            DataUploadRequest dataUploadRequest = new DataUploadRequest();
        //            int order_orderId = 208273236;
        //            dataUploadRequest.order = (_unitOfWork.QueryBySqlAsync<Order_Order>($"select *from Order_Order where Id={order_orderId}")).Result.FirstOrDefault();
        //            dataUploadRequest.goods = (_unitOfWork.QueryBySqlAsync<Order_OrderGoods>($"select *from Order_OrderGoods where OrderId={order_orderId}")).Result.ToList();
        //            dataUploadRequest.channel = (_unitOfWork.QueryBySqlAsync<Logistics_Channel>("select *from Logistics_Channel where Id=122")).Result.FirstOrDefault();
        //            dataUploadRequest.arg = new ExtendArg();
        //            UploadResult data1 = new UploadResult();
        //            try
        //            {
        //                data1 = await _orderService.DataUpload(dataUploadRequest.order, dataUploadRequest.goods, dataUploadRequest.channel, dataUploadRequest.arg);
        //            }
        //            catch (Exception ex)
        //            {

        //            }

        //            //测试 DrawPdfLabel 接口后续
        //            var baseApi = _baseApis.Where(x => x.ServiceName == dataUploadRequest.channel.ServiceCode).FirstOrDefault();
        //            try
        //            {
        //                var data2 = baseApi.DrawPdfLabel(data1, dataUploadRequest.channel, dataUploadRequest.order, dataUploadRequest.goods);
        //                return Ok(data2);
        //            }
        //            catch (Exception ex)
        //            {
        //                throw ex;
        //            }

        //        }
        //测试 CannelOrdersByModel 接口后续

        public async Task<IActionResult> TestGetLabel()
        {
            XYY.Service.Standard.ChannelApi.CaiNiao.Api api = new Service.Standard.ChannelApi.CaiNiao.Api(null);
            byte[] data= await api.DrawPdfLabel(new UploadResult { ServiceOrderNumber = "00340434717415996070" },
                _channelService.CacheGetAllChannel().Result.ToList().First(x => x.Id == 537), null, null);
            System.IO.File.WriteAllBytes(@"E:\1.pdf", data);
            return Ok();
        }

        public async Task<IActionResult> TestCannelOrdersByModel()
        {
            List<string> SysmteNos = new List<string>() { "420922529214490328167900000212", "420922529214490328167900000229" };
            string sql = @$"select a.Id Order_OrderId,a.TrackingNumber,a.SystemNo,b.ServiceCode,b.PublicName,b.ApiHost,b.ApiKey,b.ApiSecret,28256 OperationUserId,'{DateTime.Now}' CreateTime,'刘正凯' CreateUserName,'刘正凯' UpdateUserName from Order_Order a
join Logistics_Channel b on b.Id=a.ChannelId
where a.SystemNo in @SystemNo or a.TrackingNumber in @SystemNo or a.TransferNumber in @SystemNo ";//小于三或者等于四，才可以取消
            List<logistics_ChannelCancel> logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync<logistics_ChannelCancel>(sql, null,
                    new { SystemNo = SysmteNos })).ToList();
            foreach (var item in logistics_ChannelCancels)
            {
                try
                {
                    var baseApi = _baseApis.Where(x => x.ServiceName == item.ServiceCode).FirstOrDefault();
                    baseApi.CannelOrdersByModel(item);
                    item.UpdateTime = DateTime.Now;
                }
                catch (Exception ex)
                {
                    item.ResultState = ResultStateEnum.异常.GetValue(); item.ResultMessage = ex.Message;
                    continue;//异常进行下一个,记录以数据表为准
                }
            }
            return Ok();
        }
        //        #endregion
        public async Task<IActionResult> DrawPdfLabel(DrawPdfLabelRequest request)
        {
            return Ok(await _orderService.DrawPdfLabel(request.result, request.channel, request.order, request.goods));
        }

        public async Task<IActionResult> AsyncServiceTrackingNumber(int qty)
        {
            return Ok(await _orderService.AsyncServiceTrackingNumber(qty));
        }

        public class CancenOrderDto
        {
            public List<string> SysmteNos
            {
                get; set;
            }
        }

        public async Task<IActionResult> CancelOrders(CancenOrderDto cancenOrderDto)
        {
            await _orderService.CancelOrders(cancenOrderDto.SysmteNos, new XYY.Model.Standard.Channel.Logistics_Channel { ServiceCode = "WinitISP" });
            return Ok();
        }
        public async Task<IActionResult> CancelOrdersByNoStr(CancenOrderDto cancenOrderDto)
        {
            cancenOrderDto.SysmteNos.RemoveAll(x => string.IsNullOrEmpty(x));
            await _mQManager.Publish<CancelOrderJobMessage>(
                new CancelOrderJobMessage
                {
                    SysmteNos = cancenOrderDto.SysmteNos,
                    UserId = _unitOfWork.CurrentId ?? 0,
                    UserName = _unitOfWork.CurrentName,
                    CreateTime = DateTime.Now
                }, null);
            //await _orderService.CancelOrdersByNoStr(cancenOrderDto.SysmteNos);
            var returnList = await _orderService.GetPackingOrderId(cancenOrderDto.SysmteNos);
            return Ok(returnList);
        }
        public async Task<IActionResult> AddZZEUBOrder(string ladingNumber)
        {
            await _mQManager.Publish(new AddHNJobMessage { LadingNumber = ladingNumber }, null);
            return Ok();
        }

        public async Task<IActionResult> GetZZEUBOrder(string ladingNumber)
        {
            var data = await _orderService.GetZZESBUpdateData(ladingNumber);
            return Ok(data);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="channelId"></param>
        /// <returns></returns>
        [ActionName("ConfimOrders")]
        public async Task<IActionResult> ConfimOrders(int qty = 100)
        {
            List<OrderConfimResult> cq = new List<OrderConfimResult>();
            await _orderService.OrderConfim(qty);
            return Ok();
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ConfimChannelOrders(ConfimChannelOrderParam param)
        {
            List<string> numbers = param.TrackingNumbers;
            string channelServiceCode = param.ChannelServiceCode;
            await _orderService.ConfimChannelOrders(numbers, channelServiceCode);
            return Ok();
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ConfimChannelOrdersByBox(ConfimChannelOrderParamByBox param)
        {
            List<int> boxIds = param.BoxIds;
            await _orderService.ConfimChannelOrdersByBox(boxIds);
            return Ok();
        }

        [ActionName("BagConfim")]
        public async Task<IActionResult> BagConfim()
        {
            await _orderService.BagConfim();
            return Ok();
        }

        [ActionName("BagConfimWithAwb")]
        [HttpGet]
        public async Task<IActionResult> BagConfimWithAwb(string awb)
        {
            await _orderService.BagConfimWithAwb(awb);
            return Ok();
        }

        [ActionName("CannelOrderByNumber")]
        public async Task<IActionResult> CannelOrderByNumber(string systemNo)
        {
            List<string> orders = new List<string> { systemNo };
            await _orderService.CancelOrdersByNoStr(orders);
            return Ok();
        }

        public async Task<IActionResult> TestConfimOrder()
        {
            XYY.Service.Standard.ChannelApi.IMG.Api api = new Service.Standard.ChannelApi.IMG.Api();
            //await api.Confims(new List<string>(), await _ChannelRepository.GetAsync(500));
            return Ok();
        }

        [ActionName("CustomerConfim")]
        public async Task<IActionResult> CustomerConfim(int qty = 100)
        {
            await _orderService.CustomerConfim(qty);
            return Ok();
        }


        /// <summary>
        /// 获取预报日志
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public async Task<IActionResult> GetBagDeclareLogs(QueryModel queryModel)
        {
            var result = await _orderService.GetBagDeclareLogs(queryModel);
            return Ok(result);
        }


        public class BagApiRequset
        {
            public string laddingBillNumber { get; set; }
            public string serviceCode
            {
                get; set;
            }
        }

        [HttpPost]
        /// <summary>
        /// 获取预报日志
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public async Task<IActionResult> GetBagDeclareError(BagApiRequset bagApiRequset)
        {
            var result = await _orderService.GetBagDeclareError(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode);
            return Ok(result);
        }

        [HttpPost]
        public async Task<IActionResult> JTTest()
        {
            var api = new XYY.Service.Standard.ChannelApi.JiTu.Api();
            var obj = new
            {
                customerid = "SJ00021560",
                country = "US"
            };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            var msg = api.Send("9e3e3ff4f1193880f3dc3527c6c68e19", "LangTian", json, "OBTAINTRANSPORT", "https://api.yl-scm.com/yunlu-order-web/baseData/baseDataAction!findTransportList.action");
            return Ok(msg);

        }

        [HttpPost]
        /// <summary>
        /// 提单号重新申报
        /// </summary>
        /// <param name="laddingBillNumber"></param>
        /// <returns></returns>
        public async Task<IActionResult> ReBagDeclare(BagApiRequset bagApiRequset)
        {
            await _orderService.ReBagDeclare(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode);
            return Ok();
        }

        public async Task<IActionResult> UpdateLoadOrder()
        {
            var filelist = (await Request.ReadFormAsync()).Files;
            if (filelist != null && filelist.Count > 0)
            {
                var file = filelist[0];
                await _orderService.THInputOrder(file.OpenReadStream());
                return Ok();
            }
            else
            {
                return Error("请上传一个文件");
            }
        }

        public async Task<IActionResult> ImportPPXFba()
        {
            var filelist = (await Request.ReadFormAsync()).Files;
            if (filelist != null && filelist.Count > 0)
            {
                var file = filelist[0];
                await _orderService.ImportPPXFba(file.OpenReadStream());
                return Ok();
            }
            else
            {
                return Error("请上传一个文件");
            }
        }

        public async Task<IActionResult> QueryOverCancelOrders(QueryModel queryModel)
        {
            return Ok(await _orderService.QueryOverCancelOrders(queryModel));
        }

        [HttpPost]
        public async Task<IActionResult> GetIBBagLabels(GetIBBagLabelParam param)
        {
            List<int> boxIds = param.BoxIds;
            try
            {
                var labelDatas = await _orderService.GetIBBagLabel(boxIds);

                if (labelDatas == null)
                {
                    return Error("获取大包面单失败，无面单数据,请查看记录");
                }
                else if (labelDatas.Any(i => i.Success))
                {
                    var successLabels = labelDatas.Where(i => i.Success).Select(i => i.LabelContent);
                    return Ok(successLabels);
                }
                else
                {
                    string msg = string.Join(",", labelDatas.Select(i => i.Message));
                    return Ok($"获取大包面单全部失败，请查看记录:{msg}");
                }
            }
            catch (Exception ex)
            {
                return Error($"获取大包面单失败:{ex.Message}");
            }
        }

        public async Task<IActionResult> CancelIBBagLabel(CancelIBBagLabelParam param)
        {
            await _orderService.CancelIBBagLabel(param.BoxIds);
            return Ok();
        }
        [HttpPost]
        public async Task<IActionResult> GetOrderPager(QueryModel queryModel)
        {
            var result = await _orderService.GetOrderPager(queryModel);
            return Ok(result);
        }
        [HttpPost]
        public async Task<IActionResult> GetOrderQty(QueryModel qm)
        {
            var u = User.GetUserContent();
            var first = qm.QueryParamer.Where(x => x.Filed == "OrderStatus").FirstOrDefault();
            if (first != null)
            {
                qm.QueryParamer.Remove(first);
            }
            var list = await _orderService.GetOrderQty(qm);
            return Ok(list);
        }
        public async Task<IActionResult> Get(int Id)
        {
            var result = await _orderService.Get(Id);
            return Ok(result);
        }
        public async Task<IActionResult> GetCustomerDraftOrder(int id)
        {
            var order = await _orderService.GetCustomerDraftOrder(id);
            return Ok(order);
        }
        [AllowAnonymous]
        public async Task<IActionResult> OutData(QueryModel queryModel)
        {
            var u = User.GetUserContent();
            var list = await _orderService.GetCustomerOrderList(queryModel);
            var ms = new MSExcelHelper();
            var data = ms.OutDataAsByte<OutDataInfo, CustomerOrder>(list);
            var utc = DateTime.Now.ToFileTimeUtc();
            return File($"{utc}.xlsx", data);
        }
        public class OutDataInfo : MSExcelClassMapping<CustomerOrder>
        {
            public OutDataInfo()
            {
                Map(x => x.CustomerOrderNo).Name("客户单号");
                Map(x => x.TrackingNumber).Name("服务商单号");
                Map(x => x.TransferNumber).Name("行运易单号");
                Map(x => x.ReceiverCountryCode).Name("国家/地区");
                Map(x => x.CreateTime).Name("下单时间");
                Map(x => x.ReceiveTime).Name("称重时间");
                Map(x => x.CustomerWeight).Name("下单重");
                Map(x => x.OPWeight).Name("计费重");
                Map(x => x.CFright).Name("预计费用");
                Map(x => x.ChannelName).Name("产品名称");
                Map(x => x.ReceiverName).Name("收件人");
                Map(x => x.ReceiverState).Name("收件人省份");
                Map(x => x.ReceiverCity).Name("收件人城市");
                Map(x => x.ReceiverStreet).Name("收件人地址");
                Map(x => x.House).Name("收件人门牌号");
                Map(x => x.ReceiverZipCode).Name("收件人邮编");
                Map(x => x.ReceiverPhone).Name("收件人电话");
                Map(x => x.ioss).Name("含IOSS");
                Map(x => x.LatestLogisticsStatus).Name("最新物流状态");
                Map(x => x.LastMessage).Name("最新物流信息");
                Map(x => x.LatestLogisticsTime).Name("最新物流时间");
            }
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> TestMps()
        {
            var mpsOrder = await _mpsService.Get(220222937, 0);
            if (mpsOrder == null)
            {
                return Ok();
            }
            var orders = await _orderRepository.QueryAsync(i => i.CustomerOrderNo == mpsOrder.CustomerOrderNumber);
            var order = orders.FirstOrDefault();
            var orderGoods = await _orderGoodsRepository.QueryAsync(i => i.OrderId == order.Id);

            var channel = await _ChannelRepository.GetAsync(493);


            ExtendArg arg = new ExtendArg { Order = mpsOrder };
            var result = await _orderService.DataUpload(order, orderGoods.ToList(), channel, arg);
            return Ok(result);
        }
    }


}
