class HomeworkAbsencePenaltyCalculationJob < ApplicationJob
  queue_as :end

  def perform(homework_common_id)
    homework_common = HomeworkCommon.find_by(id: homework_common_id)
    return if homework_common.blank?

    #计算缺评扣分 参与匿评
    work_ids = homework_common.student_works.has_committed.pluck(:id)
    homework_detail_manual = homework_common.homework_detail_manual

    homework_common.student_works.where("work_status != 0").each do |student_work|
      absence_penalty_count = student_work.user.student_works_evaluation_distributions.where(student_work_id: work_ids).count -
          student_work.user.student_works_scores.where(student_work_id: work_ids, reviewer_role: 3).group_by(&:student_work_id).count

      student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * homework_detail_manual.absence_penalty : 0
      student_work.save
    end

    # 未参与匿评
    if homework_detail_manual.no_anon_penalty == 0
      all_dis_eva = StudentWorksEvaluationDistribution.where(student_work_id: work_ids)
      has_sw_count = all_dis_eva.select("distinct user_id").count
      anon_count = all_dis_eva.count / has_sw_count
      homework_common.student_works.where("work_status != 0").each do |student_work|
        if student_work.user.student_works_evaluation_distributions.where(student_work_id: work_ids).count == 0
          student_work.absence_penalty = homework_detail_manual.absence_penalty * anon_count
          student_work.save
        end
      end
    end
  end
end
