using System; 
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Microsoft.Win32;

namespace LLNet.Tienda.MainForms.Forms
{
    public partial class frmConsolidacion : LLNet.GUI.FormBases.frmBase
    {
        
        public frmConsolidacion()
        {
            InitializeComponent();

            GUI.CApp.TraducirForm(this);
        }

        public override void Init(object[] pArgs)
        {
            base.Init(pArgs);
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("RV_DOMAIN", "TIPO FACTURA' AND RV_MPCC02 = 'X' AND RV_MPCC03 = 'X");
            Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsTipoFactura.GetType(), dsTipoFactura.DOMAINS.TableName, qp), dsTipoFactura);
        }

        private void btnReportes_Click(object sender, EventArgs e)
        {
        }

        private static void imprimirTicket(long documento, string impresora, int copias, long formato)
        {
            Impresion.Impresion imp = new Impresion.Impresion();
            imp.Conexion = GUI.CApp.bll.ConnectionString;

            Impresion.MensajeImpresion prntMess = new Impresion.MensajeImpresion();

            RegistryKey key = Registry.CurrentUser;

            key = key.OpenSubKey(@"Software\Logistika\POS Retail 8.0.0\Impresoras\Ticket", true);

            string printerFactura = "";

            if (key != null)
                printerFactura = Utils.Helpers.ObjToStr(key.GetValue("Factura", ""));

            if (printerFactura != string.Empty)
                prntMess.Impresora = printerFactura;
            else
                prntMess.Impresora = impresora;

            prntMess.TipoFormato = Impresion.TipoFormato.Documentos;
            prntMess.Llave1 = documento;
            prntMess.Copias = copias;
            prntMess.Formato = formato;
            imp.SetMensajeImpresion(prntMess);
            try
            {
                imp.ImprimirDocumento();
            }
            catch (Exception ex)
            {
                GUI.CApp.ShowMessage(ex.Message, "Impresion de Documentos", true);
            }
        }

        private static void imprimirFacturaPreimpresa(string serie, string factura, string codigoReporte)
        {
            Hashtable ht = new Hashtable();
            Utils.QueryParams QueryParams = new LLNet.Utils.QueryParams();
            QueryParams.AddReplaceParam("SERIE", serie);
            QueryParams.AddReplaceParam("NO_DOCUMENTO", factura);
            ht.Add("TDA_V_REP_DOCUMENTOS", new object[] { QueryParams, "DsDocReports.TDA_DATOS_DOCCONS" });
            ht.Add("TDA_V_REP_DET_DOCUMENTOS", new object[] { QueryParams, "DsDocReports.TDA_DETALLE_PEDCONS" });

            LLNet.Reports.BaseReports.XRInfo Info;
            Info = Reports.BaseReports.XRBase.SetInfo(codigoReporte);

            RegistryKey key = Registry.CurrentUser;
            key = key.OpenSubKey(@"Software\Logistika\POS Retail 8.0.0\Impresoras\Preimpresos", true);

            string printerFactura = "";

            if (key != null)
                printerFactura = Utils.Helpers.ObjToStr(key.GetValue("Factura", ""));

            if (printerFactura != string.Empty)
                Info.PrinterName = printerFactura;

            LLNet.Reports.BaseReports.XRBase xrBase = new LLNet.Reports.BaseReports.XRBase(Info.BaseReport, Info.CodeReport);
            xrBase.Parametros = Info;
            xrBase.BllInstance = GUI.CApp.bll;
            xrBase.ExePath = GUI.CApp.ExeDir;
            xrBase.ExecuteReport(LLNet.Reports.BaseReports.XRExecution.XRPrint, false, ht);
        }

        private void lueTipoFactura_EditValueChanged(object sender, EventArgs e)
        {
            Utils.QueryParams  qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("TIPO_FACTURA",Utils.Helpers.ObjToStr(((DevExpress.XtraEditors.LookUpEdit)sender).EditValue));
            dsDocumentos.Clear();
            Utils.Helpers.Merge(GUI.CApp.bll.getDataSet("PDV","FacturasAConsolidar",qp),dsDocumentos);
            gridControl1.DataMember = dsDocumentos.Tables[0].TableName;
            gridView1.SelectAll();
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            vGridControl1.PostEditor();
            vGridControl1.UpdateFocusedRecord();
            vGridControl1.FocusFirst();

            string sSerie = Utils.Helpers.ObjToStr(merFactura.PropertiesCollection[0].Value).Trim();
            string sNoDocumento = Utils.Helpers.ObjToStr(merFactura.PropertiesCollection[1].Value).Trim();
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("SERIE", sSerie);
            qp.AddReplaceParam("NO_DOCUMENTO", sNoDocumento);


            if (sNoDocumento == string.Empty)
            {
                GUI.CApp.ShowMessage("Ingrese número de factura consolidada", "Consolidación de Facturas", true);
                return;
            }

            if (sSerie == string.Empty)
            {
                if (Utils.Helpers.ObjToStr(GUI.CApp.bll.GetSingleValue("ExisteFacturaConsolidadaSinSerie", qp, "PDV")) == "1")
                {
                    GUI.CApp.ShowMessage("La factura consolidada ya existe", "Consolidación de Facturas", true);
                    return;
                }

                foreach (int iHandle in gridView1.GetSelectedRows())
                {
                    string sDocumento = gridView1.GetRowCellValue(iHandle, colDocumento).ToString();
                    qp.Clear();
                    qp.AddReplaceParam("NO_DOCUMENTO", sNoDocumento);
                    qp.AddReplaceParam("DOCUMENTO", sDocumento);
                    GUI.CApp.bll.ExecuteSql("ConsolidarFacturasSinSerie", qp, "PDV");
                }

                
            }
            else
            {
                if (Utils.Helpers.ObjToStr(GUI.CApp.bll.GetSingleValue("ExisteFacturaConsolidada", qp, "PDV")) == "1")
                {
                    GUI.CApp.ShowMessage("La factura consolidada ya existe", "Consolidación de Facturas", true);
                    return;
                }

                foreach (int iHandle in gridView1.GetSelectedRows())
                {
                    string sDocumento = gridView1.GetRowCellValue(iHandle, colDocumento).ToString();
                    qp.Clear();
                    qp.AddReplaceParam("SERIE", sSerie);
                    qp.AddReplaceParam("NO_DOCUMENTO", sNoDocumento);
                    qp.AddReplaceParam("DOCUMENTO", sDocumento);
                    GUI.CApp.bll.ExecuteSql("ConsolidarFacturas", qp, "PDV");
                }
            }

            qp.Clear();
            qp.AddReplaceParam("RV_DOMAIN", "DOCUMENTOS TIENDA' AND RV_LOW_VALUE = 'FC");

            Model.General.CgRefCodes dsDocTienda = new LLNet.Model.General.CgRefCodes();

            Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsDocTienda.GetType(), dsDocTienda.DOMAINS.TableName, qp), dsDocTienda);

            if (dsDocTienda.DOMAINS.Count > 0)
            {
                switch (Convert.ToInt16(dsDocTienda.DOMAINS[0]["RV_MPNC03"]))
                {
                    case 1:
                        imprimirFacturaPreimpresa(Utils.Helpers.ObjToStr(merFactura.PropertiesCollection[0].Value), Utils.Helpers.ObjToStr(merFactura.PropertiesCollection[1].Value), dsDocTienda.DOMAINS[0].RV_MPCC03);
                        break;
                    default:
                        //                        imprimirTicket(Convert.ToInt64(dsPDV1.TDA_V_FACTURAS[0].DOCUMENTO), dsDocTienda.DOMAINS[0].RV_MPCC00, Convert.ToInt32(dsDocTienda.DOMAINS[0].RV_MPNC02), Convert.ToInt64(dsDocTienda.DOMAINS[0].RV_MPCC02));
                        break;
                }
            }

            DialogResult = DialogResult.OK;
        }

        private void btnCorrelativo_Click(object sender, EventArgs e)
        {
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("CAJA", Utils.Helpers.ObjToStr(Program.Caja));
            DataSet dsCorr = GUI.CApp.bll.getDataSet("PDV", "SigFacturaConsolidada", qp);
            GUI.CApp.bll.ExecuteSql("ActFacturaConsolidada", qp, "PDV");
            merFactura.PropertiesCollection[0].Value = dsCorr.Tables[0].Rows[0]["SERIE"];
            merFactura.PropertiesCollection[1].Value = dsCorr.Tables[0].Rows[0]["PROXIMA_FACTURA"];
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void frmConsolidacion_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            { 
                case Keys.Escape:
                    btnCancelar_Click(null, null);
                    break;
                case Keys.F9:
                    btnCorrelativo_Click(null, null);
                    break;
                case Keys.F12:
                    btnAceptar_Click(null, null);
                    break;
            }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {
        }
    }
}