# 毕设任务的交叉评阅分配
class GraduationTaskCrossCommentJob < ApplicationJob
  queue_as :default

  def perform(graduation_task_id)
    task = GraduationTask.find_by(id: graduation_task_id)
    return if task.blank?

    course = task.course
    task.graduation_task_group_assignations.each do |assignation|
      graduation_group = assignation.graduation_group
      assign_group = assignation.assign_group
      if graduation_group.present? && assign_group.present?
        course_group_ids = course.teacher_course_groups.where(course_member_id: graduation_group.course_members.pluck(:id)).pluck(:course_group_id)
        graduation_works = task.graduation_works.where(user_id: course.course_members.where(:course_group_id => course_group_ids).map(&:user_id),
                                                       work_status: [1, 2])
        if assign_group.course_members.count <= task.comment_num
          graduation_works.each do |work|
            assign_group.course_members.each do |member|
              work.graduation_work_comment_assignations << GraduationWorkCommentAssignation.new(
                  graduation_group_id: assign_group.id, user_id: member.user_id, graduation_task_id: task.id)
            end
          end
        else
          member_user_ids = assign_group.course_members.pluck(:user_id)
          count = 0
          graduation_works.each do |work|
            for i in 1 .. task.comment_num
              assign_user_id = member_user_ids[count % member_user_ids.size]
              work.graduation_work_comment_assignations << GraduationWorkCommentAssignation.new(
                  graduation_group_id: assign_group.id, user_id: assign_user_id, graduation_task_id: task.id)
              count += 1
            end
          end
        end
      end
    end
  end
end
