using System;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using DevExpress.XtraReports.Native;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using DevExpress.XtraEditors;
using DevExpress.XtraReports.UserDesigner;


namespace LLNet.Reports.BaseReports
{

    public class XRDocto : Object
    {
        #region Variables
        private int m_iStartDocto = -1;
        private int m_iEndDocto = -1;
        private int m_iMinValue = -1;
        private int m_iMaxValue = -1;
        private string m_sRollo = "";
        private object m_oTag = null;
        #endregion

        #region Constructores
        public XRDocto()
        {
        }

        public XRDocto(int Start, int End)
        {
            StartDocto = Start;
            EndDocto = End;
        }

        public XRDocto(int Start, int End, int MaxVal, int MinVal)
        {
            MinValue = MinVal;
            MaxValue = MaxVal;
            StartDocto = Start;
            EndDocto = End;
        }

        public XRDocto(int Start, int End, int MaxVal, int MinVal, string NoRollo)
        {
            MinValue = MinVal;
            MaxValue = MaxVal;
            StartDocto = Start;
            EndDocto = End;
            Rollo = NoRollo;
        }

        #endregion

        #region Propiedades

        public int MinValue
        {
            get { return m_iMinValue; }
            set
            {
                m_iMinValue = value;
                if ((m_iMaxValue > -1) && (m_iMinValue > m_iMaxValue))
                    m_iMaxValue = m_iMinValue;
            }
        }

        public int MaxValue
        {
            get { return m_iMaxValue; }
            set
            {
                if ((value > -1) && (value < m_iMinValue))
                    return;
                m_iMaxValue = value;
            }
        }

        public int StartDocto
        {
            get { return m_iStartDocto; }
            set
            {
                if ((m_iMinValue > -1) && (value < m_iMinValue))
                    return;

                m_iStartDocto = value;
                if (m_iStartDocto > m_iEndDocto)
                    m_iEndDocto = m_iStartDocto;
            }
        }

        public int EndDocto
        {
            get { return m_iEndDocto; }
            set
            {
                if (value < m_iStartDocto)
                    return;
                if ((m_iMaxValue > -1) && (value > m_iMaxValue))
                    return;
                m_iEndDocto = value;
            }
        }

        public string Rollo
        {
            get { return m_sRollo; }
            set { m_sRollo = value; }
        }

        public object Tag
        {
            get { return m_oTag; }
            set { m_oTag = value; }
        }

        #endregion

        #region Metodos
        public XRDocto Clone()
        {
            //-- Inicializamos el objeto
            XRDocto objInfo = new XRDocto(m_iStartDocto, m_iEndDocto, m_iMinValue, m_iMaxValue, m_sRollo);
            objInfo.Tag = m_oTag;
            //-- Regresamos el resultado
            return objInfo;
        }

        public void CopyTo(XRDocto docto)
        {
            docto.MinValue = m_iMinValue;
            docto.MaxValue = m_iMaxValue;
            docto.StartDocto = m_iStartDocto;
            docto.EndDocto = m_iEndDocto;
            docto.Rollo = m_sRollo;
            docto.Tag = m_oTag;
        }

        #endregion

    }

    /// <summary>
    /// Summary description for XRInfo.
    /// </summary>
    public class XRInfo : Object
    {
        #region Variables
        private int m_iReportID = -1;
        private int m_iCopies = 1;
        private bool m_bPreview = false;
        private string m_sPrinterName = "";
        private string m_sTipo = "";
        private string m_sSession = "";
        private string m_sBaseReport = "";
        private string m_sCodeReport = "";
        private object m_oTag = null;
        private XRDocto m_oDocto = new XRDocto();
        #endregion

        #region Constructores
        public XRInfo()
        {
        }

        public XRInfo(int ReportID)
        {
            m_iReportID = ReportID;
        }

        public XRInfo(int ReportID, int Copies)
        {
            m_iReportID = ReportID;
            m_iCopies = Copies;
        }

        public XRInfo(int ReportID, int Copies, bool Preview)
        {
            m_iReportID = ReportID;
            m_iCopies = Copies;
            m_bPreview = Preview;
        }

        public XRInfo(int ReportID, int Copies, bool Preview, string PrinterName)
        {
            m_iReportID = ReportID;
            m_iCopies = Copies;
            m_bPreview = Preview;
            m_sPrinterName = PrinterName;
        }

