private void pdoc_PrintPage(PrintPageEventArgs e, newComanda lista, string impresoraDest)
        {
            log.Info("Solicitando pdoc_PrintPage de "+lista.ordn_id);
            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();
            SqlCommand command = null;
            Graphics graphics = e.Graphics;
            Font font = new Font(sFont, 9, FontStyle.Bold);
            int iMesaCliente = 0;

            try
            {
                myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["BaseComercial"].ConnectionString;
                myConnection.Open();
                command = new SqlCommand("select mesa_cve from mesa where mesa_id = (select mesa_id from orden where ordn_id=" + lista.ordn_id + ")", myConnection);
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    iMesaCliente = Convert.ToInt32(reader["mesa_cve"].ToString());
                }
            }
            catch (Exception extt)
            {
                log.Error("Error en pdoc_PrintPage en " + extt.Message);
            }
            //float fontHeight = font.GetHeight();
            double fontHeight_d = 8.7;
            float fontHeight = (float)fontHeight_d;
            int startX = 15;
            int startY = 15;
            int Offset = 10;
            //graphics.DrawImage(WindowsFormsApplication1.Properties.Resources.LOGO_CITYMARKET, 38, 0, 230, 100);
            //graphics.DrawImage(Image.FromFile(Application.StartupPath +"\\citymark2.png"), 38, 0, 230, 100);

            try { graphics.DrawImage(Image.FromFile(".\\citymark2.png"), 38, 0, 230, 100); }
            catch (Exception ex) {
                log.Error("Error pdoc_PrintPage tratando de agregar imagen en " + ex.Message);
            }

            Offset = Offset + 70;
            String numOrden = "No. de Orden " + lista.ordn_id;
            graphics.DrawString(numOrden, new Font(sFont, (float)8.6, FontStyle.Bold),
                                Brushes.Black, CentrarTexto(graphics, numOrden), startY + Offset);
            Offset = Offset + 20;
            graphics.DrawString("Cliente / Mesa:" + iMesaCliente,
                        new Font(sFont, (float)8.5, FontStyle.Regular), Brushes.Black, startX - 6, startY + Offset);
            Offset = Offset + 20;
            graphics.DrawString("Cant Articulo",
                        new Font(sFont, (float)8.5, FontStyle.Regular),
                        Brushes.Black, startX - 6, startY + Offset);
            Offset = Offset + 20;
            String underLine = "---------------------------------------";
            graphics.DrawString(underLine, new Font(sFont, (float)8.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);

            int iCantidadArticulos = 0;
            string sMesero = "";
            string sRestaurante = "";
            foreach (OrdenArticulo artOrd in lista.ordenarticulo)
            {
                List<Categoria> categorias = new List<Categoria>();
                List<Articulo> articulos = new List<Articulo>();
                List<Modificador> modificadores = new List<Modificador>();
                string sArticulo = "";
                string sModificador = "";
                List<string> listaDescripcionModificadores = null;
                try//EL SIGUEINTE BLOQUE ES PARA EXTRAER LAS CATEGORIAS
                {
                    command = new SqlCommand("select art_des from articulo where art_ean = " + artOrd.art_ean, myConnection);
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        sArticulo = reader["art_des"].ToString();
                        if (sArticulo.Length > 20)
                        {
                            sArticulo = sArticulo.Substring(0, 20);
                        }

                    }
                    listaDescripcionModificadores = new List<string>();
                    foreach (Modificadoresart modiff in artOrd.modificadores)
                    {

                        command = new SqlCommand("select agru_des from agrupacion_modif where agru_id = " + modiff.agru_id + " and agru_consec=" + modiff.agru_consec, myConnection);
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            sModificador = reader["agru_des"].ToString();
                            if (sModificador.Length > 18)
                            {
                                sModificador = sModificador.Substring(0, 18);
                            }//end if
                            listaDescripcionModificadores.Add(sModificador);
                        }//end while
                    }//end foreach

                }
                catch (Exception exc)
                {
                    log.Error("Error en pdoc_PrintPage-Categorias" + exc.Message);
                }

                Offset = Offset + 10;
                graphics.DrawString(artOrd.ordn_cant.ToString(), new Font(sFont, (float)8.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX + 10, startY + Offset);

                graphics.DrawString(sArticulo, new Font(sFont, (float)8.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX + 30, startY + Offset);
                if (artOrd.ordn_obsv != null && artOrd.ordn_obsv.Length > 3)
                {
                    Offset = Offset + 10;
                    string Obsvc = artOrd.ordn_obsv;
                    /*BLOQUE PARA CONTROLAR LA IMPRESION DE OBSERVACIONES*/
                    string obsvValidado = "";
                    int tammax = 25;
                    int tamobsv = Obsvc.Length;
                    if (tamobsv > tammax)
                    {
                        double oper = (tamobsv / tammax);
                        double dblCant = Math.Ceiling(oper) +1;
                        try
                        {
                            for (int y = 0; y < dblCant; y++)
                            {
                                double z = y * tammax;
                                int aa = (int)Math.Ceiling(z);
                                int bb = aa + tammax;

                                if(y+1< dblCant){
                                    obsvValidado = Obsvc.Substring(aa, tammax);
                                    //obsvValidado = Environment.NewLine;
                                    graphics.DrawString("O:"+obsvValidado, new Font(sFont, (float)7.8, FontStyle.Regular),
                                                        new SolidBrush(Color.Black), startX+35 , startY + Offset);
                                    Offset += 10;
                                }else
                                {

                                    obsvValidado = Obsvc.Substring(aa, tamobsv-aa);
                                    graphics.DrawString("O:"  + obsvValidado, new Font(sFont, (float)7.8, FontStyle.Regular),
                                                        new SolidBrush(Color.Black), startX + 35, startY + Offset);
                                    Offset += 10;
                                    break;
                                }

                            }
                        }
                        catch (Exception tribaes)
                        {
                            log.Error("Error en pdoc_PrintPage Observaciones "+tribaes.Message);
                            graphics.DrawString("=( " + tribaes, new Font(sFont, (float)7.8, FontStyle.Regular),
                                                       new SolidBrush(Color.Black), 0, startY + Offset);
                            Offset += 10;
                        }

                    }
                    else
                    {
                        graphics.DrawString("O:+ " + Obsvc, new Font(sFont, (float)7.8, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX + 35, startY + Offset);
                    }

                }
                if (artOrd.hasModif)
                {
                    foreach (string a in listaDescripcionModificadores)
                    {
                        Offset = Offset + 10;
                        graphics.DrawString("M: " + a, new Font(sFont, (float)7.8, FontStyle.Regular),
                            new SolidBrush(Color.Black), startX + 35, startY + Offset);
                    }
                }
                iCantidadArticulos += artOrd.ordn_cant;
            }//end foreach
            try
            {
                command = new SqlCommand("select usr_nombre from ff_cat_usuario where usr_numempleado = (select ordn_mese from orden where ordn_id=" + lista.ordn_id + ")", myConnection);
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sMesero = reader["usr_nombre"].ToString();
                }
                command = new SqlCommand("select rest_des from restaurant where rest_id = (select rest_id from mesa where mesa_id=(select mesa_id from orden where ordn_id=" + lista.ordn_id + "))", myConnection);
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sRestaurante = reader["rest_des"].ToString();
                }
            }
            catch (Exception ex)
            {
                log.Error("Error en busqueda mesero y restaurante en " + ex.Message);
            }
            finally
            {
                myConnection.Close();
            }
            Offset = Offset + 20;
            graphics.DrawString(underLine, new Font(sFont, (float)8.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);
            Offset = Offset + 20;
            graphics.DrawString("No. de Articulos:" + iCantidadArticulos, new Font(sFont, (float)7.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);
            Offset = Offset + 10;
            graphics.DrawString("Atendio:" + sMesero, new Font(sFont, (float)7.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);
            Offset = Offset + 10;
            graphics.DrawString("Origen:" + sRestaurante, new Font(sFont, (float)7.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);
            Offset = Offset + 10;
            graphics.DrawString("Impresora:" + impresoraDest, new Font(sFont, (float)7.5, FontStyle.Regular),
                        new SolidBrush(Color.Black), startX - 6, startY + Offset);
            Offset = Offset + 25;

            string leyendaa = "Ticket No Valido";
            e.Graphics.DrawString(leyendaa, new Font(sFont, (float)8.6, FontStyle.Bold),
                                Brushes.Black, CentrarTexto(graphics, leyendaa), startY + Offset);
            Offset = Offset + 12;
            string leyendab = "Como Comprobante de Pago";
            e.Graphics.DrawString(leyendab, new Font(sFont, (float)8.6, FontStyle.Bold),
                                Brushes.Black, CentrarTexto(graphics, leyendab), startY + Offset);
            Offset = Offset + 20;
            DateTime nw = DateTime.Now;
            string fechahora = "" + nw;
            e.Graphics.DrawString(fechahora, new Font(sFont, (float)8.6, FontStyle.Regular),
                                Brushes.Black, CentrarTexto(graphics, fechahora), startY + Offset);
            Offset = Offset + 20;
        }
        public ActionResult newComanda( newComanda newcomand)
        {
            log.Info("Solicitando newComanda de orden "+newcomand.ordn_id);
            SqlDataReader reader = null;
            Respuesta resp = new Respuesta();
            SqlConnection myConnection = new SqlConnection();
            decimal imptot = 0;
            int idComanda=0;
            try
            {
                myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["BaseComercial"].ConnectionString;
                myConnection.Open();
                SqlCommand command = new SqlCommand("INSERT INTO COMANDA (ORDN_ID, COMA_STAT) VALUES (@ORDN, 'INIC') SELECT CAST(SCOPE_IDENTITY() AS  INT)", myConnection);
                command.Parameters.AddWithValue("@ORDN", newcomand.ordn_id);

                resp.message += "-1";
                idComanda = (int)command.ExecuteScalar();
                if (0 < idComanda)
                {
                    resp.message += "-2";
                    DateTime fecha = DateTime.Now;
                    int iFecha = Convert.ToInt32("" + fecha.Year + "" + fecha.Month + "" + fecha.Day);
                    int iHora = Convert.ToInt32(fecha.Hour + "" + fecha.Minute);
                    resp.message += "-3";
                    command = null;
                    resp.message += "-4";
                    command = new SqlCommand("INSERT INTO COMANDA_CTRL (COMA_ID, COMA_STAT, COMA_FMOV, COMA_HMOV, COMA_OBSV) VALUES (@IDCOM, 'INIC', @FECH, @HORA, @OBSV)", myConnection);
                    resp.message += "-5";
                    command.Parameters.AddWithValue("@IDCOM", idComanda);
                    command.Parameters.AddWithValue("@FECH", iFecha);
                    command.Parameters.AddWithValue("@HORA", iHora);
                    command.Parameters.AddWithValue("@OBSV", newcomand.coma_obsv);
                    resp.message += "-6";

                    if (0 < command.ExecuteNonQuery())
                    {
                        resp.message += "-7";

                        foreach (OrdenArticulo artOrd in newcomand.ordenarticulo)
                        {
                            resp.message += "-8";
                            command = new SqlCommand("INSERT INTO ORDEN_ARTICULO (ORDN_ID, COMA_ID, ART_EAN, ORDN_CANT, ORDN_IMPUNI, ORDN_IMPART, ORDN_OBSV) VALUES (@ORDN_ID,@COMA_ID,@ART_EAN,@ORDN_CANT,@ORDN_IMPUNI,@ORDN_IMPART,@OBSV)", myConnection);
                            command.Parameters.AddWithValue("@ORDN_ID", newcomand.ordn_id);
                            command.Parameters.AddWithValue("@COMA_ID", idComanda);
                            command.Parameters.AddWithValue("@ART_EAN", artOrd.art_ean);
                            command.Parameters.AddWithValue("@ORDN_CANT", artOrd.ordn_cant);
                            command.Parameters.AddWithValue("@ORDN_IMPUNI", artOrd.ordn_impuni);
                            command.Parameters.AddWithValue("@ORDN_IMPART", artOrd.ordn_impart);
                            command.Parameters.AddWithValue("@OBSV", artOrd.ordn_obsv);
                            imptot += artOrd.ordn_impart;
                            if (0 < command.ExecuteNonQuery())
                            {
                                resp.message += "-9";
                                if (artOrd.hasModif == true)
                                {
                                    foreach (Modificadoresart modiff in artOrd.modificadores)
                                    {
                                        //resp.message += "-10";
                                        command = new SqlCommand("INSERT INTO ORDENART_MODIF (ORDN_ID, COMA_ID, ART_EAN, AGRU_ID, AGRU_CONSEC) VALUES (@ORDN_ID,@COMA_ID,@ART_EAN,@AGRU_ID,@AGRU_CONSEC)", myConnection);
                                        command.Parameters.AddWithValue("@ORDN_ID", newcomand.ordn_id);
                                        command.Parameters.AddWithValue("@COMA_ID", idComanda);
                                        command.Parameters.AddWithValue("@ART_EAN", artOrd.art_ean);
                                        command.Parameters.AddWithValue("@AGRU_ID", modiff.agru_id);
                                        command.Parameters.AddWithValue("@AGRU_CONSEC", modiff.agru_consec);
                                        if (0 < command.ExecuteNonQuery())
                                        {
                                            resp.message += "-11|||";

                                            resp.success = true;
                                            resp.message += "532: OK";
                                        }
                                    }//fin foreach
                                }
                                else
                                {
                                    resp.success = true;
                                    resp.message += "539: OK";
                                }
                            }
                            else
                            {
                                resp.success = false;
                                resp.message += "MESA NO ACTUALIZADA";
                            }
                        }//end foreach
                        command = new SqlCommand("select ordn_imptot from ORDEN where ORDN_ID= @IDORD", myConnection);
                        command.Parameters.AddWithValue("@IDORD", newcomand.ordn_id);

                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            imptot += Convert.ToDecimal(reader["ordn_imptot"].ToString());
                        }
                        command = new SqlCommand("UPDATE ORDEN SET ordn_imptot =@PRECTOT WHERE ORDN_ID =@IDO", myConnection);
                        command.Parameters.AddWithValue("@IDO", newcomand.ordn_id);
                        command.Parameters.AddWithValue("@PRECTOT", imptot);
                        if (0 < command.ExecuteNonQuery())
                        {
                            resp.success = true;
                            resp.message += "567: OK";

                        }
                        try {
                            resp.message += " | PRINT";
                            printComanda(newcomand);
                            resp.message += " | PRINTGOOD";
                        }catch(Exception ext){
                            resp.success = false;
                            resp.message += "Error PRINT="+ext.Message;
                        }
                    }
                    else
                    {
                        resp.success = false;
                        resp.message += "ORDEN_CTRL NO ACTUALIZADA";
                    }
                }
                else
                {
                    resp.success = false;
                    resp.message += "NO SE CREO NUEVA ORDEN";
                }

                command.Parameters.Clear();

            }
            catch (Exception ex)
            {
                log.Error("Error en newComanda en " + ex.Message);
                resp.success = false;
                resp.message += "ERROR a. " + ex.Message;
                return Json(resp);
            }
            finally
            {
                myConnection.Close();
            }
            return Json(resp);
        }
        public void printComanda(newComanda listaOrdenesArts)
        {
            log.Info("Solicitando PrintComanda de " + listaOrdenesArts.ordn_id);
            SqlDataReader reader = null;
            SqlConnection myConnection = new SqlConnection();
            SqlCommand command = null;

            var queryDivisionImpresoras = from OrdenArticulo in listaOrdenesArts.ordenarticulo group OrdenArticulo by OrdenArticulo.tipp_id;
            foreach (var grupodeComandas in queryDivisionImpresoras)
            {
                int llavetipp = grupodeComandas.Key;
                log.Info("PrintComanda => Agrupando las comandas por tipo " + llavetipp);
                PrintDocument pdoc = null;
                PrintDialog pd = new PrintDialog();
                pdoc = new PrintDocument();
                string sNombreImpresora = "";
                string sDesImpresora = "";
                int iubicConsecOrden = 0;
                int irestOrden = 0;
                try
                {
                    int imprcount = 0;
                    myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["BaseComercial"].ConnectionString;
                    myConnection.Open();
                    log.Debug("Obteniendo ubicacion y restaurant");
                    command = new SqlCommand("select (select MESA.UBIC_CONSEC from MESA where MESA.MESA_ID = ORDEN.MESA_ID) as UBIC_CONSEC, (select MESA.REST_ID FROM MESA  where MESA.MESA_ID = ORDEN.MESA_ID) as REST_ID from ORDEN where ORDEN.ORDN_ID =" + listaOrdenesArts.ordn_id, myConnection);
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        iubicConsecOrden = Convert.ToInt32(reader["UBIC_CONSEC"].ToString());
                        irestOrden = Convert.ToInt32(reader["REST_ID"].ToString());
                        log.Debug("Ubicacion=" + iubicConsecOrden + " Restaurant = " + irestOrden);
                    }//

                    command = new SqlCommand("select impr_conf, impr_des  from IMPRESORA where TIPP_ID = " + llavetipp + " and REST_ID = " + irestOrden, myConnection);
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        sNombreImpresora = reader["IMPR_CONF"].ToString();
                        sDesImpresora = reader["IMPR_DES"].ToString();
                        log.Info("Mandando a imprimir por tipo de Producto, a impresora "+sNombreImpresora);
                        imprcount++;
                    }
                    if(sNombreImpresora.Length<1){
                        log.Info("No existe impresora para tipo "+llavetipp + " buscando por ubicacion y restaurante");

                        command = new SqlCommand("select top 1 impr_conf, impr_des from IMPRESORA where IMPRESORA.UBIC_CONSEC = " + iubicConsecOrden + " OR IMPRESORA.REST_ID=" + irestOrden, myConnection);
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            sNombreImpresora = reader["impr_conf"].ToString();
                            sDesImpresora = reader["IMPR_DES"].ToString();

                        }//fin while
                    }//fin if
                    newComanda variableArr = new newComanda();
                    variableArr.ordn_id = listaOrdenesArts.ordn_id;
                    variableArr.coma_obsv = listaOrdenesArts.coma_obsv;
                    List<OrdenArticulo> listavarible = new List<OrdenArticulo>();
                    foreach (var OrdenArticulo in grupodeComandas)
                    {
                        log.Info("Agregando una lista variable con los datos... "+ OrdenArticulo.art_ean);
                        listavarible.Add(OrdenArticulo);
                    }
                    variableArr.ordenarticulo = listavarible;

                    pdoc.PrinterSettings.PrinterName = sNombreImpresora;
                    PrinterSettings ps = new PrinterSettings();
                    Font font = new Font(sFont, 11);

                    PaperSize psize = new PaperSize("Custom", 1000, 20);
                    ps.DefaultPageSettings.PaperSize = psize;

                    pd.Document = pdoc;
                    pd.Document.DefaultPageSettings.PaperSize = psize;
                    pdoc.PrintPage += (sender, e) => pdoc_PrintPage(e, variableArr,  sDesImpresora);

                    pdoc.Print();

                }
                catch (Exception ex) {
                    log.Error("Error en PrintComanda  " + ex.Message);
                }
                finally { myConnection.Close(); }
            }//fin foreach
            /*
            DialogResult result = pd.ShowDialog();
            if (result == DialogResult.OK)
            {
                PrintPreviewDialog pp = new PrintPreviewDialog();
                pp.Document = pdoc;
                result = pp.ShowDialog();
                if (result == DialogResult.OK)
                {
                    pdoc.Print();
                }
            }
            */
        }