class Admins::HackImportsController <  Admins::BaseController

  def index
    params[:sort_by] ||= 'created_at'
    params[:sort_direction] ||= 'desc'
    item_banks = Admins::ImportHackQuery.call(params)
    @item_banks = paginate item_banks.preload([container: :hack_codes], :user, :sub_discipline)
  end

  def create
    return render_error('请上传正确的文件') if params[:file].blank? || !params[:file].is_a?(ActionDispatch::Http::UploadedFile)
    filename = File.basename(params[:file].original_filename, ".*")
    sub_discipline = SubDiscipline.find_by(name: filename)
    unless sub_discipline.present?
      render_error "请先创建'#{filename}'课程后再导入题库" and return
    end

    result = Admins::ImportHackService.call(params[:file].to_io, sub_discipline.id)
    render_ok(result)
  rescue Admins::ImportHackService::Error => ex
    render_error(ex)
  end

  def down_template
    send_file(Rails.root.join("excel_template/import_hacks_template.xlsx"), filename: "OJ试题导入模版.xlsx")
  end

end