        public XRInfo(int ReportID, int Copies, bool Preview, string PrinterName, string Tipo)
        {
            m_iReportID = ReportID;
            m_iCopies = Copies;
            m_bPreview = Preview;
            m_sPrinterName = PrinterName;
            m_sTipo = Tipo;
        }

        #endregion

        #region Propiedades
        public int ReportID
        {
            get { return m_iReportID; }
            set
            {
                bool bCancel = false;
                changeData("ReportID", value, m_iReportID, ref bCancel);
                if (!bCancel)
                    m_iReportID = value;
            }
        }

        public int Copies
        {
            get { return m_iCopies; }
            set
            {
                bool bCancel = false;
                changeData("Copies", value, m_iCopies, ref bCancel);
                if (!bCancel)
                    m_iCopies = value;
            }
        }

        public bool Preview
        {
            get { return m_bPreview; }
            set
            {
                bool bCancel = false;
                changeData("Preview", value, m_bPreview, ref bCancel);
                if (!bCancel)
                    m_bPreview = value;
            }
        }

        public string PrinterName
        {
            get { return m_sPrinterName; }
            set
            {
                bool bCancel = false;
                changeData("PrinterName", value, m_sPrinterName, ref bCancel);
                if (!bCancel)
                    m_sPrinterName = value;
            }
        }

        public string Tipo
        {
            get { return m_sTipo; }
            set
            {
                bool bCancel = false;
                changeData("Tipo", value, m_sTipo, ref bCancel);
                if (!bCancel)
                    m_sTipo = value;
            }
        }

        public string Sesion
        {
            get { return m_sSession; }
            set
            {
                bool bCancel = false;
                changeData("Session", value, m_sSession, ref bCancel);
                if (!bCancel)
                    m_sSession = value;
            }
        }

        public string BaseReport
        {
            get { return m_sBaseReport; }
            set
            {
                bool bCancel = false;
                changeData("BaseReport", value, m_sBaseReport, ref bCancel);
                if (!bCancel)
                    m_sBaseReport = value;
            }
        }

        public string CodeReport
        {
            get { return m_sCodeReport; }
            set
            {
                bool bCancel = false;
                changeData("CodeReport", value, m_sCodeReport, ref bCancel);
                if (!bCancel)
                    m_sCodeReport = value;
            }
        }

        public object Tag
        {
            get { return m_oTag; }
            set
            {
                bool bCancel = false;
                changeData("Tag", value, m_oTag, ref bCancel);
                if (!bCancel)
                    m_oTag = value;
            }
        }

        public XRDocto Docto
        {
            get { return m_oDocto; }
        }

        #endregion

        #region Metodos

        public XRInfo Clone()
        {
            //-- Inicializamos el objeto
            XRInfo objInfo = new XRInfo();
            //-- Establecemos los valores
            objInfo.ReportID = m_iReportID;
            objInfo.Copies = m_iCopies;
            objInfo.Preview = m_bPreview;
            objInfo.PrinterName = m_sPrinterName;
            objInfo.Tipo = m_sTipo;
            objInfo.Sesion = m_sSession;
            objInfo.BaseReport = m_sBaseReport;
            objInfo.CodeReport = m_sCodeReport;
            objInfo.Tag = m_oTag;
            m_oDocto.CopyTo(objInfo.Docto);
            //-- Regresamos el resultado
            return objInfo;
        }

        #endregion

        #region Eventos

        public event AfterChangeInfo OnAfterChangeInfo;

        private void changeData(string FieldName, object FieldNewValue, object FieldOldValue, ref bool Cancel)
        {
            if (OnAfterChangeInfo != null)
            {
                OnAfterChangeInfo(FieldName, FieldNewValue, FieldOldValue, ref Cancel);
            }
        }

        #endregion

    }

    public delegate void AfterChangeInfo(string FieldName, object FieldNewValue, object FieldOldValue, ref bool Cancel);
    public delegate void BeforeLoadInfoEvent(LLNet.Utils.QueryParams qParams, string TableName, System.Data.DataSet Ds, ref bool bHandle);

    public enum XRExecution
    {
        XREdit = 0, XRPreview = 1, XRPrint = 2, XRNone = 3
    }

