using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LLNet.Utils;
using LLNet.GUI;


namespace LLNet.Tienda.Dialogs.Discounts
{
    public partial class dlgDocumentDiscount : GUI.FormBases.frmBase
    {
        public dlgDocumentDiscount()
        {
            InitializeComponent();

            GUI.CApp.TraducirForm(this);
        }

        private string supervisor;
        private decimal total;
        private bool isPercent;
        private bool isCumulative;
        private decimal precioP;

        private void dlgDocumentDiscount_Load(object sender, EventArgs e)
        {
            List<string> observaciones = new List<string>()
            {
                "Sin replica ",
                "Cambio de oferta normal ",
                "Cambio de oferta Credi-e  ",
                "Mala Rotulación ",
                "Cambio de precio (Mal etiquetado)  ",
                "Dañado Aprobado por GZ  ",
                "Descuento Pani ",
                "Descuento por Ekono Plus "
            };

            cmb_observacion.DataSource = observaciones;

            btnPercent.PerformClick();
           
            if (Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS.Count == 0 || Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0]["TOTAL"] == DBNull.Value)
            {
                GUI.CApp.ShowMessage("No puede aplicar descuento si no ha ingresado productos", "Descuentos", true);
                this.Close();
                this.Dispose();
            }
            else
            {
                if (Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_DESCUENTO > 0)
                {
                    isCumulative = (GUI.CApp.ShowMessage("¿Desea acumular el descuento?", "Descuentos", true, true) == DialogResult.OK);
                }

                if (isCumulative)
                {
                    precioP = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_SIN_DESC;
                    total = Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0].TOTAL + Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].DEVOLUCIONES + Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].CANJES;
                    rowSubtotal.Properties.Value = total;
                    rowTotal.Properties.Value = total;
                    rowDevoluciones.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].DEVOLUCIONES;
                    rowCanjes.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].CANJES;
                    rowAPagar.Properties.Value = total - Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].DEVOLUCIONES - Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].CANJES;
                }
                else
                {
                    precioP = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_SIN_DESC; 
                    //precioP = Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("TOTAL_SIN_DESC"));
                    total = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_SIN_DESC;
                    rowSubtotal.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_SIN_DESC;
                    rowTotal.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL_SIN_DESC;
                    rowDevoluciones.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].DEVOLUCIONES;
                    rowCanjes.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].CANJES;
                    rowAPagar.Properties.Value = Program.FrmMainPos.DsPedido.TDA_DATOS_DOCUMENTO[0].TOTAL;
                }

                rowDescuento.Properties.Value = 0;
            }
            calcEdit1.EditValue = 0.00;
        }

        private void btnPercent_Click(object sender, EventArgs e)
        {
            isPercent = true;
            btnPercent.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
            btnPercent.Appearance.BackColor = Color.FromKnownColor(KnownColor.InactiveCaptionText);
            btnAmount.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;
            calcEdit1.Focus();
        }

        private void btnAmount_Click(object sender, EventArgs e)
        {
            isPercent = false;
            btnAmount.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
            btnAmount.Appearance.BackColor = Color.FromKnownColor(KnownColor.InactiveCaptionText);
            btnPercent.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;
            calcEdit1.Focus();
        }

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

        private void checkMinimumPrice(decimal? linesUnderMinimumPrice, string SkusUnderMinimunPrice)
        {
            if (linesUnderMinimumPrice > 0)
            {
                calcEdit1.EditValue = 0.00;
                GUI.CApp.ShowMessage("El descuento no puede sobrepasar el costo o el precio mínimo de los productos del pedido: " + SkusUnderMinimunPrice, "Descuentos", true);
            }
        }

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

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (checkDiscount( Utils.Helpers.Nvl(supervisor,GUI.CApp.usuario).ToString(), calcEdit1.Value) == false)
                SaveDiscount();
        }

        private void SaveDiscount()
        {
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("DOCUMENTO", Program.FrmMainPos.Order.ToString());
            qp.AddReplaceParam("DESCUENTO", calcEdit1.Value.ToString());
            qp.AddReplaceParam("USUARIO", GUI.CApp.usuario);
            qp.AddReplaceParam("ACUMULA", (isCumulative ? "1" : "0"));
            qp.AddReplaceParam("OBSERVACION", cmb_observacion.Text);
            qp.AddReplaceParam("LINEA", "null");

            if (isPercent)
                qp.AddReplaceParam("TIPO", "P");
            else
                qp.AddReplaceParam("TIPO", "M");

            GUI.CApp.bll.ExecuteSql("CreateDiscountOBS", qp, "PDV");

            GUI.CApp.bll.ExecuteSql("RedondearPedido", qp, "PDV"); //REDONDEAMOS

            //DLQG
            Utils.QueryParams qp2 = new LLNet.Utils.QueryParams();
            qp2.AddReplaceParam("PDOCUMENTO", Program.FrmMainPos.Order.ToString());
            if(supervisor == null)
                qp2.AddReplaceParam("PUSUARIO", GUI.CApp.usuario);            
            else
                qp2.AddReplaceParam("PUSUARIO", supervisor);            
            qp2.AddReplaceParam("PLINEA", "null");
            GUI.CApp.bll.ExecuteSql("AutorizaDiscount", qp2, "PDV"); //Bitacora usuario q autoriza Descuento
            //

            Program.FrmMainPos.RefreshData();

            DialogResult = DialogResult.OK;
        }
     

        private void calcEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //checkDiscount(GUI.CApp.usuario);
                checkDiscount(GUI.CApp.usuario, ((DevExpress.XtraEditors.CalcEdit)sender).Value);
            }
        }

        private bool checkDiscount(string pUsuario, decimal pValue)
        {
            decimal maximumDiscount = 0;
            decimal linesUnderMinimumPrice = 0;
            string SkusUnderMinimumPrice = "";

            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("USUARIO", pUsuario);
            maximumDiscount = Convert.ToDecimal(GUI.CApp.bll.GetSingleValue("DescuentoAutorizado", qp, "PDV"));
            decimal PrecioU = precioP - ((precioP * maximumDiscount) / 100);

            qp.Clear();
            qp.AddReplaceParam("DOCUMENTO", Program.FrmMainPos.Order.ToString());

            if (isPercent)
            {
                qp.AddReplaceParam("DESCUENTO", calcEdit1.Value.ToString());
                qp.AddReplaceParam("TIPO", "P");
                qp.AddReplaceParam("LINEA", "null");

                linesUnderMinimumPrice = Convert.ToDecimal(GUI.CApp.bll.GetSingleValue("LinesUnderMinimumPrice", qp, "PDV"));

                if (linesUnderMinimumPrice > 0)
                {
                    SkusUnderMinimumPrice = Convert.ToString(GUI.CApp.bll.GetSingleValue("SkusUnderMinimumPrice", qp, "PDV"));
                }
                else
                {
                    SkusUnderMinimumPrice = "";
                }

                checkMinimumPrice(linesUnderMinimumPrice, SkusUnderMinimumPrice);

                //if (calcEdit1.Value > maximumDiscount)
                decimal PrecioCd = total - (total * pValue / 100);
                if (PrecioCd < PrecioU)
                {
                    //getGrant((decimal)maximumDiscount);
                    if (getGrant(maximumDiscount) == true)
                        return true;
                }

                rowDescuento.Properties.Value = total * calcEdit1.Value / 100;
                rowTotal.Properties.Value = total - (total * calcEdit1.Value / 100);
                rowAPagar.Properties.Value = Convert.ToDecimal(rowTotal.Properties.Value) - Convert.ToDecimal(rowDevoluciones.Properties.Value) - Convert.ToDecimal(rowCanjes.Properties.Value);
            }
            else
            {
                qp.AddReplaceParam("DESCUENTO", calcEdit1.Value.ToString());
                qp.AddReplaceParam("TIPO", "M");
                qp.AddReplaceParam("LINEA", "null");

                linesUnderMinimumPrice = Convert.ToDecimal(GUI.CApp.bll.GetSingleValue("LinesUnderMinimumPrice", qp, "PDV"));

                if (linesUnderMinimumPrice > 0)
                {
                    SkusUnderMinimumPrice = Convert.ToString(GUI.CApp.bll.GetSingleValue("SkusUnderMinimumPrice", qp, "PDV"));
                }
                else
                {
                    SkusUnderMinimumPrice = "";
                }

                checkMinimumPrice(linesUnderMinimumPrice, SkusUnderMinimumPrice);

                //if ((calcEdit1.Value * 100 / total) > maximumDiscount)
                decimal PrecioCd = total -  pValue ;
                if (PrecioCd < PrecioU)
                {
                    //getGrant(total * maximumDiscount / 100);
                    if (getGrant(total * (decimal)maximumDiscount / 100) == true)
                        return true;
                }

                rowDescuento.Properties.Value = calcEdit1.Value;
                rowTotal.Properties.Value = total - calcEdit1.Value;
                rowAPagar.Properties.Value = Convert.ToDecimal(rowTotal.Properties.Value) - Convert.ToDecimal(rowDevoluciones.Properties.Value) - Convert.ToDecimal(rowCanjes.Properties.Value);
            }
            btnAceptar.Focus();
            return false;
        }

        private bool getGrant(decimal cancelValue)
        {
            GUI.Dialogs.MessageBoxes.frmPassword pwd = (GUI.Dialogs.MessageBoxes.frmPassword)GUI.CApp.CreateForm(typeof(GUI.Dialogs.MessageBoxes.frmPassword), true);
            if (pwd != null)
            {
                if (pwd.DialogResult == DialogResult.Cancel)
                {
                    supervisor = null;
                    calcEdit1.Value = cancelValue;
                    GUI.CApp.ShowMessage("El descuento no puede ser mayor al descuento autorizado del usuario", "Descuentos", true);
                    return true;
                }
                else
                {
                    if (checkDiscount(pwd.Usuario, calcEdit1.Value) == false)
                    {
                        supervisor = pwd.Usuario;
                        btnAceptar.Focus();
                        return false;
                    }
                    else
                    {
                        supervisor = null;
                        return true;
                    }
                }
            }
            return true;
        }

        private void dlgDocumentDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    btnPercent_Click(null, null);
                    break;
                case Keys.F3:
                    btnAmount_Click(null, null);
                    break;
                case Keys.F12:
                    btnAceptar_Click(null, null);
                    break;
                case Keys.F4:
                    btn_pcosto_Click(null, null);
                    break;
                case Keys.Escape:
                    btnCancelar_Click(null, null);
                    break;


            }
        }

        private int ridx = 0;

        private void vGridControl1_RecordCellStyle(object sender, DevExpress.XtraVerticalGrid.Events.GetCustomRowCellStyleEventArgs e)
        {
            if (ridx == 6) ridx = 0;

            if (ridx == 1 || ridx == 3 || ridx == 4)
            {
                e.Appearance.ForeColor = Color.Red;
            }
            ridx++;
        }

        private void btn_pcosto_Click(object sender, EventArgs e)
        {
           // Emanuel Carvajal Marin --- SLA_0035
            string docto;
            string user;

            user = GUI.CApp.usuario.ToString();
            docto = Program.FrmMainPos.Order.ToString();

            if (CApp.ValidateAccess("HabilitarPrecioCosto", "Permite facturar a precio costo"))
            {
                QueryParams qpOF = new QueryParams();
                qpOF.AddReplaceParam("DOCUMENTO", docto);
                CApp.bll.ExecuteSql("Aplicar_precio_costo", qpOF, "PDV");
                Program.FrmMainPos.RefreshData();

                QueryParams qpOF2 = new QueryParams();
                qpOF2.AddReplaceParam("USUARIO", user);
                qpOF2.AddReplaceParam("DOCUMENTO", docto);
                CApp.bll.ExecuteSql("RegModUser", qpOF2, "PDV");

                
            }

            else
            {
                return;
            }            
        }
    }
}