using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.ServiceModel;
using CreateLabel_ML.wsEstafeta;
using CreateLabel_ML.wsFedexRate;
using CreateLabel_ML.wsFedexShip;
using MySqlConnector;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System.Collections.Generic;

namespace CreateLabel_ML
{
   public class Cotizaciones
   {
      public DataTable GetLabelInfo_track(string where)
      {
         var cn=new clsConexion();
         var dt=cn.TraeDataTable("SELECT * FROM shipping_label_info WHERE "+where,new MySqlParameter[]{},CommandType.Text);
         return dt;
      }

      public RateReply Fedex_quote(RateRequest data_fedex, string reference, string so)
      {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         var log = new clsLog();
         var ws = new RatePortTypeClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport), new EndpointAddress("https://ws.fedex.com:443/web-services/rate"));
         var fedex_cotizacion = ws.getRatesAsync(data_fedex).Result;
         log.AgregaPcgRequest(JsonConvert.SerializeObject(data_fedex), JsonConvert.SerializeObject(fedex_cotizacion), reference, so, "Creador .Net Fedex");
         return fedex_cotizacion.RateReply;
      }

      public ProcessShipmentReply CreatedlabelFedex(ProcessShipmentRequest json_fedex, string reference, string so)
      {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         var log = new clsLog();
         var ws = new ShipPortTypeClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport), new EndpointAddress("https://ws.fedex.com:443/web-services/ship"));
         var fedex_created = ws.processShipmentAsync(json_fedex).Result;
         log.AgregaPcgRequest(JsonConvert.SerializeObject(json_fedex), JsonConvert.SerializeObject(fedex_created), reference, so, "Creador .Net Fedex");
         return fedex_created.ProcessShipmentReply;
      }

        public bool CreaCartaPorte(DataRow origen, DataRow destino, DataRow producto, string sale_order_id, string reference, string tracking_number)
        {
            try
            {
                Destino _Origen = new Destino()
                {
                    IdOrigen = origen["warehouse_id"].ToString(),
                    NombreRemitente = "TIENDA MERCADAZO",
                    RfcRemitente = "TME120322EQ6",
                    NumRegIdTrib = "TME120322EQ6",
                    ResidenciaFiscal = "MEX",
                    NumEstacion = "",
                    NombreEstacion = "",
                    FechaHoraSalida = ""
                };
                Domicilio _DomicilioOrigen = new Domicilio()
                {
                    Calle = "Av Barranca Honda Nave 3 San Martin Obispo II",
                    NumeroExterior = 0,
                    NumeroInterior = 0,
                    Colonia = 0,
                    Localidad = "",
                    Referencia = "",
                    Municipio = 0,
                    Estado = origen["state_2"].ToString(),
                    Pais = "MEX",
                    CodigoPostal = int.Parse(origen["zipcode_2"].ToString())
                };

                Destino _Destino = new Destino()
                {
                    IdOrigen = destino["sale_order_id"].ToString(),
                    NombreDestinatario = destino["shipping_recipient"].ToString(),
                    RfcDestinatario = "XAXX010101000",
                    NumRegIdTrib = "XAXX010101000",
                    ResidenciaFiscal = "MEX",
                    NumEstacion = "",
                    NombreEstacion = "",
                    FechaHoraSalida = ""
                };

                string calle = destino["shipping_address1"].ToString() + " " + destino["shipping_address1"].ToString();
                if (calle.Length > 100)
                {
                    calle = calle.Substring(1, 100);
                }


                Domicilio _DomicilioDestino = new Domicilio()
                {
                    Calle = calle,
                    NumeroExterior = 0,
                    NumeroInterior = 0,
                    Colonia = 0,
                    Localidad = "",
                    Referencia = "",
                    Municipio = 0,
                    Estado = destino["state"].ToString(),
                    Pais = "MEX",
                    CodigoPostal = int.Parse(destino["zipcode"].ToString())
                };

                Ubicacion _UbicacionOrigen = new Ubicacion()
                {
                    Origen = _Origen,
                    Domicilio = _DomicilioOrigen
                };


                Ubicacion _UbicacionDestino = new Ubicacion
                {
                    Destino = _Destino,
                    Domicilio = _DomicilioDestino
                };


                Ubicaciones _Ubicaciones = new Ubicaciones()
                {
                    Ubicacion = new List<Ubicacion>(),
                };

                _Ubicaciones.Ubicacion.Add(_UbicacionOrigen);
                _Ubicaciones.Ubicacion.Add(_UbicacionDestino);


                Mercancia _Mercancia = new Mercancia()
                {
                    BienesTransp = int.Parse(producto["category_id"].ToString()),
                    Descripcion = producto["product_name"].ToString(),
                    Cantidad = int.Parse(destino["quantity"].ToString()),
                    ClaveUnidad = "H87",
                    Unidad = "Piezas",
                    Dimensiones = "",
                    MaterialPeligroso = "",
                    CveMaterialPeligroso = "",
                    Embalaje = "4G",
                    DescripEmbalaje = "Cajas de Cartón",
                    PesoEnKg = producto["weight"].ToString(),
                    ValorMercancia = destino["total_cost_tax_inc"].ToString(),
                    Moneda = "MXN",
                    FraccionArancelaria = "",
                    UuidComercioExt = ""
                };

                Mercancias _Mercancias = new Mercancias()
                {
                    NumTotalMercancias = int.Parse(destino["quantity"].ToString()),
                    Mercancia = new List<Mercancia>(),
                };

                _Mercancias.Mercancia.Add(_Mercancia);

                CustomerCartaPorteFdx customercartaportefdx = new CustomerCartaPorteFdx()
                {
                    Guia = tracking_number,
                    Ubicaciones = _Ubicaciones,
                    Mercancias = _Mercancias,
                };

                AtributosEnvioCartaPorteFedex atributosenviocartaportefedex = new AtributosEnvioCartaPorteFedex()
                {
                    Comment = "",
                    CustomerCartaPorteFdx = customercartaportefdx,
                };


                var client = new RestClient("https://ws.fedex.com/LAC/ServicesAPI/mx/cartaporte/customers");
                var request = new RestRequest("", Method.POST, DataFormat.Json);
                request.AddHeader("cache-control", "no-cache");
                request.AddJsonBody(JsonConvert.SerializeObject(atributosenviocartaportefedex));
                var response = client.Execute(request);
                //log.AgregaPcgRequest(JsonConvert.SerializeObject(envio), JsonConvert.SerializeObject(response.Content), reference, so, "Creador .Net 99Minutos");
                string respuesta = response.Content;

                JObject json = new JObject();
                json = JObject.Parse(respuesta);

                string json_response = (string)json.SelectToken("status");

                if (json_response == "200")
                {
                    return true;
                }
                else
                {
                    return false;
                }
                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(atributosenviocartaportefedex)),
                  new MySqlParameter("@response_str", respuesta),
                  new MySqlParameter("@purchase_order_id", reference),
                  new MySqlParameter("@sale_order_id", sale_order_id),
                  new MySqlParameter("@source", "Merch Fedex - Carta Porte")
                   }, CommandType.Text);
            }
            catch (System.Exception ex)
            {
                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", "Error al serializar Carta porte" + ex.Message),
                  new MySqlParameter("@response_str", ""),
                  new MySqlParameter("@purchase_order_id", reference),
                  new MySqlParameter("@sale_order_id", sale_order_id),
                  new MySqlParameter("@source", "Merch Fedex - Carta Porte")
                   }, CommandType.Text);
                return false;
            }
        }

        public clsRespuestaSrEnvios Quote_SrEnvios(clsSrEnvios data_srenvios_from, string reference, string so)
      {
         var log = new clsLog();
         var wsSrEnvios = new RestClient(ConfigurationManager.AppSettings["UrlSrEnvios"])
         {
            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
         };
         var enviaSrEnvios = new RestRequest("shipments", Method.POST, DataFormat.Json);
         enviaSrEnvios.AddHeader("Authorization", ConfigurationManager.AppSettings["AuthorizationSrEnvios"]);
         enviaSrEnvios.AddJsonBody(data_srenvios_from);
         var curlPostSrEnvios = wsSrEnvios.Execute(enviaSrEnvios);
         log.AgregaPcgRequest(JsonConvert.SerializeObject(data_srenvios_from), curlPostSrEnvios.Content, reference, so, "Creador .Net SrEnvios");
         var srenvios_cotizacion = JsonConvert.DeserializeObject<clsRespuestaSrEnvios>(curlPostSrEnvios.Content);
         return srenvios_cotizacion;
      }


        public clsRespuestaEtiquetaSrEnvios CreatedlabelSrEnvios(clsEtiquetaSrEnvios enviaEtiquetaSrEnvios, string reference, string so)
      {
         var log = new clsLog();
         var wsSrEnvios = new RestClient(ConfigurationManager.AppSettings["UrlSrEnvios"])
         {
            RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
         };
         var enviaSrEnvios = new RestRequest("labels", Method.POST, DataFormat.Json);
         enviaSrEnvios.AddHeader("Authorization", ConfigurationManager.AppSettings["AuthorizationSrEnvios"]);
         enviaSrEnvios.AddJsonBody(enviaEtiquetaSrEnvios);
         var curlPostSrEnvios = wsSrEnvios.Execute(enviaSrEnvios);
         log.AgregaPcgRequest(JsonConvert.SerializeObject(enviaEtiquetaSrEnvios), curlPostSrEnvios.Content, reference, so, "Creador .Net SrEnvios");
         //se retorna el json y se decodifica
         var srenvios_created = JsonConvert.DeserializeObject<clsRespuestaEtiquetaSrEnvios>(curlPostSrEnvios.Content);
         return srenvios_created;
      }

      public EstafetaLabelResponse CreatedlabelEstafeta(EstafetaLabelRequest estafeta_xml, string reference, string so)
      {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         var log = new clsLog();
         var ws = new EstafetaLabelClient(new BasicHttpsBinding(BasicHttpsSecurityMode.Transport), new EndpointAddress("https://label.estafeta.com/EstafetaLabel20/services/EstafetaLabelWS"));
         var response_created_label_estafeta = ws.createLabelAsync(estafeta_xml).Result;
         log.AgregaPcgRequest(JsonConvert.SerializeObject(estafeta_xml), JsonConvert.SerializeObject(response_created_label_estafeta), reference, so, "Creador .Net Estafeta");
         return response_created_label_estafeta;
      }

      public void SaleOrderTrackingNumber_addlog(string sale_order_id, string tracking_number, string tracking_base64)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("INSERT INTO sale_order_tracking_number (sale_order_id, tracking_number, tracking_base64, date_created) VALUES (@sale_order_id, @tracking_number, @tracking_base64, NOW())",
            new[]
            {
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@tracking_number",tracking_number),
               new MySqlParameter("@tracking_base64",tracking_base64)
            }, CommandType.Text);
      }

      public void ShippingLabelInfo_addlog(string sale_order_id, string tracking_number, string carrier_name, string service_type, double shipment_cost, string shipment_type, int user_id, string comments)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("INSERT INTO shipping_label_info (sale_order_id, tracking_number, carrier_name, service_type, shipment_cost, shipment_type, user_id, date_created, comments) VALUES (@sale_order_id, @tracking_number, @carrier_name, @service_type, @shipment_cost, @shipment_type, @user_id, NOW(), @comments)",
            new[]
            {
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@tracking_number",tracking_number),
               new MySqlParameter("@carrier_name",carrier_name),
               new MySqlParameter("@service_type",service_type),
               new MySqlParameter("@shipment_cost",shipment_cost),
               new MySqlParameter("@shipment_type",shipment_type),
               new MySqlParameter("@user_id",user_id),
               new MySqlParameter("@comments",comments)
            }, CommandType.Text);
      }

      public void UpdSOH(string sale_order_id, string tracking_number, byte guias)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("UPDATE sale_order_header SET tracking_number=@tracking_number, multiguia_flag=@multiguia_flag WHERE sale_order_id=@sale_order_id",
            new[]
            {
               new MySqlParameter("@sale_order_id",sale_order_id),
               new MySqlParameter("@tracking_number",tracking_number),
               new MySqlParameter("@multiguia_flag",guias>1?guias:0)
            }, CommandType.Text);
      }
      public void UpdMerchantOrderHeader(string set, string where)
      {
         var cn = new clsConexion();
         cn.EjecutaConsulta("UPDATE sale_order_header SET "+set+" WHERE "+where,new MySqlParameter[]{}, CommandType.Text);

      }
   }
}