    /// <summary>
    /// Summary description for XRBase.
    /// </summary>
    public class XRBase : Object
    {
        #region Subclases
        class DesignForm : DevExpress.XtraReports.UserDesigner.XRDesignFormEx
        {
            protected override void SaveLayout() { }
            protected override void RestoreLayout() { }
        }
        #endregion

        #region Constantes
        protected static string repPath = "{0}Reports\\";
        protected static string repPathBase = repPath + "rep_{1}.repx";
        protected static string repDataPath = "{0}Reports.data\\";
        protected static string repBaseData = repDataPath + "dat_{1}.xml";
        #endregion

        #region Variables
        private Hashtable tableQueParams;
        private Hashtable tableQueNames;
        private Hashtable bindings;

        private DevExpress.XtraPrinting.Native.ReflectorBar reflectorBar;
        private DevExpress.XtraPrinting.PrintingSystem printingSystem;
        private DevExpress.XtraReports.UI.XtraReport m_objRep;
        private DevExpress.XtraEditors.ProgressBarControl progressBar;
        private Model.IBLL bllInstance;
        private Cursor saveCursor;
        private XRInfo m_objInfo;

        private string m_strExePath = "";
        private string m_strRepBase = "";
        private string m_strCodigo = "";
        private string m_strPlantilla = "";
        private string m_strDatos = "";
        private string m_strUsuario = "";
        private bool m_bStart = false;
        private bool WriteToXml = false;
        #endregion

        #region Propiedades
        public string Usuario
        {
            get { return m_strUsuario; }
            set { m_strUsuario = value; }
        }

        public string ExePath
        {
            get { return m_strExePath; }
            set
            {
                m_strExePath = value;
                if (!m_strExePath.EndsWith("\\")) m_strExePath += "\\";
                m_strDatos = String.Format(repBaseData, m_strExePath, m_strRepBase);
                m_strPlantilla = String.Format(repPathBase, m_strExePath, m_strCodigo);
            }
        }

        public string RepBase
        {
            get { return m_strRepBase; }
            set
            {
                //-- Inicializamos las propiedades
                m_strRepBase = value;
                m_strDatos = String.Format(repBaseData, m_strExePath, m_strRepBase);
                //-- Armamos el nombre del Reporte
                string strTmp = "LLNet.Reports.BaseReports." + m_strRepBase;
                Type genericType = Type.GetType(strTmp, true);
                //-- Creamos el reporte
                if ((this.m_objRep == null) || (this.m_objRep.GetType() != genericType))
                    this.m_objRep = (DevExpress.XtraReports.UI.XtraReport)Activator.CreateInstance(genericType);
            }
        }

        public string Codigo
        {
            get { return m_strCodigo; }
            set
            {
                m_strCodigo = value;
                m_strPlantilla = String.Format(repPathBase, m_strExePath, m_strCodigo);
            }
        }

        public string Plantilla
        {
            get { return m_strPlantilla; }
        }

        public string DatosBase
        {
            get { return m_strDatos; }
        }

        public XRInfo Parametros
        {
            get { return m_objInfo; }
            set
            {
                m_objInfo = value;
                this.RepBase = m_objInfo.BaseReport;
                this.Codigo = m_objInfo.CodeReport;
                m_objInfo.OnAfterChangeInfo += new AfterChangeInfo(Info_OnAfterChangeInfo);
            }
        }

        public DevExpress.XtraReports.UI.XtraReport Report
        {
            get { return m_objRep; }
        }

        public Model.IBLL BllInstance
        {
            get { return bllInstance; }
            set { bllInstance = value; }
        }

        #endregion

        #region Metodos privados
        private void InitObj()
        {
            InitObj(null);
        }

        private void InitObj(DevExpress.XtraEditors.ProgressBarControl Barra)
        {
            this.m_objInfo = new XRInfo();
            printingSystem = XtraReport.CreatePrintingSystem();
            SetProgressBar(Barra);
        }

        private void SetWaitProcess()
        {
            saveCursor = Cursor.Current;
            Cursor.Current = Cursors.AppStarting;
        }

        private void RestoreProcess()
        {
            Cursor.Current = saveCursor;
            if (progressBar != null)
                progressBar.Position = 0;
        }

