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 DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using Microsoft.Win32;

namespace LLNet.Tienda.MainForms.Forms
{
    public partial class frmCrearNotaCredito : LLNet.GUI.FormBases.frmBase
    {
        public frmCrearNotaCredito()
        {
            InitializeComponent();
            Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsMotivo1.GetType(), dsMotivo1.CG_REF_CODES.TableName), dsMotivo1);

            GUI.CApp.TraducirForm(this);            
        }

       
        private string oldNit;
        private bool band = true;
        private int linea = 0;

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

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

        public override void Init(object[] pArgs)
        {
            base.Init(pArgs);
           
            beNIT.EditValue = null;
            beCliente.EditValue = null;
            Utils.Helpers.pdocumento = null;

            Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsMotivo1.GetType(), dsMotivo1.CG_REF_CODES.TableName), dsMotivo1);
            this.lookUpEdit1.EditValue = null;
            repFacturas.BllInstance = GUI.CApp.bll;
            repFacturas.GridView = gridView1;
            
            dsDoNotaCred1.TDA_V_NOTAS_CREDITO.Clear();

            dsLovFacturas1.TDA_V_FACTURAS_CREDITO_NC.Clear();
            dvFacturas.Table = dsLovFacturas1.TDA_V_FACTURAS_CREDITO_NC;
            linea = 0;


        }

        private void getInvoices()
        {

        }

        private void beNIT_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            Tienda.MainForms.Finders.frmFindCustomer fc = new LLNet.Tienda.MainForms.Finders.frmFindCustomer();
            fc.Init(null);
            fc.ShowDialog(this);

            if (fc.DialogResult == DialogResult.OK)
            {
                socio = Convert.ToDecimal(fc.Socio);
                beNIT.EditValue = fc.NIT;
                beCliente.EditValue = fc.Nombre;
                oldNit = fc.NIT;
              

                Utils.Helpers.psocio = socio.ToString();
               
                
                
                Utils.QueryParams qp1 = new LLNet.Utils.QueryParams();
                qp1.Clear();
                qp1.AddReplaceParam("CAJA", Utils.Helpers.ObjToStr(Program.Caja));
             
                v_documentonc = Convert.ToDecimal(GUI.CApp.GetSecuence("WMS_S_DOCUMENTO"));
                string v_nota_num = GUI.CApp.bll.GetSingleValue("SigNotaCredit", qp1, "PDV").ToString();
                string v_nota_serie = GUI.CApp.bll.GetSingleValue("SerieNotaCredit", qp1, "PDV").ToString();
                
               Utils.Helpers.pdocumento = v_documentonc.ToString();

                GUI.CApp.bll.ExecuteSql("ActNotaCredito", qp1, "PDV");  


                Utils.QueryParams qpNC = new LLNet.Utils.QueryParams();
                qpNC.Clear();
                qpNC.AddReplaceParam("DOCUMENTO", Convert.ToString(v_documentonc));
                qpNC.AddReplaceParam("TIPO_DOCUMENTO", "N");
                qpNC.AddReplaceParam("NO_DOCUMENTO", Convert.ToString(v_nota_num));
                qpNC.AddReplaceParam("SERIE", v_nota_serie.ToString());
                qpNC.AddReplaceParam("JORNADA", Utils.Helpers.ObjToStr(Program.Jornada));
                qpNC.AddReplaceParam("CAJA", Utils.Helpers.ObjToStr(Program.Caja));
                qpNC.AddReplaceParam("CREADO_POR", GUI.CApp.usuario.ToString());
                qpNC.AddReplaceParam("TOTAL", "0");
                qpNC.AddReplaceParam("DOCUMENTO_PADRE", "");
                qpNC.AddReplaceParam("SOCIO", socio.ToString());
                qpNC.AddReplaceParam("OBSERVACIONES", "");
                qpNC.AddReplaceParam("SITUACION", "1");
                qpNC.AddReplaceParam("SUBTIPO_DOCUMENTO","" );
                qpNC.AddReplaceParam("USUARIO", GUI.CApp.usuario.ToString());         
                
                GUI.CApp.bll.ExecuteSql("GrabaNC", qpNC, "PDV");     
  
            }
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                if (socio != 0)
                {
                    if (GUI.CApp.ShowMessage("¿Esta Seguro de Salir sin Guardar la Nota de Credito?", "POS Nota de Crédito", true, true) == DialogResult.OK)
                    {
                        if (Utils.Helpers.pdocumento != null)
                        {
                            Utils.QueryParams qpANC = new LLNet.Utils.QueryParams();
                            qpANC.Clear();
                            qpANC.AddReplaceParam("DOCUMENTO", Convert.ToString(Utils.Helpers.pdocumento.ToString()));
                            GUI.CApp.bll.ExecuteSql("AnulaDocNC", qpANC, "PDV");
                        }
                        Program.CloseWindow(this);
                    }
                }
                else
                    Program.CloseWindow(this);
            }
            catch { }
        }

        private void frmPagoCredito_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            { 
                case Keys.Escape:
                    btnCancelar_Click(null, null);
                    break;
                case Keys.F2:
                    btnBuscar_Click(null, null);
                    break;
                case Keys.F3:
                    btnCalculate_Click(null, null);
                    break;
                case Keys.F12:
                    btnAceptar_Click(null, null);
                    break;
            }
        }

        private MainForms.Forms.frmPayments pmt;

        private void btnAceptar_Click(object sender, EventArgs e)
        {

            if (socio.ToString() != "0")
            {

                if ((this.lookUpEdit1.EditValue) != null)
                {
                    if (gridView1.RowCount > 0)
                    {

                        Utils.QueryParams qpUp = new LLNet.Utils.QueryParams();

                        for (int i = 0; i < gridView1.RowCount; i++)
                        {
                            DataRow row = gridView1.GetDataRow(i);
                            decimal v_documento = System.Decimal.Parse(row["DOCUMENTO"].ToString());
                            decimal v_valor = System.Decimal.Parse(row["VALOR"].ToString());
                            qpUp.Clear();
                            qpUp.AddReplaceParam("RECIBO", Convert.ToString(v_documentonc));
                            qpUp.AddReplaceParam("DOCUMENTO", System.Convert.ToString(v_documento));
                            qpUp.AddReplaceParam("VALOR", System.Convert.ToString(v_valor));
                            GUI.CApp.bll.ExecuteSql("ActualizaNC", qpUp, "PDV");
                            GUI.CApp.bll.ExecuteSql("ActualizaFactura", qpUp, "PDV");

                        }

                        object v_sumary = this.colVALOR.SummaryItem.SummaryValue;
                        Utils.QueryParams qp2 = new LLNet.Utils.QueryParams();
                        qp2.Clear();
                        qp2.AddReplaceParam("DOCUMENTO", Convert.ToString(v_documentonc));
                        qp2.AddReplaceParam("TOTAL", System.Convert.ToString(v_sumary));
                        GUI.CApp.bll.ExecuteSql("ActualizaTotalNC", qp2, "PDV");

                        qp2.Clear();
                        qp2.AddReplaceParam("DOCUMENTO", Convert.ToString(v_documentonc));
                        qp2.AddReplaceParam("MOTIVO", this.lookUpEdit1.EditValue.ToString());
                        GUI.CApp.bll.ExecuteSql("ActualizaMotivo", qp2, "PDV");
                                              

                        try
                        {
                            printReceipt(Convert.ToInt64(v_documentonc));
                            Program.CloseWindow(this);
                        }
                        catch { }
                    }
                    else
                    {
                        GUI.CApp.ShowMessage("No Existe un Detalle para la Nota de Crédito", "POS Nota de Crédito", true);
                       
                    }
                }
                else
                {
                    GUI.CApp.ShowMessage("Debe Seleccionar un Motivo para la Nota de Crédito", "POS Nota de Crédito", true);
                    

                }
            }
            else
            {
                GUI.CApp.ShowMessage("Debe Seleccionar un Cliente para la Nota de Crédito", "POS Nota de Crédito", true);
                
            }

            


        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            linea = linea + 1;
            gridView1.SetRowCellValue(e.RowHandle, colSERIE, linea);
            
        }

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

        private void frmPagoCredito_Shown(object sender, EventArgs e)
        {
            layoutControl1.Focus();
            layoutControl1.FocusHelper.FocusFirst();
        }

        private void beNIT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Model.PDV.DsPDV.WMS_SOCIOSRow cust = GetCustomer(Utils.Helpers.ObjToStr(((DevExpress.XtraEditors.ButtonEdit)sender).EditValue));
                if (cust != null)
                {
                    socio = cust.SOCIO;
                    beNIT.EditValue = cust.NIT;
                    beCliente.EditValue = cust.NOMBRE;
                    oldNit = cust.NIT;
                    getInvoices();
                   
                }
                else
                {
                    oldNit = null;
                    socio = 0;
                    beCliente.EditValue = null;
                    dsPDV1.TDA_V_FACTURAS_CREDITO.Clear();
                    beCliente.EditValue = "Cliente no existe";
                    beNIT.SelectAll();
                    beNIT.Focus();
                }
            }
        }


        public Model.PDV.DsPDV.WMS_SOCIOSRow GetCustomer(string NIT)
        {

            Utils.QueryParams qp = new Utils.QueryParams();

            if (NIT == oldNit && dsPDV1.WMS_SOCIOS.Count > 0 && NIT != string.Empty)
                return dsPDV1.WMS_SOCIOS[0];
            dsPDV1.WMS_SOCIOS.Clear();

            // Si no ingresaron codigo devuelve el consumidor final
            if ((NIT == null) || (NIT == ""))
            {
                return null;
            }
            else
            {
                qp.AddReplaceParam("NIT", NIT);

                // Busca el NIT ingresado
                Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsPDV1.GetType(), dsPDV1.WMS_SOCIOS.TableName, qp, "CustomerByNIT"), dsPDV1);
                if (dsPDV1.WMS_SOCIOS.Rows.Count == 0)
                {
                    return null;
                }
            }
            oldNit = NIT;

            return dsPDV1.WMS_SOCIOS[0];
        }


        private void gridView1_ShownEditor(object sender, System.EventArgs e)
        {
           if (gridView1.FocusedColumn.ColumnEdit is LLNet.Controls.LLRepAdvancedList || gridView1.FocusedColumn.ColumnEdit is LLNet.Controls.LLRepAdvancedTreeList)
            {
                if (gridView1.ActiveEditor.DataBindings.Count == 0)
                {
                    switch (this.gridView1.FocusedColumn.Name)
                    {
                        case "colNO_DOCUMENTO":
                            gridView1.ActiveEditor.DataBindings.Add(new System.Windows.Forms.Binding("EditValue", this.dvFacturas, "NO_DOCUMENTO"));
                            gridView1.ActiveEditor.DataBindings.Add(new System.Windows.Forms.Binding("Tag", this.dvFacturas, "DOCUMENTO"));
                            break;
                    }
                }

                gridView1.ActiveEditor.EditValue = gridView1.FocusedValue;

            }
        }



        private void repFacturas_BeforeButtonClick()
        {
           dsLovFacturas1.TDA_V_FACTURAS_CREDITO_NC.Clear();
            Utils.QueryParams qp2 = new LLNet.Utils.QueryParams();
            qp2.AddReplaceParam(Utils.QueryParams.PredefinedTags.PosToolbarTag, " AND SOCIO = '" + socio + "'");
            Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsLovFacturas1.GetType(), dsLovFacturas1.TDA_V_FACTURAS_CREDITO_NC.TableName, qp2), dsLovFacturas1);
        }

        private void repFacturas_AfterButtonClick()
        {
            if (this.repFacturas.DlgAdvancedList.dataView.Table.Rows.Count > 0)
            {
                try
                {
                    gridView1.SetFocusedRowCellValue(colDOCUMENTO, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["DOCUMENTO"]);
                    gridView1.SetFocusedRowCellValue(colNO_DOCUMENTO, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["NO_DOCUMENTO"]);
                    gridView1.SetFocusedRowCellValue(colFECHA_EMISION, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["FECHA_EMISION"]);
                    gridView1.SetFocusedRowCellValue(colUSUARIO1, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["USUARIO1"]);
                    gridView1.SetFocusedRowCellValue(colTOTAL, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["TOTAL"]);
                    gridView1.SetFocusedRowCellValue(colSALDO, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["SALDO"]);
                    gridView1.SetFocusedRowCellValue(colRECIBO, ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["DOCUMENTO"]);
                    gridView1.SetFocusedRowCellValue(colTIPO_DOCUMENTO, ("F"));
                    gridView1.SetFocusedRowCellValue(colVALOR, ("0"));


                    Utils.QueryParams qpIns = new LLNet.Utils.QueryParams();
                    qpIns.Clear();
                    qpIns.AddReplaceParam("RECIBO", Convert.ToString(v_documentonc));
                    qpIns.AddReplaceParam("TIPO_DOCUMENTO", "F");
                    qpIns.AddReplaceParam("DOCUMENTO", ((DataRowView)this.repFacturas.DlgAdvancedList.BindingContext[this.dvFacturas].Current).Row["DOCUMENTO"].ToString());
                    qpIns.AddReplaceParam("VALOR", "0");
                    GUI.CApp.bll.ExecuteSql("AplicaFact", qpIns, "PDV");
                }
                catch { }

                gridView1.MoveLast();
            }
        
        }

       private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
          string v_saldo = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colSALDO).ToString();
          string v_valor = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colVALOR).ToString();

          if (Convert.ToDecimal(v_valor) > Convert.ToDecimal(v_saldo))
          {
              e.Valid = false;
              gridView1.SetColumnError(colVALOR, "Monto no puede ser mayor al saldo");
          }
          
           if (Convert.ToDecimal(v_valor) <= 0)
          {
              e.Valid = false;
              gridView1.SetColumnError(colVALOR, "Monto no puede ser igual o menor a cero");
          }

        
          
        }
        

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }


              
        private void btnBuscar_Click(object sender, EventArgs e)
        {
             

            Utils.QueryParams qpUp = new LLNet.Utils.QueryParams();

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                DataRow row = gridView1.GetDataRow(i);                   
                decimal v_documento =System.Decimal.Parse(row["DOCUMENTO"].ToString());
                decimal v_valor= System.Decimal.Parse(row["VALOR"].ToString());
                qpUp.Clear();
                qpUp.AddReplaceParam("RECIBO", Convert.ToString(v_documentonc));
                qpUp.AddReplaceParam("DOCUMENTO",System.Convert.ToString(v_documento) );
                qpUp.AddReplaceParam("VALOR", System.Convert.ToString(v_valor));
                GUI.CApp.bll.ExecuteSql("ActualizaNC", qpUp, "PDV");
              //  GUI.CApp.bll.ExecuteSql("ActualizaFactura", qpUp, "PDV");

            }
            band = false;

        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
               
                Utils.QueryParams qpDe = new LLNet.Utils.QueryParams();
                qpDe.Clear();
                //if (!band)
                //{
                //    qpDe.AddReplaceParam("DOCUMENTO", gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colDOCUMENTO).ToString());
                //    qpDe.AddReplaceParam("VALOR", gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colVALOR).ToString());
                //    GUI.CApp.bll.ExecuteSql("ActualizaDelNC", qpDe, "PDV");
                //}

                qpDe.Clear();
                qpDe.AddReplaceParam("RECIBO", gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colRECIBO).ToString());
                qpDe.AddReplaceParam("DOCUMENTO", gridView1.GetRowCellValue(gridView1.FocusedRowHandle, this.colDOCUMENTO).ToString());
                GUI.CApp.bll.ExecuteSql("EliminaDetNC", qpDe, "PDV");

                this.dsFacturasNc.Delete(this.BindingContext[this.dsFacturasNc].Position);
                linea = linea - 1;
            }
            catch { }

        }

        private void printReceipt(long documento)
        {
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("RV_DOMAIN", "DOCUMENTOS TIENDA' AND RV_LOW_VALUE = 'NC3");

            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:
                        imprimirNotaCreditPreimpreso(documento, dsDocTienda.DOMAINS[0].RV_MPCC03);
                        break;
                    default:
                        imprimirNotaCreditTicket(documento, dsDocTienda.DOMAINS[0].RV_MPCC00, Convert.ToInt32(dsDocTienda.DOMAINS[0].RV_MPNC02), Convert.ToInt64(dsDocTienda.DOMAINS[0].RV_MPCC02));
                        break;
                }
            }
        }


        private static void imprimirNotaCreditTicket(long documento, string impresora, int copias, long formato)
        {

   
            Impresion.Impresion imp = new Impresion.Impresion();
            imp.Conexion = GUI.CApp.bll.ConnectionString;

            //Impresion.dsformatonc dsnotacredito = new Impresion.dsformatonc();

            //Utils.QueryParams QueryParams2 = new LLNet.Utils.QueryParams();
            //QueryParams2.AddReplaceParam(Utils.QueryParams.PredefinedTags.RepToolbarTag, " AND DOCUMENTO = '" + documento.ToString() + "'");
            //Utils.Helpers.Merge(GUI.CApp.bll.getTypedDataSet(dsnotacredito.GetType(), dsnotacredito.TDA_V_PREIMPRESO_NC.TableName, QueryParams2), dsnotacredito);
            



            Impresion.MensajeImpresion prntMess = new Impresion.MensajeImpresion();
            RegistryKey key = Registry.CurrentUser;

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

            string printerNC = "";

            if (key != null)
                printerNC = Utils.Helpers.ObjToStr(key.GetValue("Nota de Credito", ""));

            if (printerNC != string.Empty)
                prntMess.Impresora = printerNC;
            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 imprimirNotaCreditPreimpreso(long documento, string codigoReporte)
        {
            
            Hashtable ht = new Hashtable();
            Utils.QueryParams QueryParams = new LLNet.Utils.QueryParams();
             QueryParams.AddReplaceParam(Utils.QueryParams.PredefinedTags.RepToolbarTag, " AND DOCUMENTO = '" + documento.ToString() + "'");
           
             ht.Add("TDA_V_PREIMPRESO_NC", QueryParams);
      
            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 printerNC = "";

            if (key != null)
                printerNC = Utils.Helpers.ObjToStr(key.GetValue("Nota de Credito", ""));


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

  
            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);
        }

    }
}