using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using MySqlConnector;
using Newtonsoft.Json;
using RestSharp;

namespace AsignadorKits_Almex_ML
{
   public class clsMercadoLibre
   {
      public string access_token { get; set; }
      public string token_type { get; set; }
      public int expires_in { get; set; }
      public string scope { get; set; }
      public List<string> organization { get; set; }
      public string jti { get; set; }
   }

   public class mdlMercadoLibre
   {
      public string Token { get; set; }
      public string Login()
      {
         try
         {
            var cn = new clsConexion();
            var dt = cn.TraeDataTable("SELECT value FROM m_configuration WHERE name = 'MLM_ACCESS_TOKEN_TOML'", new MySqlParameter[] { }, CommandType.Text);
            var dr = dt.Rows[0];
            Token = dr["value"].ToString();
         }
         catch (Exception ex)
         {
            Token = "0";
         }
         return Token;
      }
      public clsPedidoMercadoLibre GetOrder(string pedido)
      {
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/orders/" + pedido + "?access_token=" + Token);
            var request = new RestRequest("", Method.GET, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            var response = client.Execute(request);
            var respuesta = JsonConvert.DeserializeObject<clsPedidoMercadoLibre>(response.Content);
            return respuesta;
         }
         catch (Exception ex)
         {
            return null;
         }
      }

      public clsPedidoMercadoLibre2 GetOrder2(string pedido)
      {
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/orders/" + pedido + "?access_token=" + Token);
            var request = new RestRequest("", Method.GET, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            var response = client.Execute(request);
            var respuesta = JsonConvert.DeserializeObject<clsPedidoMercadoLibre2>(response.Content);
            return respuesta;
         }
         catch (Exception ex)
         {
            return null;
         }
      }

      public clsShipmentMercadoLibre GetShipmentInfo(long id)
      {
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/shipments/" + id + "?access_token=" + Token);
            var request = new RestRequest("", Method.GET, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            var response = client.Execute(request);
            var respuesta = JsonConvert.DeserializeObject<clsShipmentMercadoLibre>(response.Content);
            return respuesta;
         }
         catch (Exception ex)
         {
            return null;
         }
      }

