using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.Threading;
using CreateLabel_ML.wsEstafeta;
using CreateLabel_ML.wsFedexRate;
using CreateLabel_ML.wsFedexShip;
using CreateLabel_ML.wsRedPack;
using MySqlConnector;
using Address = CreateLabel_ML.wsFedexRate.Address;
using ClientDetail = CreateLabel_ML.wsFedexRate.ClientDetail;
using Contact = CreateLabel_ML.wsFedexRate.Contact;
using CustomerReference = CreateLabel_ML.wsFedexRate.CustomerReference;
using CustomerReferenceType = CreateLabel_ML.wsFedexRate.CustomerReferenceType;
using Dimensions = CreateLabel_ML.wsFedexRate.Dimensions;
using DropoffType = CreateLabel_ML.wsFedexRate.DropoffType;
using LabelFormatType = CreateLabel_ML.wsFedexRate.LabelFormatType;
using LabelSpecification = CreateLabel_ML.wsFedexRate.LabelSpecification;
using LabelStockType = CreateLabel_ML.wsFedexRate.LabelStockType;
using LinearUnits = CreateLabel_ML.wsFedexRate.LinearUnits;
using NotificationSeverityType = CreateLabel_ML.wsFedexRate.NotificationSeverityType;
using PackagingType = CreateLabel_ML.wsFedexRate.PackagingType;
using Party = CreateLabel_ML.wsFedexRate.Party;
using Payment = CreateLabel_ML.wsFedexRate.Payment;
using PaymentType = CreateLabel_ML.wsFedexRate.PaymentType;
using Payor = CreateLabel_ML.wsFedexRate.Payor;
using RequestedPackageLineItem = CreateLabel_ML.wsFedexRate.RequestedPackageLineItem;
using RequestedShipment = CreateLabel_ML.wsFedexRate.RequestedShipment;
using ServiceType = CreateLabel_ML.wsFedexRate.ServiceType;
using ShippingDocumentImageType = CreateLabel_ML.wsFedexRate.ShippingDocumentImageType;
using TransactionDetail = CreateLabel_ML.wsFedexRate.TransactionDetail;
using VersionId = CreateLabel_ML.wsFedexRate.VersionId;
using WebAuthenticationCredential = CreateLabel_ML.wsFedexRate.WebAuthenticationCredential;
using WebAuthenticationDetail = CreateLabel_ML.wsFedexRate.WebAuthenticationDetail;
using Weight = CreateLabel_ML.wsFedexRate.Weight;
using WeightUnits = CreateLabel_ML.wsFedexRate.WeightUnits;

