class RefundRecordsController < AdminBaseController
  def index
    @q = RefundRecord.ransack(params[:q])
    @q.sorts = "id DESC" if @q.sorts.empty?
    @product_records = @q.result.page(params[:page])
  end

  # Create new refund record for a product
  def new
    @refund = RefundRecord.new
  end

  def create
    @product_sn = nil
    @info = params[:refund_record][:sn].strip.split(",").collect { |word| word.strip }
    if @info.size == 1 && @info[0].size == 8
      @product_sn = @info[0]
    else
      if @info.size != 3
        @error_message = "内箱（袋）标签格式无效 !"if @info.size != 3
        return
      end
      if @info.any? { |item| item.blank? }
        @error_message = "内箱（袋）标签数据无效 !"
      end

      @materiel_number = @info[0]
      @lot_no = @info[1]
      @product_sn = @info[2]
    end



    @product = Product.where(sn: @product_sn).first
    if @product.nil?
      render js: "alert('没有查看到此SN(#{@product_sn})相关的信息')" and return
    end
    if @lot_no.nil?
      @lot_no = @product.lot_no
    end

    @product.status = 'refund'
    @product.location = params[:location]
    @product.refund_records.build(type: 'RefundRecord', product_sn: @product_sn, lot_no: @lot_no, remark: params[:refund_record][:remark], status: 'refund', location: "", created_by: current_user.true_name)
    if @product.save
      redirect_to '/refund_records', notice: 'Op success.'
    else
      render js: "alert('Failed:#{@product.errors.full_messages}')"
    end
  end



end
