class RmasController < AdminBaseController
  def index
    if current_user.company != 'shnt'
      @q = RmaRecord.where(location: current_user.company).ransack(params[:q])
      @q.sorts = "id DESC" if @q.sorts.empty?
      @product_records = @q.result.page(params[:page])
    else
      @q = RmaRecord.ransack(params[:q])
      @q.sorts = "id DESC" if @q.sorts.empty?
      @product_records = @q.result.page(params[:page])
    end
  end

  # Return to shanghai factory
  def new
  end

  # Return to Novotech
  def new_to_nt

  end

  def create
    @product = Product.where(sn: params[:sn]).first
    if @product.nil?
      @device_test = DeviceTest.where(sn: params[:sn]).first
      if @device_test.nil?
        render js: "alert('没有查看到此SN相关的信息')" and return
      else
        @product = Product.new(sn: params[:sn], materiel_id: Materiel.default_one.id)
      end
    end

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

  def remark
    @rma_record = RmaRecord.where(status: :tofix).find params[:id]
  end

  def remark_it
    @rma_record = @rma_record = RmaRecord.where(status: :tofix).find params[:rma_record_id]
    if params[:remark].blank? || params[:remark].size > 40
      render js: "alert('alert('Failed')" and return
    end
    @rma_record.remark = params[:remark]
    @rma_record.save
    redirect_to "/rmas"
  end

  def handle_rma
    @rma_record = RmaRecord.where(status: :tofix).find params[:id]
  end

  def done
    @rma_record = @rma_record = RmaRecord.where(status: :tofix).find params[:rma_record_id]
    if params[:failed_fix_reason] == 'mark_dead'
      @rma_record.status = 'dead'
      @rma_record.product&.status = 'dead'
      @rma_record.done_by = current_user.true_name
      @rma_record.done_at = Time.now
      @rma_record.remark = params[:remark]
    elsif params[:failed_fix_reason] == 'to_nt'
      @rma_record.location = 'Shanghai Novotech'
      @rma_record.remark = params[:remark] + "(无法修复,转新技)"
    else
      @rma_record.status = 'fixed'
      @rma_record.product&.status = 'fixed'
      @rma_record.done_by = current_user.true_name
      @rma_record.done_at = Time.now
      @rma_record.remark = params[:remark]
    end
    RmaRecord.transaction do
      @rma_record.save
      @rma_record.product&.save
    end
    redirect_to "/rmas"
  rescue ActiveRecord::RecordInvalid
    alert("alert('Failed')")
  end

end
