# 学生提交作品 消息通知
class SubmitGraduationWorkNotifyJob < ApplicationJob
  queue_as :notify

  def perform(task_id, student_ids)
    task = GraduationTask.find_by(id: task_id)
    return if task.blank? || student_ids.blank?
    course = task.course

    attrs = %i[user_id trigger_user_id container_id container_type parent_container_id parent_container_type
              belong_container_id belong_container_type tiding_type viewed created_at updated_at]

    same_attrs = {
      container_type: 'GraduationWork', parent_container_id: task.id, parent_container_type: 'GraduationTask',
      belong_container_id: course.id, belong_container_type: 'Course', tiding_type: 'GraduationTask', viewed: 0
    }
    Tiding.bulk_insert(*attrs) do |worker|
      student_ids.each do |user_id|
        next unless User.exists?(id: user_id)

        work = task.graduation_works.find_by(user_id: user_id)
        member = course.students.find_by(user_id: user_id)
        next if work.blank? || member.blank?

        attrs = same_attrs.merge(trigger_user_id: user_id, container_id: work.id)

        member.member_teachers.find_each do |teacher|
          worker.add attrs.merge(user_id: teacher.user_id)
        end
      end
    end
  end
end
