class TransfersController < ApplicationController
  ##--- Abilities
  load_and_authorize_resource

  ##--- Breadcrum_rails
  add_breadcrumb I18n.t("breadcrumbs." + controller_name), :transfers_path
  add_breadcrumb "Nuevo traspaso", :new_transfer_path, only: :new
  add_breadcrumb "Detalle del traspaso", :transfer_path, only: :show
  add_breadcrumb "Editar traspaso", :edit_transfer_path, only: :edit
  add_breadcrumb "Verificar traspaso", :verify_transfer_path, only: :verify_transfer

  before_action :set_transfer, only: [:show, :edit, :update, :destroy]
  before_action :get_filters, only: [:index, :show, :edit, :new]

  # GET /transfers
  # GET /transfers.json
  def index
    @transfers = Transfer.includes(:user, :received_by, :transfer_details).all.order('id DESC, transfer_date DESC')
    unless current_user.usertype == "A"
      is_destiny =
        if current_user.usertype == "S"
          id_filter = current_user.warehouse_id
          0
        else
          id_filter = current_user.pointsale_id
          1
        end
      @received = @transfers.where(destiny_id: id_filter, destiny_is_pointsale: is_destiny).order('id DESC, transfer_date DESC')
      @sent = @transfers.where(origin_id: id_filter, origin_is_pointsale: is_destiny).order('id DESC, transfer_date DESC')
    end
  end

  # GET /transfers/1
  # GET /transfers/1.json
  def show; end

  # GET /transfers/new
  def new
    @transfer = Transfer.new
    set_transfer_data(nil)
  end

  # GET /transfers/1/edit
  def edit; end

  # POST /transfers
  # POST /transfers.json
  def create
    @transfer = Transfer.new(transfer_params)
    pre_transfers = PreTransfer.where(user_id: current_user.id)
    @transfer.user_id = current_user.id
    @transfer.status = :pending
    @transfer.origin_is_pointsale = params[:transfer][:origin_id].first == 'P' ? 1 : 0
    @transfer.destiny_is_pointsale = params[:transfer][:destiny_id].first == 'P' ? 1 : 0
    @transfer.origin_id = params[:transfer][:origin_id][2, params[:transfer][:origin_id].length]
    @transfer.destiny_id = params[:transfer][:destiny_id][2, params[:transfer][:destiny_id].length]

    pre_transfers.each do |pre|
      detail = TransferDetail.new(transfer_id: @transfer.id, product_id: pre.product_id, quantity: pre.quantity, adjustment: pre.quantity, status: "pending")
      @transfer.transfer_details << detail
    end
    respond_to do |format|
      origin_pointsale_name = @transfer.origin_is_pointsale? ? Pointsale.find(@transfer.origin_id).name : Warehouse.find(@transfer.origin_id).name
      destiny_pointsale_name = @transfer.destiny_is_pointsale? ? Pointsale.find(@transfer.destiny_id).name : Warehouse.find(@transfer.destiny_id).name
      @transfer.audit_comment = "Traspaso de #{origin_pointsale_name} a #{destiny_pointsale_name} creado."
      if @transfer.save
        pre_transfers.destroy_all
        message = "Traspaso creado al " + (@transfer.destiny_is_pointsale? ? "punto de venta #{destiny_pointsale_name}" : "almacén #{destiny_pointsale_name}")
        format.html { redirect_to transfers_path, success: message }
        format.json { render :show, status: :created, location: @transfer }
      else
        set_transfer_data(params)
        format.html { render :new }
        format.json { render json: @transfer.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /transfers/1
  # DELETE /transfers/1.json
  def destroy
    @transfer.audit_comment = "Traspaso de #{@transfer.origin_is_pointsale? ? Pointsale.find(@transfer.origin_id).name : Warehouse.find(@transfer.origin_id).name} a #{@transfer.destiny_is_pointsale? ? Pointsale.find(@transfer.destiny_id).name : Warehouse.find(@transfer.destiny_id).name} eliminado."
    @transfer.destroy
    respond_to do |format|
      format.html { redirect_to transfers_url, notice: 'Transfer was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def verify_transfer
    @transfer = Transfer.find(params[:transfer_id])
  end

  # para guardar la cantidad recibida por producto en el traspaso
  def detail_adjustment
    respond_to do |format|
      @transfer = Transfer.find(params[:transfer_id])
      @transfer.transfer_details.each do |detail|
        # rubocop:disable Style/Next
        if detail.id == params[:detail_id].to_i
          detail.adjustment = params[:transfer_details][:adjustment].to_i
          if detail.adjustment > detail.quantity
            detail.has_looses = 0
            detail.has_surplus = 1
          elsif detail.adjustment < detail.quantity
            detail.has_looses = 1
            detail.has_surplus = 0
          end

          if detail.save
            format.json { head :ok }
          end
        end
        # rubocop:enable Style/Next
      end
    end
  end

  def accept_transfer
    @transfer = Transfer.find(params[:transfer_id])
    @transfer.observations = params[:transfer][:observations]
    @transfer.received_by_id = current_user.id
    @transfer.status = :received
    @transfer.reception_date = Date.today
    @transfer.audit_comment = "Se dio entrada a traspaso de #{@transfer.origin_is_pointsale? ? Pointsale.find(@transfer.origin_id).name : Warehouse.find(@transfer.origin_id).name} a #{@transfer.destiny_is_pointsale? ? Pointsale.find(@transfer.destiny_id).name : Warehouse.find(@transfer.destiny_id).name}"
    @transfer.save
    @transfer.transfer_details.each do |detail|
      if @transfer.destiny_is_pointsale == 1
        stock_product = AvailableProduct.find_by(product_id: detail.product_id, pointsale_id: @transfer.destiny_id)
        if stock_product.present?
          stock_product.stock = 0 if stock_product.stock.blank?
          stock_product.stock += detail.adjustment
        else
          stock_product = AvailableProduct.new(product_id: detail.product_id, pointsale_id: @transfer.destiny_id, stock: detail.adjustment)
        end
      else
        # actualizar stock del producto cuando es para almacen
        stock_product = WarehouseStock.find_by(product_id: detail.product_id, warehouse_id: @transfer.destiny_id)
        if stock_product.present?
          stock_product.stock = 0 if stock_product.stock.blank?
          stock_product.stock += detail.adjustment
        else
          stock_product = WarehouseStock.new(product_id: detail.product_id, warehouse_id: @transfer.destiny_id, stock: detail.adjustment)
        end
      end
      stock_product.save

      # guardar en bitacora de inventario
      move = InventoriesMove.new(product_id: detail.product_id, quantity: detail.adjustment, transfer_id: @transfer.id, move_type: "incoming", reason: "transfer")
      move.save
    end
    respond_to do |format|
      format.js { flash[:success] = "Traspaso realizado correctamente." }
    end
  end

  def print_receipt
    @transfer = Transfer.find(params[:transfer_id])
    origin = @transfer.origin_is_pointsale == 1 ? Pointsale.find(@transfer.origin_id).name : Warehouse.find(@transfer.origin_id).name
    destiny = @transfer.destiny_is_pointsale == 1 ? Pointsale.find(@transfer.destiny_id).name : Warehouse.find(@transfer.destiny_id).name
    with_looses = @transfer.transfer_details.where(has_looses: 1).count
    with_surplus = @transfer.transfer_details.where(has_surplus: 1).count
    reception_status =
      if with_looses > 0 && with_surplus.zero?
        'CON PERDIDAS'
      elsif with_surplus > 0 && with_looses.zero?
        'CON EXCEDENTE'
      elsif with_surplus > 0 && with_looses > 0
        'CON INCONSISTENCIAS'
      else
        'TRASPASO COMPLETO'
      end
    respond_to do |format|
      format.pdf do
        render pdf: "traspaso_#{@transfer.id}", template: "transfers/receipt.pdf.erb", layout: 'receipt.html.erb', locals: { transfer: @transfer, reception_status: reception_status, origin: origin, destiny: destiny }, show_as_html: params.key?('debug'), page_width: '80mm', page_height: '300mm'
      end
    end
  end

  def set_transfer_data(params)
    @destiny_pointsales = Pointsale.activos.ignore_current(current_user.pointsale_id)
    @pre_transfers = PreTransfer.where(user_id: current_user.id)
    @disable_origin = false
    @disable_destiny = false
    # reestablecer origen y destino
    if @pre_transfers.present?
      @origin_id = @pre_transfers[0].origin_is_pointsale? ? "P-#{@pre_transfers[0].origin_id}" : "W-#{@pre_transfers[0].origin_id}"
      @destiny_id = @pre_transfers[0].destiny_is_pointsale? ? "P-#{@pre_transfers[0].destiny_id}" : "W-#{@pre_transfers[0].destiny_id}"
      @disable_origin = true
      @disable_destiny = true
    elsif params.present?
      @origin_id = params[:transfer][:origin_id]
      @destiny_id = params[:transfer][:destiny_id]
    end

    if current_user.usertype == "G" || current_user.usertype == "C"
      @origin_id = "P-#{current_user.pointsale_id}"
      @disable_origin = true
    elsif current_user.usertype == "S"
      @origin_id = "W-#{current_user.warehouse_id}"
      @disable_origin = true
    end

    if @origin_id == @destiny_id
      @disable_origin = false
      @disable_destiny = false
    end
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_transfer
    @transfer = Transfer.find(params[:id])
  end

  def get_filters
    @current_page = params[:current_page].blank? ? 1 : params[:current_page]
    @filter = params[:filter]
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def transfer_params
    params.require(:transfer).permit(:origin_id, :destiny_id, :transfer_date, :user_id, :status, :received_by_id, :observations, transfer_details_attributes: [:transfer_id, :product_id, :quantity, :status, :adjustment, :reception_date])
  end
end
