// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PurchaseOrderService.svc.cs" company="BEL USA">
//   This product is property of BEL USA.
// </copyright>
// <summary>
//   Defines the PurchaseOrderService type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace bel.promostandards.wcf.api.Services
{
    using AutoMapper;
    using bel.promostandards.api.domain.PurchaseOrder;
    using bel.promostandards.business.Exceptions;
    using bel.promostandards.business.Helpers;
    using bel.promostandards.credentials.Settings;
    using bel.promostandards.data.domain.Entities.PurchaseOrder;
    using bel.promostandards.data.domain.Entities.PurchaseOrder.CustomDesignConverter;
    using bel.promostandards.data.domain.Entities.Security;    
    using bel.promostandards.datalayer.dapper.Service;
    using bel.promostandards.interfaces.Data;
    using bel.promostandards.interfaces.Infrastructure;    
    using bel.promostandards.wcf.api.Helpers;
    using MySqlX.XDevAPI.Common;
    using Newtonsoft.Json;
    using NLog;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Channels;
    using System.Threading.Tasks;

    /// <summary>
    /// The order status service.
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PurchaseOrderService : IPurchaseOrderService
    {
        /// <summary>
        /// The order status service.
        /// </summary>
        private readonly interfaces.Services.IPurchaseOrderService purchaseOrderService;

        /// <summary>
        /// The mapper.
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// The logger.
        /// </summary>
        private readonly Logger logger = LogManager.GetLogger("PurchaseOrder_Service");//LogManager.GetCurrentClassLogger();


        private readonly IAWSCredentialDataService credentialsDataService;


        private readonly IDbSettings dbSettings;



        /// <summary>
        /// Initializes a new instance of the <see cref="PurchaseOrderService"/> class.
        /// </summary>
        /// <param name="purchaseOrderService">
        /// The order status service.
        /// </param>
        /// <param name="mapper">
        /// The mapper.
        /// </param>
        public PurchaseOrderService(interfaces.Services.IPurchaseOrderService purchaseOrderService, IMapper mapper, IDbSettings _dbSettings, 
            IAWSCredentialDataService _credentialsDataService)
        {
            this.purchaseOrderService = purchaseOrderService;
            this.mapper = mapper;
            this.dbSettings = _dbSettings;
            credentialsDataService = _credentialsDataService;
        }

        /// <summary>
        /// The get supported order types async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task<GetSupportedOrderTypesResponse> GetSupportedOrderTypesAsync(GetSupportedOrderTypesRequest request)
        {
            var address = OperationContext.Current
                .IncomingMessageProperties[RemoteEndpointMessageProperty.Name] is RemoteEndpointMessageProperty msg ? msg.Address : "0.0.0.0";

            var response = new GetSupportedOrderTypesResponse();
            
            try
            {
                PreCheckSupportedOrderType(request, false);
                var credentials = new Credentials { CustomerId = request.Id, Password = request.Password };
                List<OrderTypes> result = await this.purchaseOrderService.GetSupportedOrderTypesAsync(credentials);
                
                response.SupportedOrderTypes = result.Select(
                                                 src => new SupportedOrderTypes
                                                 {
                                                     TypeName = src.TypeName,
                                                     TypeId = src.TypeId
                                                 }).ToArray();
            }
            catch (CredentialsException credentialsException)
            {
                response.ServiceMessageArray = new[] {
                      new ServiceMessage
                          {
                              Code = (int)credentialsException.Code,
                              Description = credentialsException.CustomMessage,
                              Severity = SeverityTypeEnum.Error
                          }
                  };
                logger.Error($"GetSupportedOrderTypesError: Id: {request.Id} response: Error Code {credentialsException.Code} Error Message {credentialsException.CustomMessage}");
            }
            catch (GeneralException credentialsException)
            {
                response.ServiceMessageArray = new[] {

                      new ServiceMessage
                          {
                              Code =
                                  (int)
                                  credentialsException
                                      .Code,
                              Description =
                                  credentialsException
                                      .Message,
                              Severity =
                                  SeverityTypeEnum.Error
                          }
                  };
                logger.Error($"GetSupportedOrderTypesError: Id: {request.Id} response: Error Code {credentialsException.Code} Error Message {credentialsException.Message}");
            }
            catch (Exception exception)
            {
                response.ServiceMessageArray = new[] {
                      new ServiceMessage
                          {
                              Code = 999,
                              Description = exception.Message,
                              Severity = SeverityTypeEnum.Error
                          }
                  };
                logger.Error($"GetSupportedOrderTypesError: Id: {request.Id} response: Error Code 999 Error Message {exception.Message}");
            }

            return response;
        }

        /// <summary>
        /// The send po async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>1
        public async Task<SendPOResponse> SendPOAsync(SendPORequest request)
        {          
            var address = OperationContext.Current
                .IncomingMessageProperties[RemoteEndpointMessageProperty.Name] is RemoteEndpointMessageProperty msg ? msg.Address : "0.0.0.0";

            var response = new SendPOResponse();


            logger.Info($"SendPORequest: Id: {request.Id} PO: {request.PO.OrderNumber} Ip: {address}");

            try
            {
                var credentials = new Credentials { CustomerId = request.Id, Password = request.Password };

                AWSCredentialHelper credentialsHelper = new AWSCredentialHelper(credentialsDataService);
                var vendorId = credentialsHelper.ValidateCredentials(credentials, PromoStandardServiceEnum.PurchaseOrder);

                var purchaseOrderObject = await ConvertPurchaseOrderTypeToPurchaseOrderObject(request.PO, vendorId, credentials);

                var result = await purchaseOrderService.SendPurchaseOrder(credentials, new OrderHeaderObject() { OrderHeader = purchaseOrderObject.OrderHeader }, new OrderDetailsObject() { OrderDetails = purchaseOrderObject.OrderDetails });
                                
                response.TransactionId = result.Item1.ToString();                

                if (result.Item1 <= 0)
                {                    
                    throw new Exception(result.Item2);
                }
                else
                {                    
                    try
                    {
                        var orderId = Convert.ToInt32(result.Item1);
                        var cbizInventory = new CbizInventory();
                        var resultGP = await cbizInventory.prod_cbiz_inventory_syncAsync(orderId.ToString());                        
                    }
                    catch (Exception exception)
                    {
                        logger.Error($"GP Error: {JsonConvert.SerializeObject(exception)}");
                    }                    
                }

                logger.Info($"SendPOResponse: Id: {request.Id} TransactionId: {response.TransactionId}");
            }
            catch (CredentialsException credentialsException)
            {
                response.ServiceMessageArray = new ServiceMessageArray
                {
                    ServiceMsg = new List<ServiceMessage>
                    {
                        new ServiceMessage{
                            Code = (int)credentialsException.Code,
                            Description = credentialsException.CustomMessage,
                            Severity = SeverityTypeEnum.Error
                        }
                    }
                    
                };
                logger.Error($"SendPOError: Id: {request.Id} response: Error Code {credentialsException.Code} Error Message {credentialsException.CustomMessage}");
            }
            catch (GeneralException credentialsException)
            {
               response.ServiceMessageArray = new ServiceMessageArray
                {
                    ServiceMsg = new List<ServiceMessage>
                    {
                        new ServiceMessage{
                            Code = (int)credentialsException.Code,
                            Description = credentialsException.Message,
                            Severity = SeverityTypeEnum.Error
                        }
                    }
                    
                };
                logger.Error($"SendPOError: Id: {request.Id} response: Error Code {credentialsException.Code} Error Message {credentialsException.Message}");
            }
            catch (Exception exception)
            {
                response.ServiceMessageArray = new ServiceMessageArray
                {
                    ServiceMsg = new List<ServiceMessage>
                    {
                        new ServiceMessage{
                            Code = 999,
                            Description = exception.Message,
                            Severity = SeverityTypeEnum.Error
                        }
                    }
                    
                };
                logger.Error($"SendPOError: Id: {request.Id}. {JsonConvert.SerializeObject(exception)}");
            }

            
            return response;
        }

        /// <summary>
        /// The pre check.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="checkReferenceNumber">
        /// The check Reference Number.
        /// </param>
        /// <exception cref="GeneralException">
        /// Exception that contains a code and a message.
        /// </exception>
        private static void PreCheckSupportedOrderType(GetSupportedOrderTypesRequest request, bool checkReferenceNumber = true)
        {
            if (!checkReferenceNumber)
            {
                if (string.IsNullOrEmpty(((GetSupportedOrderTypesRequest)request).WsVersion))
                {
                    throw new GeneralException(115, "wsVersion not found");
                }

                return;
            }

            if (string.IsNullOrEmpty(((GetSupportedOrderTypesRequest)request).WsVersion))
            {
                throw new GeneralException(115, "wsVersion not found");
            }
        }

        /// <summary>
        /// The convert purchase order type to purchase order object.
        /// </summary>
        /// <param name="purchaseOrderType">
        /// The purchase order type.
        /// </param>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="PurchaseOrderObject"/>.
        /// </returns>
        private async Task<PurchaseOrderObject> ConvertPurchaseOrderTypeToPurchaseOrderObject(PurchaseOrderType purchaseOrderType, string vendorId, Credentials credentials)
        {
            PurchaseOrderObject purchaseOrderObject = new PurchaseOrderObject();

            if (purchaseOrderType != null)
            {
                //switch (id.ToLower())
                //{
                //    case "aws":
                //        {
                //            //ConvertAwsPo(purchaseOrderType, purchaseOrderObject);
                //            break;
                //        }
                //    default:
                //        {
                //            purchaseOrderObject = await GetPurchaseOrderObject(purchaseOrderType, id, pass);
                //            break;
                //        }
                //}

                purchaseOrderObject = await GetPurchaseOrderObject(purchaseOrderType, vendorId, credentials);
            }

            return purchaseOrderObject;
        }

        /// <summary>
        /// The convert aws po.
        /// </summary>
        /// <param name="purchaseOrderType">
        /// The purchase order type.
        /// </param>
        /// <param name="purchaseOrderObject">
        /// The purchase order object.
        /// </param>
        private static void ConvertAwsPo(PurchaseOrderType purchaseOrderType, PurchaseOrderObject purchaseOrderObject)
        {
            double taxAmount = 0;
            if (purchaseOrderType.TaxInformationArray != null && purchaseOrderType.TaxInformationArray.Length > 0)
            {
                taxAmount = purchaseOrderType.TaxInformationArray.Sum(x => x.TaxAmount);
            }

            purchaseOrderType.Rush = false;

            var purchaseOrderArray = 0;
            if (purchaseOrderType.ShipmentArray != null && purchaseOrderType.ShipmentArray.Any())
            {
                purchaseOrderArray = purchaseOrderType.ShipmentArray.Length;
            }

            DetailsContact detailsContactBill = new DetailsContact();
            DetailsContact detailsContactShip = new DetailsContact();
            if (purchaseOrderType.OrderContactArray != null && purchaseOrderType.OrderContactArray.Length > 0)
            {
                var billing = purchaseOrderType.OrderContactArray.FirstOrDefault(x => x.ContactType == "Bill");
                if (billing != null)
                {
                    var Address1 = billing.ContactDetails.Address1 ?? string.Empty;
                    var Address2 = billing.ContactDetails.Address2 ?? string.Empty;
                    var City = billing.ContactDetails.City ?? string.Empty;
                    var Company = billing.ContactDetails.CompanyName ?? string.Empty;
                    var Country = billing.ContactDetails.Country ?? string.Empty;
                    var Email = billing.ContactDetails.Email ?? string.Empty;
                    var Firstname = string.Empty;
                    var LastName = string.Empty;
                    if (billing.ContactDetails != null)
                    {
                        var firstAndLast = billing.ContactDetails.AttentionTo.Split(' ');
                        if (firstAndLast.Any())
                        {
                            Firstname = firstAndLast[0] ?? "NA";
                            if (firstAndLast.Count() > 2)
                            {
                                LastName = firstAndLast[1] ?? "NA";
                            }
                        }
                    }

                    var Phone = billing.ContactDetails.Phone ?? string.Empty;
                    var State = billing.ContactDetails.Region ?? string.Empty;
                    var ZipCode = billing.ContactDetails.PostalCode ?? string.Empty;

                    detailsContactBill.Address1 = Address1;
                    detailsContactBill.Address2 = Address2;
                    detailsContactBill.City = City;
                    detailsContactBill.Company = Company;
                    detailsContactBill.Country = Country;
                    detailsContactBill.Email = Email;
                    detailsContactBill.Firstname = Firstname;
                    detailsContactBill.LastName = LastName;
                    detailsContactBill.Phone = Phone;
                    detailsContactBill.State = State;
                    detailsContactBill.ZipCode = ZipCode;
                }

                var shipping = purchaseOrderType.OrderContactArray.FirstOrDefault(x => x.ContactType == "Ship");
                if (shipping != null)
                {
                    var Address1 = shipping.ContactDetails.Address1 ?? string.Empty;
                    var Address2 = shipping.ContactDetails.Address2 ?? string.Empty;
                    var City = shipping.ContactDetails.City ?? string.Empty;
                    var Company = shipping.ContactDetails.CompanyName ?? string.Empty;
                    var Country = shipping.ContactDetails.Country ?? string.Empty;
                    var Email = shipping.ContactDetails.Email ?? string.Empty;
                    var Firstname = string.Empty;
                    var LastName = string.Empty;
                    if (shipping.ContactDetails != null)
                    {
                        var firstAndLast = shipping.ContactDetails.AttentionTo.Split(' ');
                        if (firstAndLast.Any())
                        {
                            Firstname = firstAndLast[0] ?? "NA";
                            if (firstAndLast.Count() > 2)
                            {
                                LastName = firstAndLast[1] ?? "NA";
                            }
                        }
                    }

                    var Phone = shipping.ContactDetails.Phone ?? string.Empty;
                    var State = shipping.ContactDetails.Region ?? string.Empty;
                    var ZipCode = shipping.ContactDetails.PostalCode ?? string.Empty;

                    detailsContactShip.Address1 = Address1;
                    detailsContactShip.Address2 = Address2;
                    detailsContactShip.City = City;
                    detailsContactShip.Company = Company;
                    detailsContactShip.Country = Country;
                    detailsContactShip.Email = Email;
                    detailsContactShip.Firstname = Firstname;
                    detailsContactShip.LastName = LastName;
                    detailsContactShip.Phone = Phone;
                    detailsContactShip.State = State;
                    detailsContactShip.ZipCode = ZipCode;
                }
            }

            OrderHeader orderHeader = new OrderHeader()
            {
                OrderId = purchaseOrderType.OrderNumber,
                OrderNumber = purchaseOrderType.OrderNumber,
                OrderType = purchaseOrderType.OrderType,
                OrderDate = purchaseOrderType.OrderDate,
                OriginalDeliveryDate = DateTime.MinValue.ToString(),
                Rush = purchaseOrderType.Rush,
                BillingContact = detailsContactBill,
                ShippingContact = detailsContactShip,
                OrderAmount = Convert.ToDouble(purchaseOrderType.TotalAmount),
                ShippingAmount = purchaseOrderArray,
                TaxAmount = Convert.ToDouble(taxAmount),
                PartnerID = "AWS"
            };
            List<OrderDetails> orderDetails = new List<OrderDetails>();
            if (purchaseOrderType.LineItemArray != null && purchaseOrderType.LineItemArray.Any())
            {
                var line = 1;

                foreach (var lineOrder in purchaseOrderType.LineItemArray)
                {
                    OrderDetails orderDetail = new OrderDetails()
                    {
                        Line = line.ToString(),
                        ItemQuantity = lineOrder.Quantity.Value.ToString(),
                        OrderItemID = lineOrder.LineNumber,
                        SellerSku = lineOrder.ProductId,
                        ItemPrice = lineOrder.UnitPrice.ToString(),
                        ItemTax = taxAmount.ToString(),
                        ItemSize = null
                    };

                    orderDetails.Add(orderDetail);

                    line++;
                }
            }

            if (orderDetails != null && orderDetails.Count > 0)
            {
                purchaseOrderObject.OrderDetails = orderDetails;
            }

            purchaseOrderObject.OrderHeader = orderHeader;
        }

        /// <summary>
        /// The convert PiperLou purchase order.
        /// </summary>
        /// <param name="purchaseOrderType">
        /// The purchase order type.
        /// </param>
        /// <param name="purchaseOrderObject">
        /// The purchase order object.
        /// </param>
        private async Task<PurchaseOrderObject> GetPurchaseOrderObject(PurchaseOrderType purchaseOrderType, string vendorId, Credentials credentials)
        {
            double taxAmount = 0;
            if (purchaseOrderType.TaxInformationArray != null && purchaseOrderType.TaxInformationArray.Length > 0)
            {
                taxAmount = purchaseOrderType.TaxInformationArray.Sum(x => x.TaxAmount);
            }

            DetailsContact detailsContactBill = new DetailsContact();
            DetailsContact detailsContactShip = new DetailsContact();

            

            var blindShip = false;
            var shpThirdPartyAccount = string.Empty;
            var carrier = string.Empty;
            var serviceType = string.Empty;

            if (purchaseOrderType.OrderContactArray != null && purchaseOrderType.OrderContactArray.Length > 0)
            {
                var billing = purchaseOrderType.OrderContactArray.FirstOrDefault(x => x.ContactType == "Bill");
                if (billing != null)
                {
                    var Address1 = billing.ContactDetails.Address1 ?? string.Empty;
                    var Address2 = billing.ContactDetails.Address2 ?? string.Empty;
                    var City = billing.ContactDetails.City ?? string.Empty;
                    var Company = billing.ContactDetails.CompanyName ?? string.Empty;
                    var Country = billing.ContactDetails.Country ?? string.Empty;
                    var Email = billing.ContactDetails.Email ?? string.Empty;
                    var Firstname = string.Empty;
                    var LastName = string.Empty;
                    if (billing.ContactDetails != null)
                    {
                        if (!string.IsNullOrEmpty(billing.ContactDetails.AttentionTo))
                        {
                            var firstAndLast = billing.ContactDetails.AttentionTo.Split(' ');
                            if (firstAndLast.Any())
                            {
                                var cursor = 0;
                                foreach (var namePart in firstAndLast)
                                {
                                    if (cursor == 0)
                                    {
                                        Firstname = namePart;
                                    }
                                    else
                                    {
                                        LastName += $"{namePart} ";
                                    }

                                    cursor++;
                                }
                            }
                        }
                    }

                    var Phone = billing.ContactDetails.Phone ?? string.Empty;
                    var State = billing.ContactDetails.Region ?? string.Empty;
                    var ZipCode = billing.ContactDetails.PostalCode ?? string.Empty;

                    detailsContactBill.Address1 = Address1;
                    detailsContactBill.Address2 = Address2;
                    detailsContactBill.City = City;
                    detailsContactBill.Company = Company;
                    detailsContactBill.Country = Country;
                    detailsContactBill.Email = Email;
                    detailsContactBill.Firstname = Firstname;
                    detailsContactBill.LastName = LastName;
                    detailsContactBill.Phone = Phone;
                    detailsContactBill.State = State;
                    detailsContactBill.ZipCode = ZipCode;
                }
            }

            if (purchaseOrderType.ShipmentArray != null && purchaseOrderType.ShipmentArray.Length > 0)
            {
                var shippingObject = purchaseOrderType.ShipmentArray.FirstOrDefault();
                if (shippingObject != null)
                {
                    var shipping = shippingObject.ShipTo;
                    if (shipping != null)
                    {
                        var Address1 = shipping.ContactDetails.Address1 ?? string.Empty;
                        var Address2 = shipping.ContactDetails.Address2 ?? string.Empty;
                        var City = shipping.ContactDetails.City ?? string.Empty;
                        var Company = shipping.ContactDetails.CompanyName ?? string.Empty;
                        var Country = shipping.ContactDetails.Country ?? string.Empty;
                        var Email = shipping.ContactDetails.Email ?? string.Empty;
                        var Firstname = string.Empty;
                        var LastName = string.Empty;
                        if (shipping.ContactDetails != null)
                        {
                            if (!string.IsNullOrEmpty(shipping.ContactDetails.AttentionTo))
                            {
                                var firstAndLast = shipping.ContactDetails.AttentionTo.Split(' ');
                                if (firstAndLast.Any())
                                {
                                    var cursor = 0;
                                    foreach (var namePart in firstAndLast)
                                    {
                                        if (cursor == 0)
                                        {
                                            Firstname = namePart;
                                        }
                                        else
                                        {
                                            LastName += $"{namePart} ";
                                        }

                                        cursor++;
                                    }
                                }
                            }
                        }

                        var Phone = shipping.ContactDetails.Phone ?? string.Empty;
                        var State = shipping.ContactDetails.Region ?? string.Empty;
                        var ZipCode = shipping.ContactDetails.PostalCode ?? string.Empty;

                        detailsContactShip.Address1 = Address1;
                        detailsContactShip.Address2 = Address2;
                        detailsContactShip.City = City;
                        detailsContactShip.Company = Company;
                        detailsContactShip.Country = Country;
                        detailsContactShip.Email = Email;
                        detailsContactShip.Firstname = Firstname;
                        detailsContactShip.LastName = LastName;
                        detailsContactShip.Phone = Phone;
                        detailsContactShip.State = State;
                        detailsContactShip.ZipCode = ZipCode;
                    }

                    blindShip = shippingObject.BlindShip;

                    if (shippingObject.ThirdPartyAccount != null)
                    {
                        shpThirdPartyAccount = shippingObject.ThirdPartyAccount.AccountNumber;
                    }
                    
                    if (shippingObject.FreightDetails != null)
                    {
                        carrier = shippingObject.FreightDetails.Carrier;
                        serviceType = shippingObject.FreightDetails.Service;
                    }
                }
            }

            OrderHeader orderHeader = new OrderHeader()
            {
                OrderId = purchaseOrderType.OrderNumber,
                OrderNumber = purchaseOrderType.OrderNumber,
                OrderType = purchaseOrderType.OrderType,
                OrderDate = purchaseOrderType.OrderDate,
                OriginalDeliveryDate = DateTime.MinValue.ToString(),
                Rush = purchaseOrderType.Rush,
                BillingContact = detailsContactBill,
                ShippingContact = detailsContactShip,
                OrderAmount = Convert.ToDouble(purchaseOrderType.TotalAmount),
                InHandDate = purchaseOrderType.LineItemArray.First().RequestedInHands,
                TaxAmount = Convert.ToDouble(taxAmount),
                BPCustomer = vendorId,
                PartnerID = "BP",
                BlindShip = blindShip,
                ShpThirdPartyAccount = shpThirdPartyAccount,
                Carrier = carrier,
                Created_At = DateTime.Now,
                ServiceType = serviceType
            };
            List<OrderDetails> orderDetails = new List<OrderDetails>();
            
            if (purchaseOrderType.LineItemArray != null && purchaseOrderType.LineItemArray.Any())
            {
                var line = 1;

                foreach (var lineOrder in purchaseOrderType.LineItemArray)
                {
                    var itemColor = "White";

                    if (lineOrder.PartArray != null && lineOrder.PartArray.Length > 0)
                    {
                        var part = lineOrder.PartArray.FirstOrDefault();
                        if (part != null)
                        {
                            string[] tokens = part.PartId.Split('-');

                            itemColor = tokens.ElementAtOrDefault(1) != null ? tokens[1] : itemColor ;
                        }
                    }

                    // get the product data from DB
                    PsToBelConverter jsonConverter = new PsToBelConverter();
                    
                    //var credentials = new Credentials { CustomerId = id, Password = pass };

                    var partObj = lineOrder.PartArray.FirstOrDefault();
                    var decorationObj = lineOrder.Configuration.LocationArray.FirstOrDefault().DecorationArray.FirstOrDefault();
                    DesignProductData productDataInfo = null;
                    var productDataList = await purchaseOrderService.GetDesignProductData(credentials, partObj.PartId, decorationObj.DecorationName);
                    if (productDataList != null && productDataList.Any())
                    {
                        productDataInfo = productDataList.FirstOrDefault();
                    }
                    // End of get the product data from DB
                    
                    OrderDetails orderDetail = new OrderDetails()
                    {
                        Line = line.ToString(),
                        ItemQuantity = lineOrder.Quantity.Value.ToString(),
                        OrderItemID = lineOrder.LineNumber,
                        SellerSku = lineOrder.ProductId,
                        ItemPrice = lineOrder.UnitPrice.ToString(),
                        ItemColor = itemColor,
                        ItemTax = taxAmount.ToString(),
                        ItemSize = null,
                        InHandDate = lineOrder.RequestedShipDate,
                        OriginalDeliveryDate = DateTime.MinValue.ToString(),
                        DesignID = lineOrder.LineNumber,
                        CustomDesign = lineOrder.Configuration.LocationArray.Length > 0,
                        DesignInformation = lineOrder.Configuration.LocationArray.Length > 0 ? await jsonConverter.PsObjectToBelJson(credentials, orderHeader.OrderNumber, lineOrder.Configuration.LocationArray, productDataInfo) : null,
                        SetupCharge = lineOrder.Configuration.ChargeArray,
                    };

                    orderDetails.Add(orderDetail);

                    line++;
                }
            }

            var resPo = new PurchaseOrderObject();

            if (orderDetails != null && orderDetails.Count > 0)
            {
                resPo.OrderDetails = orderDetails;
            }

            resPo.OrderHeader = orderHeader;

            return resPo;
        }

        /// <summary>
        /// The pre check.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="checkReferenceNumber">
        /// The check Reference Number.
        /// </param>
        /// <exception cref="GeneralException">
        /// Exception that contains a code and a message.
        /// </exception>
        private static void PreCheckSendPurchaseOrder(SendPORequest request, bool checkReferenceNumber = true)
        {

            if (!checkReferenceNumber)
            {
                if (string.IsNullOrEmpty(((SendPORequest)request).WsVersion))
                {
                    throw new GeneralException(115, "wsVersion not found");
                }

                return;
            }

            if (string.IsNullOrEmpty(((SendPORequest)request).WsVersion))
            {
                throw new GeneralException(115, "wsVersion not found");
            }

        }
    }
}
