
using Microsoft.AspNetCore.Mvc;
using XYY.Core.Standard.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Service.Standard.Order;
using XYY.Core.Standard.ApiClient;
using Microsoft.Extensions.Logging;
using XYY.Model.Standard.Channel;
using XYY.Model.Standard.MpsOrder;
using XYY.Model.Standard.Order;

namespace XYY.Api.Order.Controllers.MoreThanOneTicketMps
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MpsChanelOrderController : ApiControllerBase
    {
        IMoreThanOneTicketService mpsOrderService;
        IOrderService _orderService;
        XYY.Core.Standard.AliYun.IAliYunPostFileSerivce _aliYunPostFileSerivce;

        ILogger<HttpApiClient> Looger;
        public MpsChanelOrderController(IMoreThanOneTicketService orderService,
            ILogger<HttpApiClient> looger,
            IOrderService OrderService, Core.Standard.AliYun.IAliYunPostFileSerivce aliYunPostFileSerivce)
        {
            this.mpsOrderService = orderService;
            Looger = looger;
            this._orderService = OrderService;
            _aliYunPostFileSerivce = aliYunPostFileSerivce;
        }

        public class tempRequest
        {
            public int[] orderIds { get; set; }
            public int channelId { get; set; }
        }

        public async Task<ApiJsonModel> MergePost(tempRequest tempRequest)
        {
            Order_MpsOrder mps = new Order_MpsOrder();
            mps.Boxs = new List<Order_MpsOrderBox>();
            List<Order_MpsOrder> mpsList = new List<Order_MpsOrder>();
            int weight = 0;
            foreach (var orderId in tempRequest.orderIds)
            {
                var mpsItem = await mpsOrderService.Get(orderId, 0);
                mpsList.Add(mpsItem);
                mps.Boxs.AddRange(mpsItem.Boxs);
                mps.BoxQty += mpsItem.Boxs.Count;
                mps.Weight += mpsItem.Weight;
                mps.ChargedWeight += mpsItem.ChargedWeight;
                var o = await _orderService.Get(orderId);
                weight += o.OPWeight;
            }

            var gqty = mpsList.GroupBy(x => new
            {
                x.ReceiverCountry,
                x.ReceiverCity,
                x.ReceiverState,
                x.ReceiverName,
                x.ReceiverZipCode,
                x.ReceiverStreet1,
                x.ReceiverStreet2,
                x.ReceiverPhone,
                x.ChannelId,
                x.Electric,
                x.Liquid,
                x.DeclarationMethod
            }).Count();
            if (gqty != 1)
            {
                //throw new Exception("当前订单无法合并，请检查国家、州名、城市名、收件人姓名、收件人邮编、收件人地址、收件人电话、下单渠道、是否带电、是否带磁、是否危险品、报关方式完全一致。");
            }
            mps.CustomerOrderNumber = String.Join('_', mpsList.Select(x => x.CustomerOrderNumber));
            mps.OrderId = mpsList.First().OrderId;


            try
            {
                if (mps.Boxs.Any(x => x.BoxOutStatus == XYY.Model.Standard.MpsOrder.BoxOutStatus.Default) || mps.Boxs.All(x => x.BoxOutStatus == XYY.Model.Standard.MpsOrder.BoxOutStatus.Back))
                {
                    throw new Exception("当前订单有未操作完成的箱子或全部退回的箱子，不可发货");
                }
                //增加箱子是否导入确认信息验证
                else if (mps.Boxs.Any(x => !x.ChannelWeight.HasValue || !x.ChannelLength.HasValue
                  || !x.ChannelWidth.HasValue || !x.ChannelHeight.HasValue || x.ChannelWeight <= 0))
                {
                    throw new Exception("当前订单有未导入末端下单信息的箱子，不可发货");
                }
                else
                {
                    if (mps.OrderId == 0)
                        throw new Exception($"订单{mps.TrackingNumber}未找到客户订单Id");
                    var order = await _orderService.Get(mps.OrderId.Value);
                    mps.Boxs = mps.Boxs.Where(x => x.BoxStatus != XYY.Model.Standard.MpsOrder.BoxStatus.Back).ToList();
                    //全部操作完成了，我们根据渠道匹配规则标记订单和草稿订单的相关派送渠道
                    //我们先调用原wms项目的匹配接口，之后再调整
                    HttpApiClient client =
                        new HttpApiClient(HttpApiClientHelper.WMSHost, HttpApiClientHelper.AdminToken, this.Looger);

                    order.CustomerOrderNo = order.SystemNo; //mps.CustomerOrderNumber;//郑曼媛需求：末端下单使用xyy单号

                    order.ChannelId = tempRequest.channelId;
                    order.OPWeight = weight;
                    order.CustomerId = weight;
                    List<Logistics_Channel> channels = null;
                    channels = await client.Post<List<Logistics_Channel>>("/api/BaseInfo/CacheGetAllChannel");




                    var channel = channels.FirstOrDefault(x => x.Id == order.ChannelId);
                    if (channel == null)
                        throw new Exception($"在CacheGetAllChannel中找未到渠道Id{order.ChannelId}的渠道");

                    if (channel.CanMPS)
                    {
                        //是否支持一票多件
                        DataUploadRequest req = new DataUploadRequest
                        {
                            order = order,
                            goods = null,
                            channel = channel,
                            arg = new ExtendArg
                            {
                                AgentIOSS = false,
                                Order = mps
                            }
                        };
                        FbaChannelInfoMiddleware(req.order, req.arg);
                        var result = await _orderService.DataUpload(req.order, null, req.channel, req.arg);
                        order.TrackingNumber = result.TrackingNumber;
                        order.ChannelId = req.channel.Id;
                        var result2 = await _orderService.DrawPdfLabel(result, req.channel, req.order, req.goods);
                        if (result2 != null && result2.Length > 0)
                        {
                            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(Convert.FromBase64String(result2)))
                            {
                                order.ServiceLabelPath = string.Empty;
                                string aliFile = _aliYunPostFileSerivce.PostHttpFile(ms, order.TrackingNumber + ".pdf");
                                order.ServiceLabelUrl = aliFile;

                                //更新箱子信息
                                mps.Boxs.ForEach(x =>
                                {
                                    if (!result.MPSTrackings.ContainsKey(x.BoxServiceNumber))
                                    {
                                        throw new Exception($"保存一票多件下单箱子运单号失败，渠道API未返回箱子{x.BoxServiceNumber}实际运单号");
                                    }
                                    x.BoxTrackingNumber =
                                        result.MPSTrackings[x.BoxServiceNumber];
                                });

                                await mpsOrderService.UpdateBoxNumbser(result.MPSTrackings);
                            }
                        }

                        //更新客户订单的末端订单信息
                        int num = 1;//主要针对NZ 不返回箱号，还合并下单的处理
                        foreach (var mo in mpsList)
                        {
                            Order_Order o = new Order_Order();
                            //查找每箱的单号
                            o.TrackingNumber = !string.IsNullOrEmpty(mo.Boxs.FirstOrDefault().BoxTrackingNumber) ? mo.Boxs.FirstOrDefault().BoxTrackingNumber : result.TrackingNumber + "-" + num.ToString();
                            o.ChannelId = order.ChannelId;
                            o.ServiceLabelPath = order.ServiceLabelPath;
                            o.ServiceLabelUrl = order.ServiceLabelUrl;
                            o.Id = mo.OrderId.Value;
                            await _orderService.UpdateLastInfo(o);
                            num++;
                        }
                        //await _orderService.UpdateLastInfo(order);
                        return ApiJsonModel.OK();

                    }
                    else
                    {
                        throw new Exception("渠道不支持一票多件，暂示实现逻辑");
                    }


                }
            }
            catch (Exception ex)
            {
                await mpsOrderService.UpdateDraftOrderErrorMessage(mps.DraftOrderId, ex.Message);//所有catch 异常信息记录
                throw;
            }
        }

        public async Task<ApiJsonModel> Post(int orderId, int channelId)
        {
            var mps = await mpsOrderService.Get(orderId, 0);
            try
            {
                if (mps.Boxs.Any(x => x.BoxOutStatus == XYY.Model.Standard.MpsOrder.BoxOutStatus.Default) || mps.Boxs.All(x => x.BoxOutStatus == XYY.Model.Standard.MpsOrder.BoxOutStatus.Back))
                {
                    throw new Exception("当前订单有未操作完成的箱子或全部退回的箱子，不可发货");
                }
                //增加箱子是否导入确认信息验证
                else if (mps.Boxs.Any(x => !x.ChannelWeight.HasValue || !x.ChannelLength.HasValue
                    || !x.ChannelWidth.HasValue || !x.ChannelHeight.HasValue || x.ChannelWeight <= 0))
                {
                    throw new Exception("当前订单有未导入末端下单信息的箱子，不可发货");
                }
                else
                {
                    if (mps.OrderId == 0)
                        throw new Exception($"订单{mps.TrackingNumber}未找到客户订单Id");
                    var order = await _orderService.Get(mps.OrderId.Value);
                    mps.Boxs = mps.Boxs.Where(x => x.BoxStatus != XYY.Model.Standard.MpsOrder.BoxStatus.Back).ToList();
                    //全部操作完成了，我们根据渠道匹配规则标记订单和草稿订单的相关派送渠道
                    //我们先调用原wms项目的匹配接口，之后再调整
                    HttpApiClient client =
                        new HttpApiClient(HttpApiClientHelper.WMSHost, HttpApiClientHelper.AdminToken, this.Looger);


                    order.ChannelId = channelId;
                    order.CustomerOrderNo = order.SystemNo; //mps.CustomerOrderNumber;//郑曼媛需求：末端下单使用xyy单号

                    List<Logistics_Channel> channels = null;
                    channels = await client.Post<List<Logistics_Channel>>("/api/BaseInfo/CacheGetAllChannel");




                    var channel = channels.FirstOrDefault(x => x.Id == order.ChannelId);
                    if (channel == null)
                        throw new Exception($"在CacheGetAllChannel中找未到渠道Id{order.ChannelId}的渠道");

                    if (channel.CanMPS)
                    {
                        //是否支持一票多件
                        DataUploadRequest req = new DataUploadRequest
                        {
                            order = order,
                            goods = null,
                            channel = channel,
                            arg = new ExtendArg
                            {
                                AgentIOSS = false,
                                Order = mps
                            }
                        };
                        FbaChannelInfoMiddleware(req.order, req.arg);
                        var result = await _orderService.DataUpload(req.order, null, req.channel, req.arg);
                        order.TrackingNumber = result.TrackingNumber;
                        order.ChannelId = req.channel.Id;
                        var result2 = await _orderService.DrawPdfLabel(result, req.channel, req.order, req.goods);
                        if (result2 != null && result2.Length > 0)
                        {
                            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(Convert.FromBase64String(result2)))
                            {
                                order.ServiceLabelPath = string.Empty;
                                string aliFile = _aliYunPostFileSerivce.PostHttpFile(ms, order.TrackingNumber + ".pdf");
                                order.ServiceLabelUrl = aliFile;

                                //更新箱子信息
                                mps.Boxs.ForEach(x =>
                                {
                                    if (!result.MPSTrackings.ContainsKey(x.BoxServiceNumber))
                                    {
                                        throw new Exception($"保存一票多件下单箱子运单号失败，渠道API未返回箱子{x.BoxServiceNumber}实际运单号");
                                    }
                                    x.BoxTrackingNumber =
                                        result.MPSTrackings[x.BoxServiceNumber];
                                });

                                await mpsOrderService.UpdateBoxNumbser(result.MPSTrackings);
                            }
                        }

                        //更新客户订单的末端订单信息
                        await _orderService.UpdateLastInfo(order);
                        return ApiJsonModel.OK();

                    }
                    else
                    {
                        throw new Exception("渠道不支持一票多件，暂示实现逻辑");
                    }


                }
            }
            catch (Exception ex)
            {
                await mpsOrderService.UpdateDraftOrderErrorMessage(mps.DraftOrderId, ex.Message);//所有catch 异常信息记录
                throw;
            }
        }
        /// <summary>
        /// 修改fba的下单信息
        /// 在DataUpload前调用
        /// </summary>
        /// <param name="order"></param>
        /// <param name="arg"></param>
        private void FbaChannelInfoMiddleware(Order_Order order, ExtendArg arg)
        {
            order.CustomerWeight = order.OPWeight = Convert.ToInt32(arg.Order.Boxs.Sum(x => x.ChannelWeight) * 1000);
            foreach (var item in arg.Order.Boxs)
            {
                item.OpLength = item.ChannelLength ?? 0;
                item.OpWidth = item.ChannelWidth ?? 0;
                item.OpHeight = item.ChannelHeight ?? 0;
                item.OpInputWeight = item.ChannelWeight ?? 0;
            }
        }
    }
}