      public int ActualizaEstatus(clsPedidoMercadoLibre pedido, clsShipmentMercadoLibre shipment)
      {
         var valor = 0;
         try
         {
            var cn = new clsConexion();
            var shipment_provider = string.Empty;
            var shipping_status = string.Empty;
            var sale_order_type = 0;
            var dtpedido = cn.TraeDataTable(@"select `soh`.`sale_order_id`                                          AS `sale_order_id`,
       `soh`.`customer_id`                                            AS `customer_id`,
       `c`.`customer_name`                                            AS `customer_name`,
       `c`.`customer_phone`                                           AS `customer_phone`,
       `c`.`customer_address1`                                        AS `customer_address1`,
       `c`.`customer_address2`                                        AS `customer_address2`,
       `c`.`customer_address3`                                        AS `customer_address3`,
       `c`.`customer_taxid`                                           AS `customer_taxid`,
       `c`.`grouptype`                                                AS `grouptype`,
       `soh`.`user_id`                                                AS `user_id`,
       `u`.`user_name`                                                AS `user_name`,
       `soh`.`sale_order_type_id`                                     AS `sale_order_type_id`,
       `sot`.`order_sale_name`                                        AS `sale_order_type_name`,
       `soh`.`payment_id`                                             AS `payment_id`,
       `sopl`.`payment_name`                                          AS `payment_name`,
       `soh`.`sale_order_status_id`                                   AS `sale_order_status_id`,
       `sos`.`status_name`                                            AS `status_name`,
       `soh`.`carrier_id`                                             AS `carrier_id`,
       `cc`.`carrier_name`                                            AS `carrier_name`,
       `soh`.`date_add`                                               AS `date_add`,
       `soh`.`shipping_recipient`                                     AS `shipping_recipient`,
       `soh`.`shipping_address1`                                      AS `shipping_address1`,
       `soh`.`shipping_address2`                                      AS `shipping_address2`,
       `soh`.`shipping_city`                                          AS `shipping_city`,
       `soh`.`shipping_zipcode`                                       AS `shipping_zipcode`,
       `soh`.`shipping_phone`                                         AS `shipping_phone`,
       `soh`.`shipping_cost`                                          AS `shipping_cost`,
       `soh`.`comments`                                               AS `comments`,
       `soh`.`linio_order_number`                                     AS `linio_order_number`,
       `soh`.`ml_order_number`                                        AS `ml_order_number`,
       `soh`.`reference_order_number`                                 AS `reference_order_number`,
       `soh`.`shipment_provider`                                      AS `shipment_provider`,
       `soh`.`shipping_status`                                        AS `shipping_status`,
       `soh`.`shipping_substatus`                                     AS `shipping_substatus`,
       ifnull(`soh`.`tracking_number`, IFNULL((select tracking_number from shipping_label_info where sale_order_id = `soh`.`sale_order_id` limit 1),'') ) AS `tracking_number`
from `merchantu`.`sale_order_header` `soh`
   join `merchantu`.`customer` `c` on `soh`.`customer_id` = `c`.`customer_id`
   join `merchantu`.`user` `u` on `soh`.`user_id` = `u`.`user_id`
   join `merchantu`.`sale_order_type` `sot` on `soh`.`sale_order_type_id` = `sot`.`sale_order_type_id`
   join `merchantu`.`sale_order_payment_list` `sopl` on `soh`.`payment_id` = `sopl`.`payment_id`
   join `merchantu`.`sale_order_status` `sos` on `soh`.`sale_order_status_id` = `sos`.`sale_order_status_id`
        join `merchantu`.`carrier` `cc` on `soh`.`carrier_id` = `cc`.`carrier_id` WHERE soh.reference_order_number='" + pedido.id + "'", new MySqlParameter[] { }, CommandType.Text);
            var drpedido = dtpedido.Rows[0];
            shipment_provider = shipment.mode == "custom" ? "custom" : shipment.tracking_method;
            // validamos estatus principal, si cancelado, cancelamos pedido
            if (pedido.status == "cancelled")
               shipping_status = "cancelled";
            else
            {
               if (string.IsNullOrEmpty(shipment.status))
                  shipping_status = pedido.status;
               else
               {
                  shipping_status = shipment.status.Length <= 2 ? pedido.status : shipment.status;
               }
            }
            //validacion logistic type = fulfillment
            sale_order_type = shipment.logistic_type == "fulfillment" ? 3 : 1;
            if (drpedido["tracking_number"].ToString().Length <= 0)
            {
               valor = cn.EjecutaConsulta("UPDATE sale_order_header SET shipment_provider = @shipment_provider, shipping_status=@shipping_status, tracking_number=@tracking_number, shipping_id_number=@shipping_id_number, shipping_substatus=@shipping_substatus, sale_order_type_id=@sale_order_type_id WHERE reference_order_number=@reference_order_number", new[]
               {
                  new MySqlParameter("@shipment_provider",shipment_provider),
                  new MySqlParameter("@shipping_status",shipping_status),
                  new MySqlParameter("@tracking_number",shipment.tracking_number),
                  new MySqlParameter("@shipping_id_number",pedido.shipping.id),
                  new MySqlParameter("@shipping_substatus",shipment.substatus),
                  new MySqlParameter("@sale_order_type_id",sale_order_type),
                  new MySqlParameter("@reference_order_number",pedido.id)
               }, CommandType.Text);
            }
            else
            {
               valor = cn.EjecutaConsulta("UPDATE sale_order_header SET shipping_status=@shipping_status,  shipping_id_number=@shipping_id_number, shipping_substatus=@shipping_substatus, sale_order_type_id=@sale_order_type_id WHERE reference_order_number=@reference_order_number", new[]
               {
                  new MySqlParameter("@shipping_status",shipping_status),
                  new MySqlParameter("@shipping_id_number",pedido.shipping.id),
                  new MySqlParameter("@shipping_substatus",shipment.substatus),
                  new MySqlParameter("@sale_order_type_id",sale_order_type),
                  new MySqlParameter("@reference_order_number",pedido.id)
               }, CommandType.Text);
            }
         }
         catch (Exception ex)
         {
         }
         return valor;
      }
      public int ActualizaEstatus2(clsPedidoMercadoLibre2 pedido, clsShipmentMercadoLibre shipment)
      {
         var valor = 0;
         try
         {
            var cn = new clsConexion();
            var shipment_provider = string.Empty;
            var shipping_status = string.Empty;
            var sale_order_type = 0;
            var dtpedido = cn.TraeDataTable(@"select `soh`.`sale_order_id`                                          AS `sale_order_id`,
       `soh`.`customer_id`                                            AS `customer_id`,
       `c`.`customer_name`                                            AS `customer_name`,
       `c`.`customer_phone`                                           AS `customer_phone`,
       `c`.`customer_address1`                                        AS `customer_address1`,
       `c`.`customer_address2`                                        AS `customer_address2`,
       `c`.`customer_address3`                                        AS `customer_address3`,
       `c`.`customer_taxid`                                           AS `customer_taxid`,
       `c`.`grouptype`                                                AS `grouptype`,
       `soh`.`user_id`                                                AS `user_id`,
       `u`.`user_name`                                                AS `user_name`,
       `soh`.`sale_order_type_id`                                     AS `sale_order_type_id`,
       `sot`.`order_sale_name`                                        AS `sale_order_type_name`,
       `soh`.`payment_id`                                             AS `payment_id`,
       `sopl`.`payment_name`                                          AS `payment_name`,
       `soh`.`sale_order_status_id`                                   AS `sale_order_status_id`,
       `sos`.`status_name`                                            AS `status_name`,
       `soh`.`carrier_id`                                             AS `carrier_id`,
       `cc`.`carrier_name`                                            AS `carrier_name`,
       `soh`.`date_add`                                               AS `date_add`,
       `soh`.`shipping_recipient`                                     AS `shipping_recipient`,
       `soh`.`shipping_address1`                                      AS `shipping_address1`,
       `soh`.`shipping_address2`                                      AS `shipping_address2`,
       `soh`.`shipping_city`                                          AS `shipping_city`,
       `soh`.`shipping_zipcode`                                       AS `shipping_zipcode`,
       `soh`.`shipping_phone`                                         AS `shipping_phone`,
       `soh`.`shipping_cost`                                          AS `shipping_cost`,
       `soh`.`comments`                                               AS `comments`,
       `soh`.`linio_order_number`                                     AS `linio_order_number`,
       `soh`.`ml_order_number`                                        AS `ml_order_number`,
       `soh`.`reference_order_number`                                 AS `reference_order_number`,
       `soh`.`shipment_provider`                                      AS `shipment_provider`,
       `soh`.`shipping_status`                                        AS `shipping_status`,
       `soh`.`shipping_substatus`                                     AS `shipping_substatus`,
       ifnull(`soh`.`tracking_number`, (select `merchantu`.`shipping_label_info`.`tracking_number`
                                                from `merchantu`.`shipping_label_info`
                                                where `soh`.`sale_order_id` = `soh`.`sale_order_id`
                                                limit 1) ) AS `tracking_number`
from `merchantu`.`sale_order_header` `soh`
   join `merchantu`.`customer` `c` on `soh`.`customer_id` = `c`.`customer_id`
   join `merchantu`.`user` `u` on `soh`.`user_id` = `u`.`user_id`
   join `merchantu`.`sale_order_type` `sot` on `soh`.`sale_order_type_id` = `sot`.`sale_order_type_id`
   join `merchantu`.`sale_order_payment_list` `sopl` on `soh`.`payment_id` = `sopl`.`payment_id`
   join `merchantu`.`sale_order_status` `sos` on `soh`.`sale_order_status_id` = `sos`.`sale_order_status_id`
        join `merchantu`.`carrier` `cc` on `soh`.`carrier_id` = `cc`.`carrier_id` WHERE soh.reference_order_number='" + pedido.id + "'", new MySqlParameter[] { }, CommandType.Text);
            var drpedido = dtpedido.Rows[0];
            shipment_provider = shipment.mode == "custom" ? "custom" : shipment.tracking_method;
            // validamos estatus principal, si cancelado, cancelamos pedido
            if (pedido.status == "cancelled")
               shipping_status = "cancelled";
            else
            {
               shipping_status = shipment.status.Length <= 2 ? pedido.status : shipment.status;
            }
            //validacion logistic type = fulfillment
            sale_order_type = shipment.logistic_type == "fulfillment" ? 3 : 1;
            if (drpedido["tracking_number"].ToString().Length <= 0)
            {
               valor = cn.EjecutaConsulta("UPDATE sale_order_header SET shipment_provider = @shipment_provider, shipping_status=@shipping_status, tracking_number=@tracking_number, shipping_id_number=@shipping_id_number, shipping_substatus=@shipping_substatus, sale_order_type_id=@sale_order_type_id WHERE reference_order_number=@reference_order_number", new[]
               {
                  new MySqlParameter("@shipment_provider",shipment_provider),
                  new MySqlParameter("@shipping_status",shipping_status),
                  new MySqlParameter("@tracking_number",shipment.tracking_number),
                  new MySqlParameter("@shipping_id_number",pedido.shipping.id),
                  new MySqlParameter("@shipping_substatus",shipment.substatus),
                  new MySqlParameter("@sale_order_type_id",sale_order_type),
                  new MySqlParameter("@reference_order_number",pedido.id)
               }, CommandType.Text);
            }
            else
            {
               valor = cn.EjecutaConsulta("UPDATE sale_order_header SET shipping_status=@shipping_status,  shipping_id_number=@shipping_id_number, shipping_substatus=@shipping_substatus, sale_order_type_id=@sale_order_type_id WHERE reference_order_number=@reference_order_number", new[]
               {
                  new MySqlParameter("@shipping_status",shipping_status),
                  new MySqlParameter("@shipping_id_number",pedido.shipping.id),
                  new MySqlParameter("@shipping_substatus",shipment.substatus),
                  new MySqlParameter("@sale_order_type_id",sale_order_type),
                  new MySqlParameter("@reference_order_number",pedido.id)
               }, CommandType.Text);
            }
         }
         catch (Exception ex)
         {
         }
         return valor;
      }

      public string ManipulatePdf(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSizeWithRotation(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(pageSize.Width / 8 * 7, pageSize.Height / 8 * 7); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize.Rotate(), 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
            for (var i = 1; i <= pageCount; i++)
            {
               document.NewPage();
               var page = pdfWriter.GetImportedPage(pdfReader, i);
               var image = Image.GetInstance(page);
               //image.RotationDegrees = 90;
               image.ScalePercent(87);
               image.SetAbsolutePosition(0, 0);
               document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }

      public string ManipulatePdfRedPack(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSize(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(CmAUnits(10), CmAUnits(20)); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize, 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
               for (var i = 1; i <= pageCount; i++)
               {
                  document.NewPage();
                  var page = pdfWriter.GetImportedPage(pdfReader, i);
                  var image = Image.GetInstance(page);
               //image.RotationDegrees = 90;
               image.ScalePercent(98); //87
                  image.SetAbsolutePosition(0, 0);
                  document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }

      public string ManipulatePdfPaqueteExpress(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSize(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(CmAUnits(10), CmAUnits(20)); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize, 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
            for (var i = 1; i <= pageCount; i++)
            {
               document.NewPage();
               var page = pdfWriter.GetImportedPage(pdfReader, i);
               var image = Image.GetInstance(page);
               //image.RotationDegrees = 100;
               image.ScalePercent(97);
               image.SetAbsolutePosition(-25, -230);
               document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }

      private float CmAUnits(float cm)
      {
         return (cm / 2.54f) * 72f;
      }

      public string GetLabelPDF(long shipmentId)
      {
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/shipment_labels?shipment_ids=" + shipmentId + "&response_type=pdf&access_token=" + Token);
            var request = new RestRequest("", Method.GET, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            var response = client.Execute(request);
            return Convert.ToBase64String(response.RawBytes);
         }
         catch (Exception ex)
         {
            return "0";
         }
      }

      public string ManipulatePdfDHL(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSize(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(CmAUnits(10), CmAUnits(20)); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize, 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
            for (var i = 1; i <= pageCount-1; i++)
            {
               document.NewPage();
               var page = pdfWriter.GetImportedPage(pdfReader, i);
               var image = Image.GetInstance(page);
               //image.RotationDegrees = 90;
               image.ScalePercent(90);
               image.SetAbsolutePosition(-30, -200);
               document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }
      public string ManipulatePdfMEL(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSize(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(CmAUnits(10), CmAUnits(20)); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize, 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
            for (var i = 1; i <= pageCount - 1; i++)
            {
               document.NewPage();
               var page = pdfWriter.GetImportedPage(pdfReader, i);
               var image = Image.GetInstance(page);
               //image.RotationDegrees = 90;
               image.ScalePercent(98);
               image.SetAbsolutePosition(-20, -235);
               document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }
      public string ManipulatePdfEstafeta(string origenBase64, string sale_order_id)
      {
         try
         {
            var archivo = @"C:\MerchantExport\guias\" + sale_order_id + ".pdf";
            var pdfReader = new PdfReader(new MemoryStream(Convert.FromBase64String(origenBase64)));
            var pageSize = pdfReader.GetPageSize(1);
            var originalHeight = pageSize.Height;
            var originalWidth = pageSize.Width;
            var newSize = new Rectangle(CmAUnits(10), CmAUnits(20)); //PageSize.LETTER;
            var newHeight = newSize.Height;
            var newWidth = newSize.Width;
            var scaleHeight = newHeight / originalHeight;
            var scaleWidth = newWidth / originalWidth;
            var document = new Document(newSize, 0, 0, 0, 0);
            var pdfWriter = PdfWriter.GetInstance(document, new FileStream(archivo, FileMode.Create));
            pdfWriter.StrictImageSequence = true;
            document.Open();
            var pageCount = pdfReader.NumberOfPages;
            for (var i = 1; i <= pageCount - 1; i++)
            {
               document.NewPage();
               var page = pdfWriter.GetImportedPage(pdfReader, i);
               var image = Image.GetInstance(page);
               //image.RotationDegrees = 90;
               image.ScalePercent(85);
               image.SetAbsolutePosition(-30, -200);
               document.Add(image);
            }
            document.Close();
            return Convert.ToBase64String(File.ReadAllBytes(archivo));
         }
         catch (Exception e)
         {
            return "0";
         }
      }
      public clsRespuestaMensajeMercadoLibre EnviaMensaje(string pedido, string sale_order_id)
      {
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/messages/action_guide/packs/" + pedido + "/option");
            var request = new RestRequest("", Method.POST, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            var url = "https://mercadazo.com.mx/content/9-problemas-con-tu-compra";
            var urlfactura = "https://quieromifactura.mx/PROD/pages/?WEBID1=TME1_" + pedido;
            var mensaje = "Si tienes problemas o dudas con tu compra, ingresa:<br/><a href=\""+url+"\">"+url+"</a><br/>Para facturar haz click en la siguiente liga:<br/><a href=\"" + urlfactura + "\">" + urlfactura + "</a>";
            var envia = new
            {
               option_id = "OTHER",
               text = mensaje
            };
            request.AddJsonBody(envia);
            var response = client.Execute(request);
            var cn = new clsConexion();
            cn.EjecutaConsulta("INSERT INTO pcg_request (request_str, response_str, purchase_order_id, sale_order_id, date_created, source) VALUES (@request_str, @response_str, @purchase_order_id, @sale_order_id, NOW(), @source)", new []
            {
               new MySqlParameter("@request_str",JsonConvert.SerializeObject(envia)),
               new MySqlParameter("@response_str",response.Content),
               new MySqlParameter("@purchase_order_id",pedido),
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@source","Mensaje ML")
            }, CommandType.Text);
            var respuesta = JsonConvert.DeserializeObject<clsRespuestaMensajeMercadoLibre>(response.Content);
            return respuesta;
         }
         catch (Exception ex)
         {
            return null;
         }
      }

      public string MeliUpdOrderTracking(int sale_order_id, string reference_order_number, string shipping_id_number, string tracking_number, string carrier)
      {
         string rawResponse, receiver_id;
         var envio = string.Empty;
         var cn = new clsConexion();
         try
         {
            var dt = cn.TraeDataTable("SELECT buyer_id FROM m_meliorder WHERE meli_oid = " + reference_order_number, new MySqlParameter[] { }, CommandType.Text);
            receiver_id = dt.Rows[0]["buyer_id"].ToString();
            using (var httpClient = new HttpClient())
            {
               using (var request = new HttpRequestMessage(new HttpMethod("PUT"), "https://api.mercadolibre.com/shipments/" + shipping_id_number))
               {
                  request.Headers.TryAddWithoutValidation("Authorization", "Bearer "+Token);
                  request.Headers.TryAddWithoutValidation("Accept", "application/json");
                  envio = "{\"speed\": 240,\"status\":\"shipped\",\"tracking_number\": " + carrier + tracking_number + ",\"receiver_id\": " + receiver_id + "}";
                  request.Content = new StringContent(envio);
                  request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                  var response = httpClient.SendAsync(request).Result;
                  rawResponse = response.Content.ReadAsStringAsync().Result;
                  cn.EjecutaConsulta("INSERT INTO pcg_request (request_str, response_str, purchase_order_id, sale_order_id, date_created, source) VALUES (@request_str, @response_str, @purchase_order_id, @sale_order_id, @date_created, @source)", new[]
                  {
                     new MySqlParameter("@request_str",envio),
                     new MySqlParameter("@response_str",rawResponse),
                     new MySqlParameter("@purchase_order_id",reference_order_number),
                     new MySqlParameter("@sale_order_id",sale_order_id),
                     new MySqlParameter("@date_created", DateTime.Now),
                     new MySqlParameter("@source","ML")
                  }, CommandType.Text);
               }
            }
         }
         catch (WebException wex)
         {
            rawResponse = wex.Message;
            cn.EjecutaConsulta("INSERT INTO pcg_request (request_str, response_str, purchase_order_id, sale_order_id, date_created, source) VALUES (@request_str, @response_str, @purchase_order_id, @sale_order_id, @date_created, @source)", new[]
            {
               new MySqlParameter("@request_str",envio),
               new MySqlParameter("@response_str",wex.Message),
               new MySqlParameter("@purchase_order_id",reference_order_number),
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@date_created", DateTime.Now),
               new MySqlParameter("@source","ML")
            }, CommandType.Text);
         }
         catch (Exception ex)
         {
            rawResponse = ex.Message;
            cn.EjecutaConsulta("INSERT INTO pcg_request (request_str, response_str, purchase_order_id, sale_order_id, date_created, source) VALUES (@request_str, @response_str, @purchase_order_id, @sale_order_id, @date_created, @source)", new[]
            {
               new MySqlParameter("@request_str",envio),
               new MySqlParameter("@response_str",ex.Message),
               new MySqlParameter("@purchase_order_id",reference_order_number),
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@date_created", DateTime.Now),
               new MySqlParameter("@source","ML")
            }, CommandType.Text);
         }
         return rawResponse;
      }

      public string MeliSplitOrder(int sale_order_id, string reference_order_number, string shipping_id_number, string reason)
      {
         string rawResponse;
         try
         {
            var client = new RestClient("https://api.mercadolibre.com/shipments/" + shipping_id_number + "/split");
            var request = new RestRequest("", Method.POST, DataFormat.Json);
            request.AddHeader("Authorization", "Bearer " + Token);
            request.AddJsonBody(new clsEnvioSplitMercadoLibre
            {
               shipments = new List<ShipmentSPlitMercadoLibre>(new[]
               {
                  new ShipmentSPlitMercadoLibre
                  {
                     reason = reason,
                     description = reason,
                     orders = new List<OrderSplitMercadoLibre>(new[]
                     {
                        new OrderSplitMercadoLibre
                        {
                           id = reference_order_number
                        }
                     })
                  }
               })
            });
            var response = client.Execute(request);
            rawResponse = response.Content;
         }
         catch (WebException wex)
         {
            rawResponse = wex.Message;
         }
         catch (Exception ex)
         {
            rawResponse = ex.Message;
         }
         return rawResponse;
      }
   }
}
