/*!
 * \brief MProductosTotales::eliminarDescuento
 * \param idx
 * \return
 */
bool MProductosTotales::eliminarDescuento( QModelIndex idx )
{
    if( !idx.isValid() )
        return false;
    if( !esDescuento( idx ) ) {
        qWarning( "Lo que estás intentando eliminar no es un descuento!" );
        return false;
    }

    beginRemoveRows( QModelIndex(), idx.row(), idx.row() );

    // Actualizo los datos siguientes al que elimino
    for( int i = idx.row(); i < idx.row()+descuentos->count(); i++ ) {
        descuentos      ->insert( i, descuentos      ->value( i+1 ) );
        texto_descuentos->insert( i, texto_descuentos->value( i+1 ) );
    }
    descuentos      ->remove( cantidades->size() + descuentos->size() - 1 );
    texto_descuentos->remove( cantidades->size() + texto_descuentos->size() - 1 );

    // Actualizo el subtotales
    for( int i = idx.row(); i < subtotales->count(); i++ ) {
        subtotales->insert( i, subtotales->value( i + 1 ) );
    }

    // Las posiciones estan basadas en indice base 0
    subtotales->remove( subtotales->size() - 1 );

    endRemoveRows();
    emit dataChanged( this->index( idx.row(), 0 ), this->index( this->rowCount(), this->columnCount() ) );

    recalcularTotal();
    return true;
}
/*!
 * \brief MProductosTotales::agregarDescuento
 * \param texto
 * \param porcentaje
 */
void MProductosTotales::agregarDescuento( QString texto, double porcentaje )
{
    if( texto_descuentos->values().contains( texto ) ) {
        qWarning( "El descuento ya existe" );
        return;
    }
    int pos = cantidades->size()+descuentos->size();
    emit beginInsertRows( QModelIndex(), pos, pos );

    texto_descuentos->insert( pos, texto );
    descuentos->insert( pos, porcentaje );

    // Poner el subtotal en subtotales
    double ant = 0.0;
    if( descuentos->size() == 1 ) {
        ant = totalItems;
    } else {
        ant = subtotales->value( subtotales->size() - 1 );
    }
    double sub = ant * ( 1 - ( porcentaje / 100 ) );
    subtotales->insert( pos, sub  );

    // Calcular el total
    Total = sub;

    emit endInsertRows();
    emit dataChanged( index( cantidades->size()-1, 0 ), index( rowCount(), columnCount() ) );
    recalcularTotal();
}
/*!
    \fn MProductosTotales::recalcularTotalItems()
 */
void MProductosTotales::recalcularTotalItems()
{
 totalItems = 0;
 for( QHash<int, double>::const_iterator i = subtotales->constBegin(); i != subtotales->constEnd(); ++i )
 {
  totalItems += i.value();
 }
 // Emito la senal de que cambio el valor
 emit dataChanged( this->index( this->cantidades->size(), 0 ), this->index( this->cantidades->size(), 3 ) );
 recalcularTotal();
}
/*!
 * \fn MProductosTotales::agregarItem( const int cant, const int id_producto, const double pu )
 * Funcion especial que ingresara los elementos sin hacer las verificaciones normales como si fuera un agregado desde la lista de ventas.
 * Util para mostrar elementos con subtotales y totales en listas estaticas para mostrar por ejemplo elementos de compras.
 * \param cant Cantidad del item.
 * \param id_producto Identificador del producto
 * \param pu Precio unitario del item
 */
void MProductosTotales::agregarItem( const double cant, const int id_producto, double pu )
{
    int pos = this->cantidades->size();
    this->insertRow( -1 );

    this->cantidades->insert( pos, cant );
    this->precio_unitario->insert( pos, pu );
    this->subtotales->insert( pos, cant * pu );

    // inserto el indice de lo anterior en el mapa de productos
    this->productos->insert( pos, id_producto );

    if( _calcularTotal )
        recalcularTotalItems(); recalcularTotal();

    emit dataChanged( this->index( pos, 0 ), this->index( pos, this->columnCount() ) );
    emit dataChanged( this->index( this->rowCount(), 0 ), this->index( this->rowCount(), this->columnCount() ) );
}
/*!
    \fn FormAgregarRecibo::cambioCliente( int id_combo )
    Slot llamado cuando se cambia o seleccióna un nuevo cliente.
 */
void FormAgregarRecibo::cambioCliente( int id_combo )
{
// Si es un cliente existente veo si tiene saldo
    if( preferencias::getInstancia()->value( "Preferencias/CtaCte/habilitada" ).toBool() && ERegistroPlugins::getInstancia()->existePlugin( "ctacte" ) )
    {
        if( id_combo == 0 ) {
            // El numero indica Consumidor Final
            qDebug( "FormAgregarRecibo::cambioCliente::Se eligio consumidor final" );
            return;
        }
        QString numero_cuenta =  MCuentaCorriente::obtenerNumeroCuentaCorriente( this->CBCliente->model()->data( this->CBCliente->model()->index( id_combo, 0), Qt::EditRole ).toInt() );
        if( numero_cuenta == QString::number( MCuentaCorriente::ErrorBuscarLimite ) || numero_cuenta == QString::number( MCuentaCorriente::ErrorNumeroCuenta ) )
        {
            qDebug( "FormAgregarRecibo::cambioCliente::Numero de cuenta invalido" );
            return;
        }
        else
        {
            dSBDeuda->setValue( MCuentaCorriente::saldo( numero_cuenta ) );
            recalcularTotal();
            return;
        }
    }
}
/*!
    \fn FormAgregarRecibo::cambioPagado( double valor )
    Slot llamado cuando se cambia la cantidad ingresada en pagado
 */
void FormAgregarRecibo::cambioPagado( double /*valor*/ )
{
    recalcularTotal();
}