class AvailableProductsController < ApplicationController
  before_action :set_available_product, only: [:edit_price, :update_price]
  autocomplete :available_product, :name, full: true

  def stock
    @showcolumns = "minMax"
    # se utiliza para mandarle al datatable el numero de columnas y en que orden se deben de acomodar
    @column_definition = [{ "data": "0" }, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }, { "data": "7" }].to_json
    @location_id = current_user.pointsale_id.present? ? current_user.pointsale_id : current_user.warehouse_id
    respond_to do |format|
      format.html
      format.json { render json: StocksDatatable.new(view_context, current_user, @showcolumns) }
    end
  end

  def initial_stock
    @showcolumns = "initial"
    @location_id = current_user.pointsale_id.present? ? current_user.pointsale_id : current_user.warehouse_id
    # se utiliza para mandarle al datatable el numero de columnas y en que orden se deben de acomodar
    @column_definition = [{ "data": "0" }, { "data": "1" }, { "data": "2" }, { "data": "3" }, { "data": "4" }, { "data": "5" }, { "data": "6" }].to_json

    respond_to do |format|
      format.html
      format.json { render json: StocksDatatable.new(view_context, current_user, @showcolumns) }
    end
  end

  def stock_by_pointsale
    add_breadcrumb "Existencias", :stock_by_pointsale_path
    @selected = current_user.usertype == "S" ? "W-#{current_user.warehouse_id}" : "P-#{current_user.pointsale_id}"
    respond_to do |format|
      format.html
      format.json { render json: StockByPointsaleDatatable.new(view_context, current_user, @selected) }
    end
  end

  def edit_price
    @product = @available_product.product
  end

  def update_price
    @product = @available_product.product
    message = "El precio del venta para el producto #{@available_product.product.name} se actualizo a $#{params[:available_product][:price_sale]} en punto de venta #{@available_product.pointsale.name}."

    respond_to do |format|
      if @available_product.update_attributes params[:available_product]
        @available_product.audit_comment = message
        format.html { redirect_to products_url, success: message }
        format.json { head :no_content }
        format.js { flash[:success] = message }
      else
        format.js { render :edit_price }
        format.json { render json: @available_product.errors, status: :unprocessable_entity }
      end
    end
  end

  def update_all_variants_prices
    @product = Product.find(params[:product_id])
    respond_to do |format|
      if @product.is_parent
        children_ids = @product.children.pluck(:id)
        AvailableProduct.where('pointsale_id = (?) and product_id IN (?)', params[:pointsale_id], children_ids).update_all(price_sale: params[:new_price])
        format.json { head :ok }
      else
        format.json { render json: @available_product.errors, status: :unprocessable_entity }
      end
    end
  end

  # POST /pointsales/5/available_products
  def create
    @available_product = AvailableProduct.new(available_product_params)

    respond_to do |format|
      if @available_products.save
        format.html { redirect_to pointsale_available_product_url, notice: 'Se agregó un producto disponible para el punto de venta.' + Pointsale.find(pointsale_id).select("name") }
      else
        format.html { render pointsale_available_product_path(@available_product.pointsale_id) }
      end
    end
  end

  def update_stock
    min = params[:stock_min]
    max = params[:stock_max]

    respond_to do |format|
      if current_user.usertype == 'S'
        WarehouseStock.where(id: params[:ids]).update_all(stock_min: min, stock_max: max)
      else
        AvailableProduct.where(id: params[:ids]).update_all(stock_min: min, stock_max: max)
      end
      format.json { head :ok }
    end
  end

  def set_initial_stock
    respond_to do |format|
      if current_user.usertype == 'S'
        WarehouseStock.where(id: params[:ids]).update_all(stock: params[:stock])
      else
        AvailableProduct.where(id: params[:ids]).update_all(stock: params[:stock])
      end
      format.json { head :ok }
    end
  end

  # rubocop:disable Metrics/BlockLength
  def print_stock
    respond_to do |format|
      location = params[:location]
      category = params[:category]
      sub_category = params[:sub_category]
      search = params[:search]
      size = params[:size].to_i
      location_id = params[:location][2, params[:location].length] unless location.blank?

      if (current_user.usertype == 'S' && location.blank?) || (!location.blank? && location.first == 'W')
        stock = WarehouseStock.activos.includes(:warehouse, :categories).where(warehouse_id: (location_id.blank? ? current_user.warehouse_id : location_id)).where('stock > 0')
      elsif (current_user.usertype != 'S' && location.blank?) || (!location.blank? && location.first == 'P')
        stock = AvailableProduct.activos.includes(:pointsale, :categories).where(pointsale_id: (location_id.blank? ? current_user.pointsale_id : location_id)).where('stock > 0')
      end

      if sub_category.present?
        stock = stock.joins(:categories).where('categories.id = ?', sub_category)
      elsif category.present?
        subs_ids = Category.activos.where(parent_id: category).pluck(:id)
        stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
      end

      if size != 0
        stock = stock.limit(size)
      end

      unless search.blank?
        stock = stock.where("products.sku ilike :search or products.name ilike :search", search: "%#{search}%")
      end

      if location.first == 'W'
        location = Warehouse.find(location_id)
      elsif location.first == 'P'
        location = Pointsale.find(location_id)
      end

      format.pdf do
        render pdf: "existencias", template: "available_products/stock_by_pointsale.pdf.erb", layout: "pdf_base.pdf.erb", locals: { stock: stock, location: location, category: category, sub_category: sub_category, search: search }, show_as_html: params.key?('debug'), page_size: 'Letter'
      end
    end
  end
  # rubocop:enable Metrics/BlockLength

  def total_products_by_pointsale
    location = params[:location]
    category = params[:category]
    sub_category = params[:sub_category]
    location_id = params[:location][2, params[:location].length] unless location.blank?

    if location.first == 'P'
      stock = AvailableProduct.activos.where(pointsale_id: location_id)
    elsif location.first == 'W'
      stock = WarehouseStock.activos.where(warehouse_id: location_id)
    end

    if sub_category.present?
      stock = stock.joins(:categories).where('categories.id = ?', sub_category)
    elsif category.present?
      subs_ids = Category.activos.where(parent_id: category).pluck(:id)
      stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
    end

    total_prods = stock.sum(:stock)
    render json: total_prods
  end

  def total_invested_in_pointsale
    location = params[:location]
    category = params[:category]
    sub_category = params[:sub_category]
    location_id = params[:location][2, params[:location].length] unless location.blank?

    if location.first == 'P'
      stock = AvailableProduct.activos.where(pointsale_id: location_id).where('stock > 0')
    elsif location.first == 'W'
      stock = WarehouseStock.activos.where(warehouse_id: location_id).where('stock > 0')
    end

    if sub_category.present?
      stock = stock.joins(:categories).where('categories.id = ?', sub_category)
    elsif category.present?
      subs_ids = Category.activos.where(parent_id: category).pluck(:id)
      stock = stock.joins(:categories).where('categories.id IN (?)', subs_ids)
    end

    obj = Hash.new
    obj['invested_in_pesos'] = location.first == 'P' ? stock.where('products.is_in_dollars = false').sum('available_products.stock * products.price_base') : stock.where('products.is_in_dollars = false').sum('warehouse_stocks.stock * products.price_base')
    obj['invested_in_dollars'] = location.first == 'P' ? stock.where('products.is_in_dollars = true').sum('available_products.stock * products.price_base_dollars') : stock.where('products.is_in_dollars = true').sum('warehouse_stocks.stock * products.price_base_dollars')
    render json: obj
  end

  # DELETE //pointsales/5/available_products/1
  def destroy
    @available_product.destroy
    # respond_to do |format|
    #   format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' }
    #   format.json { head :no_content }
    # end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def get_products
    @products = Product.activos_children
  end

  # Use callbacks to share common setup or constraints between actions.
  def set_available_product
    @available_product = AvailableProduct.find(params[:available_product_id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def available_product_params
    params.require(:available_product).permit(:pointsale_id, :product_id, :stock_min, :stock_max, :stock, :ids, :price_sale)
  end
end
