using System;
using System.Collections.Generic;
using System.Data;
using MySqlConnector;
using Newtonsoft.Json;
using RestSharp;

namespace ActualizarEstatusPaqueteriaTodos
{
   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(string 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;
      }

   }
}
