# 生成竞赛团体证书Job
class GenerateCompetitionTeamCertificateJob < ApplicationJob
  queue_as :notify

  def perform(competition_team_id)
    @team = CompetitionTeam.find_by(id: competition_team_id)
    @prize = @team&.competition_prize_users&.first&.competition_prize
    return if @team.blank? || !@prize.team_certificate_exists? || @team.certificate_exists?

    members = @team.team_members.includes(user: :user_extension).to_a

    @member_names = members.select { |m| !m.user.is_teacher? }.map(&:user_name).join('、')
    @teacher_names = members.select { |m| m.user.is_teacher? }.map(&:user_name).join('、')

    file = File.open(Rails.root.join("app/templates/competition_certificates/team.html.erb"))
    html = ERB.new(file.read).result(binding)
    kit = PDFKit.new(html, page_width: 842, page_height: 595)

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