        private void setGeneralXRReportsParams()
        {
            //-- Si esta binding a la tabla de usuarios la lleno
            if (bindings.ContainsKey(typeof(Model.Reports.DsReports)))
            {
                //-- Inicializamos variables
                ArrayList tables = bindings[typeof(Model.Reports.DsReports)] as ArrayList;
                string wms_usuarios = "WMS_USUARIOS";
                //-- Si esta entre las tablas y no lo he adicionado, lo adiciono
                if (tables.IndexOf(wms_usuarios) != -1 && !tableQueParams.ContainsKey(wms_usuarios))
                {
                    Utils.QueryParams userQueryParams = new LLNet.Utils.QueryParams();
                    userQueryParams.AddReplaceParam("USUARIO", this.m_strUsuario);
                    tableQueParams.Add("WMS_USUARIOS", userQueryParams);
                }
            }
        }

        protected void ExecuteXRSubReport(XtraReport subReport)
        {
            subReport.BeforePrint += new System.Drawing.Printing.PrintEventHandler(report_BeforePrint);
        }

        private void Info_OnAfterChangeInfo(string FieldName, object FieldNewValue, object FieldOldValue, ref bool Cancel)
        {
            switch (FieldName)
            {
                case "BaseReport":
                    this.RepBase = FieldNewValue.ToString();
                    break;

                case "CodeReport":
                    this.Codigo = FieldNewValue.ToString();
                    break;

                default:
                    break;
            }
        }

        #endregion

        #region Metodos publicos
        public void SetProgressBar(DevExpress.XtraEditors.ProgressBarControl Barra)
        {
            this.progressBar = Barra;
            if (Barra != null)
                reflectorBar = new DevExpress.XtraPrinting.Native.ReflectorBar(Barra);
        }

        public void EditReport()
        {
            EditReport(true, null);
        }

        public void EditReport(bool UseSavedData)
        {
            EditReport(UseSavedData, null);
        }

        public void EditReport(bool UseSavedData, Hashtable ptableQueParams)
        {
            ExecuteReport(XRExecution.XREdit, UseSavedData, ptableQueParams);
        }

        public void EditReport(bool UseSavedData, Hashtable pTableQueParams, Hashtable pTableQueNames)
        {
            ExecuteReport(XRExecution.XREdit, UseSavedData, pTableQueParams, pTableQueNames);
        }

        public void PrintReport(bool UseSavedData)
        {
            PrintReport(UseSavedData, null);
        }

        public void PrintReport(bool UseSavedData, Hashtable ptableQueParams)
        {
            ExecuteReport(XRExecution.XRPrint, UseSavedData, ptableQueParams);
        }

        public void PrintReport(bool UseSavedData, Hashtable ptableQueParams, Hashtable ptableQueNames)
        {
            ExecuteReport(XRExecution.XRPrint, UseSavedData, ptableQueParams, ptableQueNames);
        }

        public void PreviewReport()
        {
            PreviewReport(true, null);
        }

        public void PreviewReport(bool UseSavedData)
        {
            PreviewReport(UseSavedData, null);
        }

        public void PreviewReport(bool UseSavedData, Hashtable ptableQueParams)
        {
            ExecuteReport(XRExecution.XRPreview, UseSavedData, ptableQueParams);
        }

        public void PreviewReport(bool UseSavedData, Hashtable ptableQueParams, Hashtable ptableQueNames)
        {
            ExecuteReport(XRExecution.XRPreview, UseSavedData, ptableQueParams, ptableQueNames);
        }

        public void ExecuteReport(bool UseSavedData)
        {
            //-- Declaracion de variables
            XRExecution tmpProceso;
            //-- Establecemos los parametros
            if (this.m_objInfo.Preview)
                tmpProceso = XRExecution.XRPreview;
            else
                tmpProceso = XRExecution.XRPrint;
            //-- Ejecutamos el reporte
            ExecuteReport(tmpProceso, UseSavedData, null);
        }

        public void ExecuteReport(Hashtable ptableQueParams)
        {
            //-- Declaracion de variables
            XRExecution tmpProceso;
            //-- Establecemos los parametros
            if (this.m_objInfo.Preview)
                tmpProceso = XRExecution.XRPreview;
            else
                tmpProceso = XRExecution.XRPrint;
            //-- Ejecutamos el reporte
            ExecuteReport(tmpProceso, false, ptableQueParams);
        }

