class ExportShixunReportService
  include ApplicationHelper
  include StudentWorksHelper

  attr_reader :homework, :work

  def initialize(homework, work)
    @homework = homework
    @work     = work
  end

  def filename
    @_filename ||= "#{work.user&.student_id}_#{work.user.real_name}_#{homework.name}_#{Time.now.strftime('%Y%m%d_%H%M%S')}.pdf".gsub(' ', '-').gsub('/', '_')
  end

  def prepare_binding
    load_data

    binding
  end

  def to_pdf
    @_pdf ||= generate_pdf
  end

  private

  def generate_pdf
    file = File.open(Rails.root.join('app/templates/shixun_work/shixun_work.html.erb'))
    html = ERB.new(file.read).result(prepare_binding)
    kit = PDFKit.new(html)

    base_css = %w(app/templates/shared/main.css app/templates/shixun_work/shixun_work.css app/templates/shared/codemirror.css)
    base_css.each { |css| kit.stylesheets << Rails.root.join(css) }

    file = Tempfile.new(filename)
    kit.to_pdf(file.path)
    file
  end

  def load_data
    @course = homework.course
    @user   = @work.user
    @shixun = homework.shixuns.take
    @games  = @work.myshixun.games.includes(:challenge, :game_codes,:outputs) if @work.myshixun

    # 用户最大评测次数
    @user_evaluate_count = @games.pluck(:evaluate_count).sum if @games
    # @user_evaluate_count = @games.inject(0){|sum, g| sum + g.outputs.pluck(:query_index)&.first } if @games
    # 图形效率图的数据
    @echart_data    = student_efficiency(homework, @work)
    @myself_eff     = @echart_data[:efficiency_list].find { |item| item.last == @user.id }
    @myself_consume = @echart_data[:consume_list].find { |item| item.last == @user.id }
  end
end