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

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

            GUI.CApp.TraducirForm(this);
        }

        private string supervisor;
        private decimal total;
        private decimal precioP;
        private bool isPercent;
        private bool isAmount;
        private bool isCumulative;
        private decimal? pLinea;

        private void dlgLineDiscount_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
            {

                pLinea = Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("LINEA"));

                if (Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("DESCUENTO")) > 0)
                {
                    isCumulative = (GUI.CApp.ShowMessage("¿Desea acumular el descuento?", "Descuentos", true, true) == DialogResult.OK);
                }

                if (isCumulative)
                {
                    precioP = Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("PRECIO_CIMP"));
                    total = Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("TOTAL_LINEA"));
                    rowSubtotal.Properties.Value = total;
                    rowTotal.Properties.Value = total;
                    rowPrecio.Properties.Value = Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("PRECIO_CLIENTE").ToString();
                }
                else
                {
                    precioP = Math.Round(Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("PRECIO_CIMP")), 2);
                    total = Math.Round(Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("CANTIDAD")) * Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("PRECIO_CIMP")), 2);
                    rowSubtotal.Properties.Value = total;
                    rowTotal.Properties.Value = total;
                    rowPrecio.Properties.Value = Math.Round(Convert.ToDecimal(Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("PRECIO_CIMP")), 2);
                }

                rowProducto.Properties.Value = Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("DESCRIPCION").ToString();
                rowCantidad.Properties.Value = Program.FrmMainPos.pos.ctlDetail1.bgvDetail.GetFocusedRowCellValue("CANTIDAD").ToString();


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

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

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

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

        private void checkMinimumPrice(decimal? linesUnderMinimumPrice)
        {
            if (linesUnderMinimumPrice > 0)
            {
                calcEdit1.Value = Convert.ToDecimal(0);
                GUI.CApp.ShowMessage("El descuento no puede sobrepasar el costo o el precio mínimo de los productos del pedido", "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("OBSERVACION",cmb_observacion.Text);
            qp.AddReplaceParam("ACUMULA", (isCumulative ? "1" : "0"));
            

            if (pLinea != null)
                qp.AddReplaceParam("LINEA", pLinea.ToString());
            else
                qp.AddReplaceParam("LINEA", "null");

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

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

            //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);
            if (pLinea != null)
                qp2.AddReplaceParam("PLINEA", pLinea.ToString());
            else
                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, ((DevExpress.XtraEditors.CalcEdit)sender).Value);
            }
        }

        private bool checkDiscount(string pUsuario, decimal pValue)
        {
            decimal maximumDiscount = 0;
            decimal linesUnderMinimumPrice = 0;
            decimal pCantidad = Convert.ToDecimal(rowCantidad.Properties.Value);

            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", pValue.ToString());
                qp.AddReplaceParam("TIPO", "P");
                qp.AddReplaceParam("LINEA", pLinea.ToString());

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

                checkMinimumPrice(linesUnderMinimumPrice);

                decimal PrecioCd = (total - (total * pValue / 100)) / pCantidad;
                if (PrecioCd < PrecioU)
                {
                    if (getGrant(((total / pCantidad) - PrecioU) / (total / pCantidad) * 100) == true)
                        return true;

                }

                rowDescuento.Properties.Value = total * pValue / 100;
                rowTotal.Properties.Value = total - (total * pValue / 100);
            }

            else if (isAmount)
            {
                qp.AddReplaceParam("DESCUENTO", pValue.ToString());
                qp.AddReplaceParam("TIPO", "M");
                qp.AddReplaceParam("LINEA", pLinea.ToString());

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

                checkMinimumPrice(linesUnderMinimumPrice);

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

                rowDescuento.Properties.Value = (pValue * pCantidad);
                rowTotal.Properties.Value = total - (pValue * pCantidad);

            }
            else
            {
                qp.AddReplaceParam("DESCUENTO", (total - pValue).ToString());
                qp.AddReplaceParam("TIPO", "M");

                checkMinimumPrice(linesUnderMinimumPrice);

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

                }

                rowDescuento.Properties.Value = total - (pValue * pCantidad);
                rowTotal.Properties.Value = (pValue * pCantidad);

            }
            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 = Math.Round(cancelValue, 2);
                    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 btnPrice_Click(object sender, EventArgs e)
        {
            isPercent = false;
            isAmount = false;
            btnPrice.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
            btnPrice.Appearance.BackColor = Color.FromKnownColor(KnownColor.InactiveCaptionText);
            btnPercent.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;
            btnAmount.ButtonStyle = DevExpress.XtraEditors.Controls.BorderStyles.Default;
            calcEdit1.Focus();
        }

        private void dlgLineDiscount_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F5:
                    btnPercent_Click(null, null);
                    break;
                case Keys.F6:
                    btnAmount_Click(null, null);
                    break;
                case Keys.F7:
                    btnPrice_Click(null, null);
                    break;
                case Keys.F12:
                    btnAceptar_Click(null, null);
                    break;
            }
        }
    }
}