        public void ExecuteReport(XRExecution Proceso, bool UseSavedData, Hashtable ptableQueParams, bool ToXml)
        {
            WriteToXml = ToXml;
            ExecuteReport(Proceso, UseSavedData, ptableQueParams);
        }

        public void ExecuteReport(XRExecution Proceso, bool UseSavedData, Hashtable ptableQueParams, Hashtable ptableQueNames, bool ToXml)
        {
            WriteToXml = ToXml;
            ExecuteReport(Proceso, UseSavedData, ptableQueParams, ptableQueNames);
        }

        public void ExecuteReport(XRExecution Proceso, bool UseSavedData, Hashtable ptableQueParams)
        {
            ExecuteReport(Proceso, UseSavedData, ptableQueParams, null);
        }

        public void ExecuteReport(XRExecution Proceso, bool UseSavedData, Hashtable ptableQueParams, Hashtable ptableQueNames)
        {
            printingSystem.ShowMarginsWarning = false;
            //-- Validacion inicial
            if (m_objRep == null) return;
            //-- Inicializamos variables
            if (reflectorBar != null) ProgressReflector.RegisterReflector(reflectorBar);
            SetWaitProcess();
            //-- Inicializamos objetos
            bindings = new Hashtable();
            tableQueParams = new Hashtable();
            if (ptableQueParams != null)
                tableQueParams = ptableQueParams;
            if (ptableQueNames != null)
                tableQueNames = ptableQueNames;
            //-- Empezamos
            try
            {
                //-- Inicializamos el reporte
                if (System.IO.File.Exists(this.m_strPlantilla))
                    this.m_objRep.LoadLayout(this.m_strPlantilla);
                this.m_objRep.Name = this.m_strCodigo;
                //-- Establecemos el area de impresión
                m_bStart = true;
                printingSystem.ClearContent();
                this.m_objRep.PrintingSystem = printingSystem;
                printingSystem.StartPrint += new DevExpress.XtraPrinting.PrintDocumentEventHandler(printingSystem_StartPrint);
                //-- Cargamos los registros
                if (UseSavedData)
                {
                    WriteToXml = false;
                    System.Data.DataSet ds = (System.Data.DataSet)this.m_objRep.DataSource;
                    if (System.IO.File.Exists(this.m_strDatos))
                    {
                        ds.EnforceConstraints = false;
                        ds.ReadXml(this.m_strDatos);
                    }
                }
                else
                {
                    this.m_objRep.BeforePrint += new System.Drawing.Printing.PrintEventHandler(report_BeforePrint);
                }
                //-- Procedemos según el caso
                switch (Proceso)
                {
                    case XRExecution.XREdit:
                        DesignForm designForm = new DesignForm();
                        try
                        {
                            designForm.OpenReport(m_objRep);
                            designForm.FileName = this.m_strPlantilla;
                            //GUI.CApp.CreateForm(designForm.GetType(),"",true);
                            //designForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                            //designForm.MdiParent = GUI.CApp.MainForm;
                            //designForm.ShowDialog();
                            designForm.Show();
                        }
                        catch (System.Exception ex)
                        {
                            string strError = ex.StackTrace;
                            throw new Exception("Error mostrando pantalla de edicion", ex);
                        }
                        finally
                        {
                            //designForm.Dispose();
                        }
                        break;

                    case XRExecution.XRPreview:
                        //this.printingSystem.PreviewForm.MdiParent = GUI.CApp.MainForm;
                        this.printingSystem.PreviewFormEx.StartPosition = FormStartPosition.CenterScreen;
                        this.printingSystem.PreviewFormEx.WindowState = FormWindowState.Maximized;
                        //this.m_objRep.ShowPreview();
                        this.m_objRep.ShowPreviewDialog();
                        break;

                    case XRExecution.XRPrint:

                        //m_objRep.PrintingSystem.ShowMarginsWarning = false;
                        if (this.m_objInfo.PrinterName.Length == 0)
                        {
                            this.m_objRep.PrintDialog();
                        }
                        else
                            this.m_objRep.Print();
                        break;

                    default:
                        break;
                }
            }
            //catch(System.Exception ex)
            //{
            //	throw new System.Exception("Error cargando reporte", ex);
            //}
            finally
            {
                RestoreProcess();
                if (reflectorBar != null) ProgressReflector.UnregisterReflector(reflectorBar);
            }
        }
        public static Model.Reports.DsWmsDoctos InitMenu(string Codigo)
        {
            //-- Declaracion de variables
            Utils.QueryParams qry = new LLNet.Utils.QueryParams();
            Model.Reports.DsWmsDoctos ds;
            //-- Establecemos los parametros
            qry.AddReplaceParam(Utils.QueryParams.PredefinedTags.AllToolbarsTag, " AND CODIGO = " + Utils.Helpers.scm(Codigo));
            ds = (Model.Reports.DsWmsDoctos)GUI.CApp.bll.getTypedDataSet(typeof(Model.Reports.DsWmsDoctos), "WMS_V_POSDOCTOS", qry);
            //-- Regresamos el resultado
            return ds;
        }

