class Pointsale < ActiveRecord::Base
  ##--- Associaciones
  has_and_belongs_to_many :expensesconcepts
  has_and_belongs_to_many :products, join_table: :available_products
  has_many :purchases
  has_many :pre_purchases
  has_many :suppliers, through: :purchases
  has_many :inventories
  has_many :users
  has_many :credits
  has_many :credit_payments
  has_many :cash_registers
  has_many :open_cash_registers, through: :cash_registers
  has_many :cash_registers_moves, through: :open_cash_registers
  has_many :cash_outs, through: :open_cash_registers
  has_many :sales, through: :open_cash_registers
  has_many :expenses, through: :open_cash_registers
  has_many :sales_details, through: :sales
  has_many :product_wastes
  has_many :transfers
  has_many :sellers
  has_many :products_returns

  has_many :sales_details, through: :sales

  accepts_nested_attributes_for :users
  validates_associated :users, on: :create
  # has_attached_file :img_pointsale, :styles => { :medium => "250x80>", :thumb => "50x50>" }, :default_url => "/images/:style/missing.png"

  enum status: [:erased, :active, :inactive]

  attr_accessor :skip_name_validation
  attr_accessor :skip_products_validation

  mount_uploader :img_pointsale, ImageUploader

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

  ##--- Validaciones previas de guardar
  validates :name, presence: { message: "Debe capturar el nombre del punto de venta." }, unless: :skip_name_validation
  validates :prefix, presence: { message: "Debe indicar el prefijo del punto de venta." }, length: { maximum: 3, too_long: "El maximo de caracteres debe ser %{count}.", minimum: 3, too_short: "El minimo de caracteres debe ser %{count}." }, uniqueness: { message: "El prefijo ya fue utilizado, favor de especificar otro." }
  # validates_attachment_content_type :img_pointsale, :content_type => /\Aimage\/.*\Z/

  ##--- Tipo de vistas / consultas
  scope :vigentes, -> { where("status != 0").order("status ASC, name ASC") }
  scope :activos, -> { where("status = 1").order("name ASC") }
  scope :ignore_current, ->(pointsale_id) { where.not(id: pointsale_id) }
  # def has_stock

  def total_products(pointsale_id)
    unless pointsale_id.nil?
      Pointsale.find(pointsale_id).products.where("stock > 0").sum(:stock).to_i
    end
  end

  def self.get_pointsale(id, option)
    if option == "open_cash_register"
      Pointsale.open_cash_registers.find(id)
    end
  end

  def get_open_cash_register
    open_cash_registers.where(status: 0).last
  end

  def can_open_cash_register?
    crs = cash_registers.activos
    if crs.size == 1
      # solo hay una caja, checar si esta abierta
      # si esta abierta entonces, regresar false, para que no puedan abrirla otra vez
      !open_cash_registers.abiertas.any?
    else
      # mas de una caja, checar si hay alguna que se pueda abrir
      opened_cash_registers = OpenCashRegister.where(cash_register_id: crs.pluck(:id), status: 0)
      # si el punto de venta tiene 2 cajas y nomas esta abierta una, regresar true para que puedan abrir la otra
      crs.size > opened_cash_registers.size ? true : false
    end
  end

  def self.delete_duplicates_available
    ActiveRecord::Base.connection.exec_query('SELECT DISTINCT (a.product_id), a.pointsale_id,
      COUNT (a.product_id) AS productos FROM available_products AS a WHERE
      (SELECT COUNT (b.product_id) FROM available_products as b
      WHERE b.product_id = a.product_id AND b.pointsale_id = a.pointsale_id
      GROUP BY b.product_id, b.pointsale_id ) > 1 GROUP BY a.product_id, a.pointsale_id
      ORDER BY productos DESC').each do |row|

      availables = AvailableProduct.where(product_id: row["product_id"], pointsale_id: row["pointsale_id"]).order('stock desc')
      con_mayor_stock = availables[0]
      diferentes = 0
      availables.each do |ap|
        next unless ap.id != con_mayor_stock.id
        if ap.stock.zero? || ap.stock == con_mayor_stock.stock
          ap.destroy
        end
      end
    end
    'termine carnalit0'
  end
end