namespace CreateLabel_ML
{
   public class Program
   {
      public static void Main(string[] args)
      {
         var log = new clsLog(); //Clase que crear el Log e inserta la botacira pc
         try
         {
            var cotizaciones = new Cotizaciones();
            var query = ConfigurationManager.AppSettings["SPConsulta"]; //store procedure que trae la informacion de los pedidos a procesar
            var cont = 0;
            var cn = new clsConexion();
            var data = cn.TraeDataTable(query, new MySqlParameter[] { }, CommandType.StoredProcedure);
            var dtRemitente = cn.TraeDataTable("select a.warehouse_id,a.warehouse_name, a.reference, a.address_1, a.address_2, a.active, a.warehouse_type_id, a.company,a.contact_name, a.contact_phone, a.contact_email, a.country, a.city, a.state, a.zipcode, a.comments_reference,a.statecode, zs.zipcode as zipcode_2, zs.state as state_2 from warehouse as a left outer join zipcode_state zs on a.zipcode = zs.zipcode where warehouse_id =@warehouse_id", new[]
            {
               new MySqlParameter("@warehouse_id", ConfigurationManager.AppSettings["WareHouse_ID"])
            }, CommandType.Text);
            var drRemitente = dtRemitente.Rows[0];
            log.EscribeLog(data.Rows.Count + " pedidos.");
            foreach (DataRow order in data.Rows)
            {
               log.EscribeLog("New Log ----------");
               var amount_list_1 = new List<clsCotizacion>();
               var json_srnevios_ = "";
               var json_srenvios = "";
               var code_final = "";
               var so = order["sale_order_id"].ToString();
               var sku = "sku: " + order["product_id"];
               var qty = "qty: " + order["quantity"];
               var name = order["product_name"].ToString();
               var reference = order["reference_order_number"].ToString();
               var dtLabel_info = cotizaciones.GetLabelInfo_track("sale_order_id=" + so);
               if (dtLabel_info.Rows.Count > 0)
                  log.EscribeLog("El pedido " + so + " ya tiene guia, por favor verificar.");
               else
               {
                  if (int.Parse(order["flag_creation_track"].ToString()) == 0)
                  {
                     byte guias = 1;
                     var dtproducto = cn.TraeDataTable("SELECT * FROM multiguide_products WHERE product_id=@product_id",
                        new[]
                        {
                           new MySqlParameter("@product_id", order["product_id"])
                        }, CommandType.Text);
                     if (dtproducto.Rows.Count > 0)
                     {
                        guias = byte.Parse(dtproducto.Rows[0]["guides_number"].ToString());
                        log.EscribeLog("Pedido requiere " + guias + " guias");
                     }
                     for (int i = 0; i < guias; i++)
                     {
                        log.EscribeLog("Procesando soid: " + so + " reference: " + reference);
                        var zpl_code = "";
                        var seller_sku = order["seller_sku"].ToString().ToLower();
                        log.EscribeLog("Seller_SKU " + seller_sku);
                        // ===> Mercadolibre (solo los que no son carritos)
                        /*declaramos variables necesarias*/
                        #region Variables
                        /*Inicio*/
                        var weight = int.Parse(order["weight"].ToString());
                        var length = int.Parse(order["length"].ToString());
                        var width = int.Parse(order["width"].ToString());
                        var height = int.Parse(order["height"].ToString());
                        var to_postalcode = order["shipping_zipcode"].ToString();
                        var shipping_recipient = order["shipping_recipient"].ToString();
                        var shipping_state = order["shipping_state"].ToString();
                        var shipping_neighborhood = order["shipping_neighborhood"].ToString();
                        var shipping_address1 = order["shipping_address1"].ToString();
                        var shipping_address2 = order["shipping_address2"].ToString();
                        var shipping_city = order["shipping_city"].ToString();
                        var shipping_phone = order["shipping_phone"].ToString();
                        var product_name = order["product_name"].ToString();
                        var comments = order["comments"].ToString();
                        var packageSize_volume = "";
                        var category_id = order["category_id"].ToString();
                        var now = new DateTime();
                        /*Fin*/
                        #endregion
                        /*Se genera cotizacion de los 4 servicios, fedex, estafeta, señor envios, e iEnvios*/

                        #region Fedex
                        /*Inicio*/
                        log.EscribeLog("Cotiza Fedex");
                        var data_fedex = new RateRequest
                        {
                           WebAuthenticationDetail = new WebAuthenticationDetail
                           {
                              ParentCredential = new WebAuthenticationCredential
                              {
                                 Key = ConfigurationManager.AppSettings["ParentKey"],
                                 Password = ConfigurationManager.AppSettings["ParentPassword"]
                              },
                              UserCredential = new WebAuthenticationCredential
                              {
                                 Key = ConfigurationManager.AppSettings["Key"],
                                 Password = ConfigurationManager.AppSettings["Password"]
                              }
                           },
                           ClientDetail = new ClientDetail
                           {
                              AccountNumber = ConfigurationManager.AppSettings["AccountNumber"],
                              MeterNumber = ConfigurationManager.AppSettings["MeterNumber"]
                           },
                           TransactionDetail = new TransactionDetail
                           {
                              CustomerTransactionId = "*** Express Domestic Shipping Request using PHP ***"
                           },
                           Version = new VersionId
                           {
                              Intermediate = 0,
                              Major = 24,
                              Minor = 0,
                              ServiceId = "crs"
                           },
                           RequestedShipment = new RequestedShipment
                           {
                              ShipTimestamp = DateTime.Now,
                              DropoffType = DropoffType.REGULAR_PICKUP,
                              ServiceType = ServiceType.FEDEX_EXPRESS_SAVER,
                              PackagingType = PackagingType.YOUR_PACKAGING,
                              TotalWeight = new Weight
                              {
                                 Value = weight,
                                 Units = WeightUnits.KG,
                                 UnitsSpecified = true,
                                 ValueSpecified = true
                              },
                              Shipper = new Party
                              {
                                 Contact = new Contact
                                 {
                                    PersonName = drRemitente["contact_name"].ToString(),
                                    CompanyName = drRemitente["company"].ToString(),
                                    EMailAddress = drRemitente["contact_email"].ToString(),
                                    PhoneNumber = drRemitente["contact_phone"].ToString()
                                 },
                                 Address = new Address
                                 {
                                    StreetLines = new[]
                                    {
                                       drRemitente["address_1"].ToString(),
                                       drRemitente["address_2"].ToString()
                                    },
                                    City = drRemitente["city"].ToString(),
                                    StateOrProvinceCode = drRemitente["statecode"].ToString(),
                                    PostalCode = drRemitente["zipcode"].ToString(),
                                    CountryCode = "MX",
                                    CountryName = "MEXICO"
                                 }
                              },
                              Recipient = new Party
                              {
                                 Contact = new Contact
                                 {
                                    PersonName = shipping_recipient,
                                    CompanyName = shipping_recipient,
                                    EMailAddress = string.Empty,
                                    PhoneNumber = shipping_phone
                                 },
                                 Address = new Address
                                 {
                                    StreetLines = new[]
                                    {
                                       shipping_address1,
                                       shipping_address2,
                                       shipping_neighborhood
                                    },
                                    City = shipping_city,
                                    StateOrProvinceCode = string.Empty,
                                    PostalCode = to_postalcode,
                                    CountryCode = "MX",
                                    Residential = true,
                                    ResidentialSpecified = true,
                                    CountryName = "MEXICO"
                                 }
                              },
                              ShippingChargesPayment = new Payment
                              {
                                 PaymentType = PaymentType.SENDER,
                                 PaymentTypeSpecified = true,
                                 Payor = new Payor
                                 {
                                    ResponsibleParty = new Party
                                    {
                                       AccountNumber = "634652221",
                                       Address = new Address
                                       {
                                          CountryCode = "MX"
                                       }
                                    }
                                 }
                              },
                              ShipTimestampSpecified = true,
                              DropoffTypeSpecified = true,
                              ServiceTypeSpecified = true,
                              PackagingTypeSpecified = true,
                              LabelSpecification = new LabelSpecification
                              {
                                 LabelFormatType = LabelFormatType.COMMON2D,
                                 LabelFormatTypeSpecified = true,
                                 ImageType = ShippingDocumentImageType.PDF,
                                 ImageTypeSpecified = true,
                                 LabelStockType = LabelStockType.PAPER_7X475,
                                 LabelStockTypeSpecified = true
                              },
                              PackageCount = "1",
                              RequestedPackageLineItems = new[]
                              {
                                 new RequestedPackageLineItem
                                 {
                                    SequenceNumber = "1",
                                    GroupPackageCount = "1",
                                    Weight = new Weight
                                    {
                                       Value = weight,
                                       Units = WeightUnits.KG,
                                       ValueSpecified = true,
                                       UnitsSpecified = true
                                    },
                                    Dimensions = new Dimensions
                                    {
                                       Height = height.ToString(),
                                       Length = length.ToString(),
                                       Width = width.ToString(),
                                       Units = LinearUnits.CM,
                                       UnitsSpecified = true
                                    },
                                    CustomerReferences = new[]
                                    {
                                       new CustomerReference
                                       {
                                          CustomerReferenceType = CustomerReferenceType
                                             .CUSTOMER_REFERENCE,
                                          Value = "RefXXXXX",
                                          CustomerReferenceTypeSpecified = true
                                       }
                                    }
                                 }
                              }
                           }
                        };
                        var fedex_cotizacion = cotizaciones.Fedex_quote(data_fedex, reference, so);
                        if (fedex_cotizacion.HighestSeverity == NotificationSeverityType.FAILURE ||
                            fedex_cotizacion.HighestSeverity == NotificationSeverityType.ERROR)
                        {
                           log.EscribeLog("Cotiza otro Fedex");
                           data_fedex.RequestedShipment.ServiceType = ServiceType.FEDEX_2_DAY_FREIGHT;
                           fedex_cotizacion = cotizaciones.Fedex_quote(data_fedex, reference, so);
                        }
                        var amount_fedex = string.Empty;
                        if (fedex_cotizacion.HighestSeverity != NotificationSeverityType.ERROR &&
                            fedex_cotizacion.HighestSeverity != NotificationSeverityType.FAILURE)
                        {
                           var amount_fedex_ = fedex_cotizacion.RateReplyDetails[0].RatedShipmentDetails[0]
                              .ShipmentRateDetail.TotalNetCharge.Amount;
                           amount_fedex = amount_fedex_.ToString("F2");
                           amount_list_1.Add(new clsCotizacion
                           {
                              Costo = (double) amount_fedex_,
                              Nombre = "Fedex",
                              X = "x1"
                           });
                        }
                        else
                        log.EscribeLog("Fedex mando error.");
                        /*Fin*/
                        #endregion

                        #region Estafeta
                        /*Seccion de cotizacioin de Estafeta*/
                        /*Inicio*/
                        var peso_volumetrico = length * width * height / 5000;
                        if (peso_volumetrico > 30 || weight > 30)
                           log.EscribeLog("El peso es mayor a 30 KG, se ignora Estafeta.");
                        else
                        {
                           log.EscribeLog("Cotiza Estafeta - Se omiten todas las cotizaciones de estafeta");
                           //var costo_base = int.Parse(ConfigurationManager.AppSettings["Tarifa"]); // tarifa primeros 5 kilos
                           //var tarifa_kilo = int.Parse(ConfigurationManager.AppSettings["CostoKilo"]);
                           ////peso volumetrico
                           ////redondeamos hacia arriba
                           //var peso_volumetrico_real = Math.Ceiling((double)peso_volumetrico);
                           //double amount_estafeta = 0;
                           //if (peso_volumetrico_real > weight)
                           //{
                           //   var sobre_peso = peso_volumetrico_real - 5;
                           //   var costo_sobrepeso = sobre_peso * tarifa_kilo;
                           //   var costo_total = (costo_base + costo_sobrepeso) * 1.16;
                           //   amount_estafeta = costo_total;
                           //}
                           //else
                           //{
                           //   var sobre_peso = weight - 5;
                           //   var costo_sobrepeso = sobre_peso * tarifa_kilo;
                           //   var costo_total = (costo_base + costo_sobrepeso) * 1.16;
                           //   amount_estafeta = costo_total;
                           //}
                           //amount_list_1.Add(new clsCotizacion
                           //{
                           //   Costo = amount_estafeta,
                           //   Nombre = "Estafeta",
                           //   X = "x3"
                           //});
                           //log.AgregaPcgRequest("Cotizacion por formula aritmetica", amount_estafeta.ToString(),
                           //   reference, so, "API Estafeta");
                        }

                        /*Fin*/
                        #endregion Estafeta

                        #region Sr. Envios
                        /*Seccion de cotizacion de Sr. Envios*/
                        /*Inicio*/
                        log.EscribeLog("Cotiza Sr. Envios");
                        Thread.Sleep(1000);
                        var srenvios_cotizacion = cotizaciones.Quote_SrEnvios(new clsSrEnvios
                        {
                           address_from = new AddressFrom
                           {
                              address1 = drRemitente["address_1"].ToString(),
                              address2 = drRemitente["address_2"].ToString(),
                              city = drRemitente["city"].ToString(),
                              company = drRemitente["company"].ToString(),
                              country = "MX",
                              email = drRemitente["contact_email"].ToString(),
                              name = drRemitente["contact_name"].ToString(),
                              phone = drRemitente["contact_phone"].ToString(),
                              province = drRemitente["state"].ToString(),
                              zip = drRemitente["zipcode"].ToString()
                           },
                           address_to = new AddressTo
                           {
                              company = shipping_recipient,
                              country = "MX",
                              email = "cesar.garcia."+DateTime.Now.ToString("HHmmss")+"@mercadazo.com.mx",
                              phone = shipping_phone,
                              province = shipping_state,
                              zip = to_postalcode,
                              address1 = shipping_address1,
                              address2 = shipping_address2,
                              city = shipping_city,
                              name = shipping_recipient,
                              reference = comments.Length > 25 ? comments.Substring(0, 25) : comments,
                              contents = product_name
                           },
                           parcels = new List<Parcel>(new[]
                           {
                              new Parcel
                              {
                                 height = height,
                                 length = length,
                                 weight = weight,
                                 width = width,
                                 mass_unit = "KG",
                                 distance_unit = "CM"
                              }
                           }),
                           consignment_note_class_code = category_id
                        }, reference, so);
                        if (srenvios_cotizacion.included != null)
                           foreach (var cotizacion in srenvios_cotizacion.included)
                           {
                              if (string.Compare(cotizacion.type, "rates", StringComparison.CurrentCultureIgnoreCase) ==
                                  0)
                              {
                                 var id = cotizacion.id;
                                 var amount_srenvios = double.Parse(cotizacion.attributes.total_pricing);
                                 var provider = cotizacion.attributes.provider;
                                 if (amount_srenvios > 0)
                                 {
                                    var dtproveedor = cn.TraeDataTable("SELECT * FROM sr_envios_providers WHERE provider='" + provider + "'",
                                       new MySqlParameter[] { }, CommandType.Text);
                                    if (dtproveedor.Rows.Count > 0)
                                       amount_list_1.Add(new clsCotizacion
                                       {
                                          Costo = amount_srenvios,
                                          Nombre = provider,
                                          X = id
                                       });
                                 }
                              }
                           }
                        else
                           log.EscribeLog("Sr. Envios mando error.");
                        /*Fin*/
                        #endregion

                        #region iEnvios

                        /* Inicio iEnvios */
                        log.EscribeLog("Cotiza iEnvios.");
                        var modeloiEnvios = new mdlIEnvios();
                        var ienvios = modeloiEnvios.Cotiza(new clsIEnvios
                        {
                           cp_destino = to_postalcode,
                           cp_origen = drRemitente["zipcode"].ToString(),
                           clave = ConfigurationManager.AppSettings["WareHouse_Reference"],
                           productos = new List<ProductoIEnvios>(new[]
                           {
                              new ProductoIEnvios
                              {
                                 sku = string.Empty,
                                 producto = product_name,
                                 medidas = new List<Medida>(new[]
                                 {
                                    new Medida
                                    {
                                       alto = height.ToString(),
                                       ancho = width.ToString(),
                                       largo = length.ToString(),
                                       peso = weight.ToString(),
                                       cantidad = "1",
                                       pieza = seller_sku + ": 1"
                                    }
                                 })
                              }
                           })
                        }, reference, so);
                        if (ienvios.cotizacion != null)
                        {
                           amount_list_1.AddRange(ienvios.cotizacion
                              .Where(cotizacion => cotizacion.error.Trim().Length == 0)
                              .Select(cotizacion => new clsCotizacion
                              {
                                 Costo = double.Parse(cotizacion.tarifa.Replace(" ", string.Empty)
                                    .Replace(",", string.Empty)),
                                 Nombre = "iENVIOS",
                                 X = cotizacion.folio.ToString()
                              }));
                        }
                        else
                           log.EscribeLog("iEnvios mando error.");
                        /* Fin */
                        #endregion

                        #region RedPack

                        /* Inicio RedPack */
                        log.EscribeLog("Cotiza RedPack.");
                        var modelorespack = new mdlRedPack();
                                //////////////////777

                              var guiacobertura = modelorespack.Cobertura(new Guia
                                {
                                  tipoEntrega = new IdDesc
                                  { id=2,
                                   descripcion="",
                                   idSpecified=true
                                  },
                                    consignatario = new wsRedPack.Direccion
                                    {
                                        nombre_Compania = shipping_recipient,
                                        calle = shipping_address1,
                                        colonia_Asentamiento = shipping_neighborhood,
                                        codigoPostal = int.Parse(to_postalcode),
                                        numeroExterior = shipping_address2,
                                        numeroInterior = "NA",
                                        codigoPostalSpecified = true,
                                        ciudad = shipping_city,
                                        estado = shipping_state,
                                        contacto = shipping_recipient,
                                        email = "NA",
                                        pais = "México",
                                        referenciaUbicacion = comments,
                                        telefonos = new[]
                                    {
                                    new Telefono
                                    {
                                       extension = "NA",
                                       LADA = "NA",
                                       telefono = shipping_phone
                                    }
                                 }
                                    },
                                    remitente = new wsRedPack.Direccion
                                    {
                                        nombre_Compania = drRemitente["contact_name"].ToString(),
                                        calle = drRemitente["address_1"].ToString(),
                                        colonia_Asentamiento = drRemitente["address_2"].ToString(),
                                        codigoPostal = int.Parse(drRemitente["zipcode"].ToString()),
                                        numeroExterior = "NA",
                                        numeroInterior = "NA",
                                        codigoPostalSpecified = true,
                                        ciudad = drRemitente["city"].ToString(),
                                        estado = drRemitente["state"].ToString(),
                                        contacto = drRemitente["contact_name"].ToString(),
                                        email = drRemitente["contact_email"].ToString(),
                                        pais = "México",
                                        referenciaUbicacion = "NA",
                                        telefonos = new[]
   {
                                    new Telefono
                                    {
                                       extension = "NA",
                                       LADA = "NA",
                                       telefono = drRemitente["contact_phone"].ToString()
                                    }
                                 }
                                    },
                                    paquetes = new[]
{
                                 new Paquete
                                 {
                                    alto = height,
                                    ancho = width,
                                    largo = length,
                                    peso = weight,
                                    consecutivo = 0,
                                    altoSpecified = true,
                                    anchoSpecified = true,
                                    largoSpecified = true,
                                    pesoSpecified = true,
                                    consecutivoSpecified = true,
                                    descripcion = seller_sku
                                 }
                              }
                                }, reference, so);

                                ///////////////////

                        //        var guiacobertura = modelorespack.Cobertura(new Guia
                        //{
                        //   remitente = new wsRedPack.Direccion
                        //   {
                        //      codigoPostal = int.Parse(drRemitente["zipcode"].ToString()),
                        //      codigoPostalSpecified = true
                        //   },
                        //   consignatario = new wsRedPack.Direccion
                        //   {
                        //      codigoPostal = int.Parse(to_postalcode),
                        //      codigoPostalSpecified = true
                        //   }
                        //}, reference, so);

                        Guia guia=null;
                        if(guiacobertura.resultadoConsumoWS[0].estatus==1)
                           if(guiacobertura.cotizaciones.Any(c=>string.Compare(c.tipoServicio.equivalencia,"DOMICILIO",StringComparison.CurrentCultureIgnoreCase)==0))
                           {
                              guia = modelorespack.Cotiza(new Guia
                              {
                                 consignatario = new wsRedPack.Direccion
                                 {
                                    nombre_Compania = shipping_recipient,
                                    calle = shipping_address1,
                                    colonia_Asentamiento = shipping_neighborhood,
                                    codigoPostal = int.Parse(to_postalcode),
                                    numeroExterior = shipping_address2,
                                    numeroInterior = "NA",
                                    codigoPostalSpecified = true,
                                    ciudad = shipping_city,
                                    estado = shipping_state,
                                    contacto = shipping_recipient,
                                    email = "NA",
                                    pais = "México",
                                    referenciaUbicacion = comments,
                                    telefonos = new[]
                                 {
                                    new Telefono
                                    {
                                       extension = "NA",
                                       LADA = "NA",
                                       telefono = shipping_phone
                                    }
                                 }
                                 },
                                 remitente = new wsRedPack.Direccion
                              {
                                 nombre_Compania = drRemitente["contact_name"].ToString(),
                                 calle = drRemitente["address_1"].ToString(),
                                 colonia_Asentamiento = drRemitente["address_2"].ToString(),
                                 codigoPostal = int.Parse(drRemitente["zipcode"].ToString()),
                                 numeroExterior = "NA",
                                 numeroInterior = "NA",
                                 codigoPostalSpecified = true,
                                 ciudad = drRemitente["city"].ToString(),
                                 estado = drRemitente["state"].ToString(),
                                 contacto = drRemitente["contact_name"].ToString(),
                                 email = drRemitente["contact_email"].ToString(),
                                 pais = "México",
                                 referenciaUbicacion = "NA",
                                 telefonos = new[]
                                 {
                                    new Telefono
                                    {
                                       extension = "NA",
                                       LADA = "NA",
                                       telefono = drRemitente["contact_phone"].ToString()
                                    }
                                 }
                              },
                                 paquetes = new[]
                              {
                                 new Paquete
                                 {
                                    alto = height,
                                    ancho = width,
                                    largo = length,
                                    peso = weight,
                                    consecutivo = 0,
                                    altoSpecified = true,
                                    anchoSpecified = true,
                                    largoSpecified = true,
                                    pesoSpecified = true,
                                    consecutivoSpecified = true,
                                    descripcion = seller_sku
                                 }
                              }
                              }, reference, so);
                              if (guia.resultadoConsumoWS[0].estatus == 1)
                              {
                                 foreach (var cot in guia.cotizaciones)
                                 {
                                    if (cot.tipoServicio.id == 2)
                                    {
                                       amount_list_1.Add(new clsCotizacion
                                       {
                                          Costo = cot.tarifa,
                                          X = "x7",
                                          Nombre = "REDPACK"
                                       });
                                       break;
                                    }
                                 }
                              }
                              else
                                 log.EscribeLog("Error al cotizar RedPack.");
                        }
                        else
                        log.EscribeLog("Redpack sin Cobertura.");

                                /*Fin*/
                                #endregion

                                #region 99 Minutos

                                log.EscribeLog("Cotiza 99 Minutos");
                        Thread.Sleep(1000);
                        var modelo99min = new mdl99min();                                
                        var _99min = modelo99min.Cotiza(new ClsCotizacion99Minutos   
                        {
                            Weight = weight.ToString(),
                            Width = height.ToString(),
                            Depth = width.ToString(),
                            Height = length.ToString(),
                            Origin = new Origin
                                    {
                                        CodePostal = drRemitente["zipcode"].ToString(),
                                        Country = "MEX",
                                    },
                            Destination = new Destination
                                    {
                                        CodePostal = to_postalcode,
                                        Country = "MEX",
                                    }
                        }, reference, so);
                           if (_99min !=null) 
                           { 
                            if (_99min.Message != null)
                            {
                                    if (_99min.Message.Count > 0)
                                    {
                                        foreach (var message in _99min.Message)
                                        {
                                            var dtServiceTypeCode = cn.TraeDataTable("SELECT * FROM 99Minutos_deliveryType WHERE DeliveryType_code=@ServiceTypeCode and serviceType_status=1", new[]
                                            {
                                                new MySqlParameter("@ServiceTypeCode", message.DeliveryType.Description.ToString())
                                            }, CommandType.Text);

                                            if (dtServiceTypeCode.Rows.Count > 0)
                                            {
                                                amount_list_1.Add(new clsCotizacion
                                                {
                                                    Costo = double.Parse(message.Cost.ToString()),
                                                    Nombre = "99Min",
                                                    X = message.DeliveryType.Description.ToString()
                                                });
                                            }
                                        }                                    
                                    }
                                }
                           }
                          else
                            log.EscribeLog("99Minutos mando error o no tiene sin cobertura.");
                        /* Fin */
                        #endregion

                        /*Generalizamos los valores a solo uno*/
                        /*Inicio*/
                        log.EscribeLog("Ordena cotizaciones");
                        if (amount_list_1.Count == 0)
                           log.EscribeLog("Pedido sin cobertura.");
                        else
                        {
                           amount_list_1 = amount_list_1.OrderBy(c => c.Costo).ToList();
                           var provider_final = amount_list_1[0].Nombre.ToUpper();
                           code_final = amount_list_1[0].X;
                           var minimo_final = amount_list_1[0].Costo;
                           /*Fin*/
                           /*Pasamos el nombre o la inicial de la paqueteria a un valor string*/
                           /*mandamos la paquteria real*/
                           var provider_ = provider_final;
                           /*imprimimos valores obtenidos*/
                           /*Inicio*/
                           /*Fin*/
                           var tracking_number_carrier = string.Empty;
                           var base_64_carrier = string.Empty;
                           var carrier_method = string.Empty;
                           var carrier_service_type = string.Empty;
                           var carrier_aumount = string.Empty;
                           var web = new WebClient();
                           log.EscribeLog("Se eligio " + provider_final);
                           var otraguia = string.Empty;
                                    switch (provider_final)
                                    {
                                        #region Fedex
                                        case "FEDEX":
                                            /*Envios para Fedex*/
                                            /*Inicio*/
                                            //Se imprime paqueteria elegida
                                            //se genera json para mandar a fedex
                                            var json_fedex = new ProcessShipmentRequest
                                            {
                                                WebAuthenticationDetail = new wsFedexShip.WebAuthenticationDetail
                                                {
                                                    ParentCredential = new wsFedexShip.WebAuthenticationCredential
                                                    {
                                                        Key = "xxxxxxxxxxx",
                                                        Password = "xxxxxxxxxx"
                                                    },
                                                    UserCredential = new wsFedexShip.WebAuthenticationCredential
                                                    {
                                                        Key = "mqlupHjZZEzFYTJj",
                                                        Password = "8x4E9KlA9TFuQhJ5cRjAwu6zb"
                                                    }
                                                },
                                                ClientDetail = new wsFedexShip.ClientDetail
                                                {
                                                    AccountNumber = "634652221",
                                                    MeterNumber = "113502074"
                                                },
                                                TransactionDetail = new wsFedexShip.TransactionDetail
                                                {
                                                    CustomerTransactionId = "*** Express Domestic Shipping Request using PHP ***"
                                                },
                                                Version = new wsFedexShip.VersionId
                                                {
                                                    Intermediate = 0,
                                                    Major = 26,
                                                    Minor = 0,
                                                    ServiceId = "ship"
                                                },
                                                RequestedShipment = new wsFedexShip.RequestedShipment
                                                {
                                                    ShipTimestamp = DateTime.Now,
                                                    DropoffType = wsFedexShip.DropoffType.REGULAR_PICKUP,
                                                    ServiceType = data_fedex.RequestedShipment.ServiceType.ToString(),
                                                    PackagingType = "YOUR_PACKAGING",
                                                    TotalWeight = new wsFedexShip.Weight
                                                    {
                                                        Value = weight,
                                                        Units = wsFedexShip.WeightUnits.KG
                                                    },
                                                    Shipper = new wsFedexShip.Party
                                                    {
                                                        Contact = new wsFedexShip.Contact
                                                        {
                                                            PersonName = drRemitente["contact_name"].ToString(),
                                                            CompanyName = drRemitente["company"].ToString(),
                                                            EMailAddress = drRemitente["contact_email"].ToString(),
                                                            PhoneNumber = drRemitente["contact_phone"].ToString()
                                                        },
                                                        Address = new wsFedexShip.Address
                                                        {
                                                            StreetLines = new[]
                                                        {
                                                drRemitente["address_1"].ToString(),
                                                drRemitente["address_2"].ToString()
                                             },
                                                            City = drRemitente["city"].ToString(),
                                                            StateOrProvinceCode = drRemitente["statecode"].ToString(),
                                                            PostalCode = drRemitente["zipcode"].ToString(),
                                                            CountryCode = "MX",
                                                            CountryName = "MEXICO"
                                                        }
                                                    },
                                                    Recipient = new wsFedexShip.Party
                                                    {
                                                        Contact = new wsFedexShip.Contact
                                                        {
                                                            PersonName = shipping_recipient,
                                                            CompanyName = shipping_recipient,
                                                            EMailAddress = string.Empty,
                                                            PhoneNumber = shipping_phone
                                                        },
                                                        Address = new wsFedexShip.Address
                                                        {
                                                            StreetLines = new[]
                                                        {
                                                shipping_address1,
                                                shipping_address2,
                                                shipping_neighborhood
                                             },
                                                            City = shipping_city,
                                                            StateOrProvinceCode = string.Empty,
                                                            PostalCode = to_postalcode,
                                                            CountryCode = "MX",
                                                            Residential = true,
                                                            ResidentialSpecified = true,
                                                            CountryName = "MEXICO"
                                                        }
                                                    },
                                                    ShippingChargesPayment = new wsFedexShip.Payment
                                                    {
                                                        PaymentType = wsFedexShip.PaymentType.SENDER,
                                                        Payor = new wsFedexShip.Payor
                                                        {
                                                            ResponsibleParty = new wsFedexShip.Party
                                                            {
                                                                AccountNumber = "634652221",
                                                                Address = new wsFedexShip.Address
                                                                {
                                                                    CountryCode = "MX"
                                                                }
                                                            }
                                                        }
                                                    },
                                                    LabelSpecification = new wsFedexShip.LabelSpecification
                                                    {
                                                        LabelFormatType = wsFedexShip.LabelFormatType.COMMON2D,
                                                        ImageType = wsFedexShip.ShippingDocumentImageType.PDF,
                                                        ImageTypeSpecified = true,
                                                        LabelStockType = wsFedexShip.LabelStockType.PAPER_7X475,
                                                        LabelStockTypeSpecified = true
                                                    },
                                                    PackageCount = "1",
                                                    RequestedPackageLineItems = new[]
                                                  {
                                          new wsFedexShip.RequestedPackageLineItem
                                          {
                                             SequenceNumber = "1",
                                             GroupPackageCount = "1",
                                             Weight = new wsFedexShip.Weight
                                             {
                                                Value = weight,
                                                Units = wsFedexShip.WeightUnits.KG
                                             },
                                             Dimensions = new wsFedexShip.Dimensions
                                             {
                                                Height = height.ToString(),
                                                Length = length.ToString(),
                                                Width = width.ToString(),
                                                Units = wsFedexShip.LinearUnits.CM
                                             },
                                             CustomerReferences = new[]
                                             {
                                                new wsFedexShip.CustomerReference
                                                {
                                                   CustomerReferenceType =
                                                      wsFedexShip.CustomerReferenceType.CUSTOMER_REFERENCE,
                                                   Value = "RefXXXXX"
                                                }
                                             },
                                             ItemDescription = seller_sku,
                                             ItemDescriptionForClearance = seller_sku
                                          }
                                       }
                                                }
                                            };
                                            //se manda json al webservices a fedex
                                            //die($response_created_label_fedex);
                                            //se retorna el json y se decodifica
                                            log.EscribeLog("Crea guia Fedex");
                                            var fedex_created = cotizaciones.CreatedlabelFedex(json_fedex, reference, so);
                                            if (fedex_created.HighestSeverity != wsFedexShip.NotificationSeverityType.FAILURE &&
                                                fedex_created.HighestSeverity != wsFedexShip.NotificationSeverityType.ERROR)
                                            {
                                                var track_fedex = fedex_created.CompletedShipmentDetail.MasterTrackingId
                                                   .TrackingNumber;
                                                var pdf_fedex = Convert.ToBase64String(fedex_created.CompletedShipmentDetail
                                                   .CompletedPackageDetails[0].Label.Parts[0].Image);
                                                //var url_pdf = "https://www.mercadot.com/_dashboard/go/fedex/".pdf_fedex;
                                                //se imprimen valores de guia y url
                                                tracking_number_carrier = track_fedex;
                                                base_64_carrier = pdf_fedex;
                                                carrier_method = "FEDEX";
                                                carrier_service_type = "FEDEX_EXPRESS_SAVER";
                                                carrier_aumount = amount_fedex;

                                                /////////////////////////////////////////
                                                //Carta porte FEDEX
                                                if(cotizaciones.CreaCartaPorte(dtRemitente.Rows[0],order, order, order["sale_order_id"].ToString() , "0", tracking_number_carrier))
                                                {
                                                    log.EscribeLog("Se Genero Carta Porte para FEDEX");
                                                }
                                                else
                                                {
                                                    log.EscribeLog("Error al Generar Carta Porte para FEDEX " + tracking_number_carrier);
                                                }

                                                /////////////////////////////////////////



                                                log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                                log.EscribeLog("Nombre: " + shipping_recipient);
                                                log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                            }
                                            else
                                                log.EscribeLog("Error al crear guia Fedex.");
                                            /*Fin*/
                                            break;
                                        #endregion

                                        #region Estafeta

                                        case "ESTAFETA":
                                            /*Envios para Estafeta*/
                                            /*Inicio*/
                                            //var estafeta_xml = new EstafetaLabelRequest
                                            //{
                                            //   customerNumber = ConfigurationManager.AppSettings["customerNumber"],
                                            //   labelDescriptionList = new[]
                                            //   {
                                            //      new LabelDescriptionList
                                            //      {
                                            //         aditionalInfo = "so: " + so,
                                            //         content = seller_sku + " : 1",
                                            //         contentDescription = name,
                                            //         costCenter = "12345",
                                            //         deliveryToEstafetaOffice = false,
                                            //         destinationCountryId = "MX",
                                            //         destinationInfo = new DestinationInfo
                                            //         {
                                            //            address1 = shipping_address1.Length > 30
                                            //               ? shipping_address1.Substring(0, 30)
                                            //               : shipping_address1,
                                            //            address2 = shipping_address2,
                                            //            cellPhone = shipping_phone,
                                            //            city = shipping_city,
                                            //            contactName = shipping_recipient.Length > 30
                                            //               ? shipping_recipient.Substring(0, 30)
                                            //               : shipping_recipient,
                                            //            corporateName = shipping_recipient,
                                            //            customerNumber = "0000000",
                                            //            neighborhood = shipping_neighborhood,
                                            //            phoneNumber = shipping_phone,
                                            //            state = shipping_state,
                                            //            zipCode = to_postalcode
                                            //         },
                                            //         numberOfLabels = 1,
                                            //         officeNum = "465",
                                            //         originInfo = new OriginInfo
                                            //         {
                                            //            address1 = drRemitente["address_1"].ToString(),
                                            //            address2 = drRemitente["address_2"].ToString(),
                                            //            cellPhone = drRemitente["contact_phone"].ToString(),
                                            //            city = drRemitente["city"].ToString(),
                                            //            contactName = drRemitente["contact_name"].ToString(),
                                            //            corporateName = drRemitente["company"].ToString(),
                                            //            customerNumber = ConfigurationManager.AppSettings["customerNumber"],
                                            //            neighborhood = drRemitente["address_2"].ToString(),
                                            //            phoneNumber = drRemitente["contact_phone"].ToString(),
                                            //            state = drRemitente["state"].ToString(),
                                            //            zipCode = drRemitente["zipcode"].ToString()
                                            //         },
                                            //         originZipCodeForRouting = drRemitente["zipcode"].ToString(),
                                            //         parcelTypeId = 1,
                                            //         reference = sku + " : " + qty,
                                            //         returnDocument = false,
                                            //         serviceTypeId = "70",
                                            //         valid = true,
                                            //         weight = weight
                                            //      }
                                            //   },
                                            //   labelDescriptionListCount = 1,
                                            //   login = ConfigurationManager.AppSettings["customerNumber"],
                                            //   paperType = 1,
                                            //   password = ConfigurationManager.AppSettings["customerPassword"],
                                            //   quadrant = 0,
                                            //   suscriberId = "Z4",
                                            //   valid = true
                                            //};
                                            ////Solicitamos todos los datos de la guia
                                            //var response_created_label_estafeta =
                                            //   cotizaciones.CreatedlabelEstafeta(estafeta_xml, reference, so);
                                            ////Declaramos numero de guia y el base64
                                            //if (response_created_label_estafeta.valid)
                                            //{
                                            //   if(response_created_label_estafeta.labelPDF==null)
                                            //      log.EscribeLog("Error al crear guia Estafeta. " +response_created_label_estafeta.globalResult.resultDescription);
                                            //   else
                                            //   {
                                            //      tracking_number_carrier = response_created_label_estafeta.labelResultList[0].resultDescription;
                                            //      base_64_carrier = Convert.ToBase64String(response_created_label_estafeta.labelPDF);
                                            //      carrier_method = "Estafeta";
                                            //      carrier_aumount = minimo_final.ToString("F2");
                                            //      carrier_service_type = "Terrestre";
                                            //      log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                            //      log.EscribeLog("Nombre: " + shipping_recipient);
                                            //      log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                            //   }
                                            //}
                                            //else
                                            //   log.EscribeLog("Error al crear guia Estafeta. " + response_created_label_estafeta.globalResult.resultDescription);
                                            ///*Fin*/
                                            break;
                                        #endregion

                                        #region REDPACK
                                        case "REDPACK":
                                            guia = modelorespack.CreaGuia(guia, reference, so);
                                            if (guia.resultadoConsumoWS[0].estatus == 1)
                                            {
                                                var track_srenvios = guia.numeroDeGuia;
                                                var pdf_srenvios = guia.paquetes[0].formatoEtiqueta;
                                                var b64Doc = Convert.ToBase64String(pdf_srenvios);
                                                //se imprimen valores de guia y url
                                                tracking_number_carrier = track_srenvios;
                                                base_64_carrier = b64Doc;
                                                carrier_method = "REDPACK";
                                                carrier_service_type = code_final;
                                                carrier_aumount = amount_list_1[0].Costo.ToString();
                                                log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                                log.EscribeLog("Nombre: " + shipping_recipient);
                                                log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                                cn.EjecutaConsulta("UPDATE sale_order_folio SET estatus=0 WHERE folio=" + guia.numeroDeGuia,
                                                   new MySqlParameter[] { }, CommandType.Text);
                                            }
                                            else
                                                log.EscribeLog("Error al crear guia RedPack.");
                                            break;
                                        #endregion

                                        #region PAQUETEEXPRESS
                                        case "PAQUETEXPRESS":
                                            /*Envio para Señor envios*/
                                            /*Inicio*/
                                            //se genera json para mandar a Se�or envios
                                            //se manda json al webservices a se�or envios
                                            //se retorna el json y se decodifica
                                            clsRespuestaEtiquetaSrEnvios srenvios_created;
                                            try
                                            {
                                                srenvios_created = cotizaciones.CreatedlabelSrEnvios(new clsEtiquetaSrEnvios
                                                {
                                                    rate_id = int.Parse(code_final),
                                                    label_format = "pdf"
                                                }, reference, so);
                                            }
                                            catch
                                            {
                                                try
                                                {
                                                    srenvios_created = cotizaciones.CreatedlabelSrEnvios(new clsEtiquetaSrEnvios
                                                    {
                                                        rate_id = int.Parse(code_final),
                                                        label_format = "pdf"
                                                    }, reference, so);
                                                }
                                                catch
                                                {
                                                    srenvios_created = null;
                                                }
                                            }
                                            if (srenvios_created != null)
                                            {
                                                var track_srenvios = srenvios_created.data.attributes.tracking_number;
                                                var pdf_srenvios = srenvios_created.data.attributes.label_url;
                                                var carrier_srenvios = srenvios_created.data.attributes.tracking_url_provider;
                                                var rate_srenvios = srenvios_created.data.attributes.rate_id;
                                                otraguia = srenvios_created.data.attributes.payload.object_dto;
                                                var b64Doc = Convert.ToBase64String(web.DownloadData(pdf_srenvios));
                                                //se imprimen valores de guia y url
                                                tracking_number_carrier = track_srenvios;
                                                base_64_carrier = b64Doc;
                                                carrier_method = provider_;
                                                carrier_service_type = code_final;
                                                carrier_aumount = amount_list_1[0].Costo.ToString();
                                                log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                                log.EscribeLog("Nombre: " + shipping_recipient);
                                                log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                            }
                                            /*Fin*/
                                            break;
                                        #endregion

                                        #region IENVIOS
                                        case "IENVIOS":
                                            /*Envio para iEnvios*/
                                            /*Inicio*/
                                            //se genera json para mandar a Se�or envios
                                            //se manda json al webservices a se�or envios
                                            //se retorna el json y se decodifica
                                            var ienvios_created = modeloiEnvios.CreaGuia(new clsEnviaIEnvios
                                            {
                                                folio = int.Parse(code_final),
                                                destinatario = new Destinatario
                                                {
                                                    celular = shipping_phone,
                                                    correo = string.Empty,
                                                    nombre_completo = shipping_recipient,
                                                    direccion = new Direccion
                                                    {
                                                        calle = shipping_address1,
                                                        colonia = shipping_neighborhood,
                                                        comentarios = comments,
                                                        cp = to_postalcode,
                                                        num_ext = shipping_address2,
                                                        num_int = string.Empty
                                                    }
                                                }
                                            }, reference, so);
                                            if (!ienvios_created.error)
                                            {
                                                var track_ienvios = ienvios_created.data.orden.folio_orden;
                                                var pdf_ienvios = ienvios_created.data.url_pdf;
                                                var carrier_ienvios = "iENVIOS";
                                                var b64iDoc = Convert.ToBase64String(web.DownloadData(pdf_ienvios));
                                                //se imprimen valores de guia y url
                                                tracking_number_carrier = track_ienvios;
                                                base_64_carrier = b64iDoc;
                                                carrier_method = provider_;
                                                carrier_service_type = code_final;
                                                carrier_aumount = amount_list_1[0].Costo.ToString();
                                                log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                                log.EscribeLog("Nombre: " + shipping_recipient);
                                                log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                            }
                                            else
                                                log.EscribeLog("Error al crear guia iEnvios.");
                                            /*Fin*/
                                            break;
                                            #endregion

                                        #region 99Min
                                        case "99MIN":
                                        double weight_volume;
                                        // peso volumetrico
                                        weight_volume = (length * width * height) / 5000;
                                        // redondeamos hacia arriba
                                        weight_volume = weight_volume * 1000;
                                        weight_volume = Math.Ceiling(weight_volume);

                                        if (weight_volume <= 10000){
                                            packageSize_volume = "xs";
                                        }
                                        else if (weight_volume <= 15000){ 
                                            packageSize_volume = "s";
                                        }
                                        else if (weight_volume <= 200009) { 
                                            packageSize_volume = "m";
                                        }
                                        else if (weight_volume <= 25000) { 
                                            packageSize_volume = "l";
                                        }
                                   
                                   
                                    if (comments.Length > 2000)
                                    {
                                        comments = comments.ToString().Substring(0, 2000);
                                    }
                                    comments = comments.ToString().Replace("\r\n", " ");
                                    comments = comments.ToString().Replace("\n", " ");


                                    var AddressFrom99 = drRemitente["address_1"].ToString();
                                    AddressFrom99 = AddressFrom99 + " " +  drRemitente["address_2"].ToString();
                                    AddressFrom99 = AddressFrom99 + " " + drRemitente["city"].ToString();
                                    AddressFrom99 = AddressFrom99 + " " + drRemitente["state"].ToString();
                                    AddressFrom99 = AddressFrom99 + " " + drRemitente["zipcode"].ToString();
                                    AddressFrom99 = AddressFrom99.ToString().Replace("\r\n", " ");
                                    AddressFrom99 = AddressFrom99.ToString().Replace("\n", " ");

                                    var numberOrigin99 = drRemitente["address_1"].ToString() + "  " + drRemitente["address_2"].ToString();
                                            
                                    var Addressto99 = shipping_address1;
                                    Addressto99 = Addressto99 + " " + shipping_address2;
                                    Addressto99 = Addressto99 + " " + shipping_city;
                                    Addressto99 = Addressto99 + " " + shipping_state;
                                    Addressto99 = Addressto99 + " " + to_postalcode;
                                    Addressto99 = Addressto99 + " " + to_postalcode;
                                    Addressto99 = Addressto99 + " " + shipping_neighborhood;
                                    Addressto99 = Addressto99.ToString().Replace("\r\n", " ");
                                    Addressto99 = Addressto99.ToString().Replace("\n", " ");
                                    var numberTo99 = shipping_address1 + "  " + shipping_address2;


                                    var _99Minutos_create = modelo99min.CreaGuia(new ClsEnvia99Minutos                                
                                    {
                                        DeliveryType = code_final.ToString(),
                                        PackageSize   = packageSize_volume.ToString(),
                                        Notes = comments,
                                        CahsOnDelivery = "False",
                                        AmountCash = 0,
                                        SecurePackage = false,
                                        AmountSecure =0,
                                        ReceivedId = "",
                                        EnviaOrigin = new EnviaOrigin
                                                {
                                                   Sender = drRemitente["contact_name"].ToString(),
                                                   NameSender = drRemitente["contact_name"].ToString(),
                                                   LastNameSender = drRemitente["contact_name"].ToString(),
                                                   EmailSender = drRemitente["contact_email"].ToString(),
                                                   PhoneSender = drRemitente["contact_phone"].ToString(),
                                                   AddressOrigin = AddressFrom99,
                                                   NumberOrigin = numberOrigin99,
                                                   CodePostalOrigin = drRemitente["zipcode"].ToString(),                                                   
                                            EnviaCountry = "MEX"

                                        },
                                        EnviaDestination = new EnviaDestination
                                                {
                                                    Receiver = shipping_recipient,
                                                    NameReceiver = shipping_recipient,
                                                    LastNameReceiver = shipping_recipient,
                                                    EmailReceiver = "-",
                                                    PhoneReceiver = shipping_phone,
                                                    AddressDestination = Addressto99,
                                                    NumberDestination = numberTo99,
                                                    CodePostalDestination = to_postalcode,
                                                    EnviaCountry ="MEX"
                                                }
                                    }, reference, so);

                                            if (_99Minutos_create != null)
                                            {
                                                if (_99Minutos_create.Message[0].MessageMessage == "Creado")
                                                {

                                                    var tracking_number = _99Minutos_create.Message[0].Reason.Counter;
                                                    var Trackingid = _99Minutos_create.Message[0].Reason.Trackingid;
                                                    var clienid = _99Minutos_create.Message[0].Reason.Clienid;
                                                    var created = _99Minutos_create.Message[0].Reason.Created;
                                                    var _99MinutosPDF = modelo99min.CreaPDF(new ClsEnvioPdf99Minutos
                                                    {
                                                        Counter = tracking_number,
                                                        Base64 = true,
                                                        Size = "zebra",
                                                        Orientation = "vertical"
                                                    }, reference, so);

                                                    if (_99MinutosPDF != null)
                                                    {
                                                        tracking_number_carrier = tracking_number.ToString();
                                                        base_64_carrier = _99MinutosPDF.Pdf;
                                                        base_64_carrier = base_64_carrier.Replace("b'", "");
                                                        base_64_carrier = base_64_carrier.Replace("'", "");
                                                        carrier_method = provider_;
                                                        carrier_service_type = code_final;
                                                        carrier_aumount = amount_list_1[0].Costo.ToString();
                                                        log.EscribeLog("Tracking number: " + tracking_number_carrier);
                                                        log.EscribeLog("Nombre: " + shipping_recipient);
                                                        log.EscribeLog("Direccion: " + shipping_address1 + " " + shipping_address2);
                                                    }
                                                }
                                                else
                                                    log.EscribeLog("99Min mando error o no tiene sin cobertura.");
                                            }
                                            break;                                         
                                #endregion
                           }
                           //declaramos variables finales para editar el pdf
                           var final_tracking_number = tracking_number_carrier;
                           var final_carrier = carrier_method;
                           var final_service_type = carrier_service_type;
                           var final_aumount = carrier_aumount;
                           /*creamos txt y guardamos en ubicacion*/
                           var pdf_base64_ = base_64_carrier;
                           var pdf_base64 = pdf_base64_;
                           if (pdf_base64.Length < 10)
                              pdf_base64 = "0";
                           if (pdf_base64 == "0" || pdf_base64 == string.Empty)
                              log.EscribeLog("No se descargo guia correctamente, no se puede enviar pedido.");
                           else
                           {
                              cotizaciones.SaleOrderTrackingNumber_addlog(so, final_tracking_number, pdf_base64);
                              //Se guarda informacion en shippinglabelinfo
                              cotizaciones.ShippingLabelInfo_addlog(so, final_tracking_number, final_carrier, final_service_type, double.Parse(final_aumount), "1", 1, "Creador .Net " + final_carrier);
                              if(otraguia.Length>0)
                                 cotizaciones.ShippingLabelInfo_addlog(so, otraguia, final_carrier, final_service_type, double.Parse(final_aumount), "1", 1, "Creador .Net " + final_carrier);
                              cotizaciones.UpdSOH(so, final_tracking_number, guias);
                              cotizaciones.UpdMerchantOrderHeader("shipment_provider='" + final_carrier + "'", "reference_order_number='" + reference + "'");
                              var dtcarrier = cn.TraeDataTable("SELECT * FROM carrier WHERE carrier_name='" + final_carrier + "'", new MySqlParameter[] { }, CommandType.Text);
                              var carrier_id = dtcarrier.Rows[0]["carrier_id"].ToString();
                              cotizaciones.UpdMerchantOrderHeader("carrier_id=" + carrier_id,"reference_order_number='" + reference + "'");
                           }
                           //Si los pedidos se asginaron correctamente
                           cont++;
                           log.EscribeLog("Guia Generada ");
                        }
                     }
                  }
                  else
                  {
                     //Si no se puede asginar por cantidad permitada manda este mensaje
                     log.EscribeLog("No se puede asignar, el quantity es mayor al package_quantity.");
                  }
               }
               log.EscribeLog("----------");
            }
         }
         catch (FaultException fex)
         {
            log.EscribeLog("Error: " + fex.Message + " " + fex.Reason + " " + fex.StackTrace);
         }
         catch (WebException wex)
         {
            log.EscribeLog("Error: " + wex.Message + " " + wex.Response);
         }
         catch (Exception ex)
         {
            log.EscribeLog("Error: " + ex.Message + " " + ex.StackTrace);
         }
      }
   }
}