        public static LLNet.Reports.BaseReports.XRInfo SetInfo(string Codigo)
        {
            //-- Obtenemos la informacion de la base de datos
            Model.Reports.DsWmsDoctos ds = InitMenu(Codigo);
            System.Data.DataTable tb = ds.WMS_V_POSDOCTOS;
            if (tb.Rows.Count == 0)
            {
                XtraMessageBox.Show("No existe reporte de impresión configurado!", "Reportes", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop);
                return null;
            }
            System.Data.DataRow row = tb.Rows[0];
            //-- Trasladamos la informacion
            Reports.BaseReports.XRInfo objInfo = new LLNet.Reports.BaseReports.XRInfo();
            objInfo.ReportID = Convert.ToInt32(Utils.Helpers.Nvl(row["FORMATO"], 0));
            objInfo.BaseReport = row["BASE_FORMATO"].ToString();
            objInfo.CodeReport = row["CODIGO_FORMATO"].ToString();
            objInfo.Copies = Convert.ToInt32(Utils.Helpers.Nvl(row["NO_COPIAS"], 1));
            objInfo.Preview = (Utils.Helpers.Nvl(row["PREIMPRESION"], "").ToString() == "X");
            objInfo.PrinterName = Utils.Helpers.Nvl(row["IMPRESORA"], "").ToString();
            objInfo.Tipo = Utils.Helpers.Nvl(row["TIPO"], "").ToString();
            //-- Regresamos la informacion
            return objInfo;
        }

        #endregion

        #region Constructores
        public XRBase()
        {
            //-- Inicializamos objetos
            InitObj();
        }

        public XRBase(string ReportBase)
        {
            //-- Inicializamos objetos
            InitObj();
            //-- Inicializamos propiedades
            RepBase = ReportBase;
        }

        public XRBase(string ReportBase, DevExpress.XtraEditors.ProgressBarControl Barra)
        {
            //-- Inicializamos objetos
            InitObj(Barra);
            //-- Inicializamos propiedades
            RepBase = ReportBase;
        }

        public XRBase(string ReportBase, string ReportCode)
        {
            //-- Inicializamos objetos
            InitObj();
            //-- Inicializamos propiedades
            RepBase = ReportBase;
            Codigo = ReportCode;
        }

        public XRBase(string ReportBase, string ReportCode, DevExpress.XtraEditors.ProgressBarControl Barra)
        {
            //-- Inicializamos objetos
            InitObj(Barra);
            //-- Inicializamos propiedades
            RepBase = ReportBase;
            if (ReportCode.Length > 0)
                Codigo = ReportCode;
        }

        #endregion

        #region Eventos

        public event BeforeLoadInfoEvent BeforeLoadInfo;

        private void dataLoad(LLNet.Utils.QueryParams qParams, string TableName, System.Data.DataSet Ds, ref bool bHandle)
        {
            if (BeforeLoadInfo != null)
            {
                BeforeLoadInfo(qParams, TableName, Ds, ref bHandle);
            }
        }

        #endregion

        #region Eventos del Reporte
        private void printingSystem_StartPrint(object sender, DevExpress.XtraPrinting.PrintDocumentEventArgs e)
        {
            //-- Get printer settings.
            PrinterSettings prnSettings = e.PrintDocument.PrinterSettings;
            //-- Establecemos valores
            if (m_bStart)
            {
                m_bStart = false;
                if (this.m_objInfo.Copies > 0)
                    prnSettings.Copies = (short)this.m_objInfo.Copies;
                if (this.m_objInfo.PrinterName.Length > 0)
                    prnSettings.PrinterName = this.m_objInfo.PrinterName;
            }
        }

