# 生成竞赛个人证书Job
class GenerateCompetitionPersonalCertificateJob < ApplicationJob
  queue_as :notify

  def perform(prize_user_id)
    @prize_user = CompetitionPrizeUser.find_by(id: prize_user_id)
    return if @prize_user.blank? || @prize_user.certificate_exist?

    template = @prize_user.user.is_teacher? ? 'teacher' : 'personal'
    file = File.open(Rails.root.join("app/templates/competition_certificates/#{template}.html.erb"))
    html = ERB.new(file.read).result(binding)
    kit = PDFKit.new(html, page_width: 842, page_height: 595)

    path = @prize_user.certificate_path
    dir = File.dirname(path)
    FileUtils.mkdir_p(dir) unless File.directory?(dir)
    kit.to_pdf(path)
  end
end