# 任务发布 消息通知
class HomeworkCommonPushNotifyJob < ApplicationJob
  queue_as :notify

  def perform(homework_common_id, group_ids)
    homework = HomeworkCommon.find_by(id: homework_common_id)
    return if homework.blank?
    course = homework.course

    if group_ids.present?
      students = course.students.where(course_group_id: group_ids)
      subquery = course.teacher_course_groups.where(course_group_id: group_ids).select(:course_member_id)
      teachers = course.teachers.where(id: subquery)
    else
      students = course.students
      teachers = course.teachers
    end

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

    same_attrs = {
      trigger_user_id: homework.user_id, container_id: homework.id, container_type: 'HomeworkCommon',
      parent_container_id: homework.id, parent_container_type: 'HomeworkPublish',
      belong_container_id: homework.course_id, belong_container_type: 'Course',
      viewed: 0, tiding_type: 'HomeworkCommon'
    }
    Tiding.bulk_insert(*attrs) do |worker|
      teacher_ids = teachers.pluck(:user_id)
      if homework.tidings.where(parent_container_type: 'HomeworkPublish', user_id: teacher_ids).exists?
        teacher_ids.each do |user_id|
          worker.add same_attrs.merge(user_id: user_id)
        end
      end

      students.pluck(:user_id).each do |user_id|
        worker.add same_attrs.merge(user_id: user_id)
      end
    end
  end
end