        private void report_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            //-- Inicializamos variables
            DevExpress.XtraReports.UI.XtraReport rep = (DevExpress.XtraReports.UI.XtraReport)sender;
            System.Type reportType = sender.GetType();
            //-- Llenamos los datasets				
            try
            {
                //-- Lleno el hash bindins con todos los datasets y sus respectivas tablas usadas
                foreach (FieldInfo field in rep.GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (field.FieldType == typeof(Subreport))
                    {
                        Subreport subReport = (Subreport)field.GetValue(rep);
                        ExecuteXRSubReport(subReport.ReportSource);
                    }

                    if (field.FieldType.IsSubclassOf(typeof(XRControl)))
                    {
                        XRControl control = (XRControl)field.GetValue(rep);

                        foreach (XRBinding binding in control.DataBindings)
                        {
                            if (binding.DataSource != null)
                            {
                                if (bindings.ContainsKey(binding.DataSource.GetType())) //ya tiene el DataSource
                                {
                                    ArrayList tables = bindings[binding.DataSource.GetType()] as ArrayList;
                                    string dataMember = binding.DataMember.ToString();
                                    string[] strMembers = dataMember.Split(".".ToCharArray());
                                    if (strMembers.Length == 2)
                                    {
                                        if (tables.IndexOf(strMembers[0]) == -1)
                                            tables.Add(strMembers[0]);
                                    }
                                    else if (strMembers.Length > 2)
                                    {
                                        System.Data.DataSet ds = (System.Data.DataSet)binding.DataSource;
                                        System.Data.DataRelation dr = ds.Relations[strMembers[strMembers.Length - 2]];
                                        string strTable = dr.ChildTable.TableName;
                                        if (tables.IndexOf(strTable) == -1)
                                            tables.Add(strTable);
                                    }
                                }
                                else //-- no estaba
                                {
                                    ArrayList table = new ArrayList();
                                    string dataMember = binding.DataMember.ToString();
                                    table.Add(dataMember.Substring(0, dataMember.IndexOf(".")));
                                    bindings.Add(binding.DataSource.GetType(), table);
                                }
                            }
                        }
                    }
                }
                //-- lleno parametros de valores de parammetros generales  
                setGeneralXRReportsParams();

                //-- recorro todos los datasets que encontre en el reporte
                foreach (object dataSource in bindings.Keys)
                {
                    ArrayList tables = bindings[dataSource] as ArrayList;
                    System.Type dataSetType = dataSource as System.Type;

                    //-- busco la instancia de dataset en el reporte
                    System.Data.DataSet dataSet = null;
                    foreach (FieldInfo field in rep.GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance))
                    {
                        if (field.FieldType.ToString() == dataSetType.ToString())
                        {
                            //dataSet = (System.Data.DataSet)field.GetValue(rep);
                            dataSet = (System.Data.DataSet)rep.DataSource;
                            break;
                        }
                    }

                    if (dataSet != null) //si encontre el dataset, lo lleno
                    {
                        //-- lleno cada tabla de cada dataset, con queryparams o sin el
                        foreach (object table in tables)
                        {
                            Utils.QueryParams qp = null;
                            string queryName = null;
                            if ((tableQueParams != null) && (tableQueParams.ContainsKey(table.ToString())))
                            {
                                if (tableQueParams[table.ToString()] is Utils.QueryParams)
                                {
                                    qp = tableQueParams[table.ToString()] as Utils.QueryParams;
                                }
                                else
                                {
                                    object[] obj = tableQueParams[table.ToString()] as object[];
                                    qp = obj[0] as Utils.QueryParams;
                                    queryName = obj[1].ToString();
                                }
                            }

                            bool bHandle = false;
                            dataLoad(qp, table.ToString(), dataSet, ref bHandle);
                            if (!bHandle)
                                Utils.Helpers.Merge(bllInstance.getTypedDataSet(dataSetType, table.ToString(), qp, queryName), dataSet);

                        }
                    }
                    if (WriteToXml)
                        dataSet.WriteXml(m_strDatos, System.Data.XmlWriteMode.IgnoreSchema);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error en la ejecución del Reporte : \n" + ex.Message, "POS", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
        }

        #endregion

    }
}
