class CashRegistersMove < ActiveRecord::Base
  belongs_to :open_cash_register
  belongs_to :payment_method

  belongs_to :expense
  belongs_to :sale
  belongs_to :purchase
  belongs_to :credit_payment
  belongs_to :products_return

  ##--- Llevar registro de Actividad del usuario
  audited

  enum move_type: [:egreso, :ingreso]
  enum status: [:inactive, :active]
  enum concept: [:sale, :purchase, :expense, :credit_payment, :reserved_payment, :products_return, :reserved_first_payment, :reserved_last_payment]

  attr_accessor :skip_received_validation

  validates_presence_of :quantity, message: "Debe indicar cantidad."
  validates_presence_of :payment_method_id, message: "Debe seleccionar método de pago."
  validates_presence_of :received, message: "Debe seleccionar monto recibido.", if: :in_cash?, unless: :skip_received_validation

  scope :activos, -> { where("cash_registers_moves.status = ?", 1) }

  def in_cash?
    cash_payment_id = PaymentMethod.find_by(isCash: 1).id
    if payment_method_id == cash_payment_id
      return true
    else
      return false
    end
  end

  # rubocop:disable Metrics/BlockNesting
  def calculate_quantities
    cash_payment_method_id = PaymentMethod.find_by(isCash: 1).id
    # ventas
    if sale.present?
      if sale.cash?
        if payment_method_id == cash_payment_method_id
          sale_total = sale.total

          already_paid = CashRegistersMove.where(sale_id: sale_id, open_cash_register_id: open_cash_register_id).sum(:quantity)
          rest = sale_total - already_paid
          if received.present?
            self.change = rest > received ? 0 : received - rest
            self.quantity = received > rest ? rest : received
          end
        else
          self.quantity = received
          self.change = 0
        end
      elsif sale.reserved? || sale.credit?
        self.change = received.present? ? (received - quantity) : 0
      end
      # devoluciones
    elsif products_return.present?
      if payment_method_id == cash_payment_method_id
        total = products_return.difference_amount

        already_paid = CashRegistersMove.where(products_return_id: products_return_id, open_cash_register_id: open_cash_register_id).sum(:quantity)

        rest = total - already_paid
        if received.present?
          self.change = received - (total - already_paid)
          self.quantity = received > rest ? rest : received
        end
      else
        self.quantity = received
        self.change = 0
      end
    end
  end
  # rubocop:enable Metrics/BlockNesting

  def self.incomings_per_period(period)
    all_incomings = Array.new
    case period
    when 'day'
      beg_period = Date.current.beginning_of_day
      end_period = Date.current.end_of_day
    when 'week'
      beg_period = Date.current.beginning_of_week
      end_period = Date.current.end_of_week
    when 'month'
      beg_period = Date.current.beginning_of_month
      end_period = Date.current.end_of_month
    end

    Pointsale.activos.each do |pointsale|
      obj = {}
      obj[:pointsale] = pointsale.name.tr(" ", "\n")
      obj[:total] = pointsale.cash_registers_moves.where(created_at: beg_period..end_period, move_type: '1', status: '1').sum(:quantity)
      # sales = pointsale.sales.activas.where(date_sale: beg_period..end_period)
      # obj[:total] = CashRegistersMove.activos.where("sale_id IN (?)", sales.pluck(:id)).where(created_at: beg_period..end_period).sum(:quantity)
      all_incomings << obj
    end
    all_incomings.to_json
  end

  def choose_concept_when_reserved
    reserve_has_moves = CashRegistersMove.where(sale_id: sale_id, move_type: 1, status: 1).any?
    # rubocop:disable Style/ConditionalAssignment
    if reserve_has_moves
      self.concept = sale.reserve_debt > quantity ? :reserved_payment : :reserved_last_payment
    else
      self.concept = :reserved_first_payment
    end
    # rubocop:enable Style/ConditionalAssignment
  end
end
