class ProductsController < AdminBaseController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  # GET /products
  # GET /products.json
  def index
    if not current_user.allowed?(:view_products)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @q = Product.ransack(params[:q])
    @q.sorts = "id DESC" if @q.sorts.empty?
    @products = @q.result.page(params[:page])
  end

  # GET /products/1
  # GET /products/1.json
  def show
    @device_test = DeviceTest.where(sn: @product.sn).first
    if @device_test
      @hardware = Hardware.where(mac: @device_test.mac).first
    end
    @product_records = @product.product_records.order("id DESC")
  end

  # GET /products/1/edit
  def edit
  end

  # PATCH/PUT /products/1
  # PATCH/PUT /products/1.json
  def update
    return
    respond_to do |format|
      if @product.update(product_params)
        format.html { redirect_to @product, notice: 'Product was successfully updated.' }
        format.json { render :show, status: :ok, location: @product }
      else
        format.html { render :edit }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.json
  def destroy
    return
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_product
      @product = Product.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def product_params
      params.require(:product).permit(:sn, :materiel_id, :status)
    end
end
