class HomeworkPublishUpdateWorkStatusJob < ApplicationJob
  # 作业发布时更新学生（发布前已开启过实训）的作业状态和成绩
  queue_as :default

  def perform(group_ids, homework_id)
    # Do something later
    homework = HomeworkCommon.find_by(id: homework_id)
    return if homework.blank?
    course = homework.course
    return if course.blank?

    where_con = group_ids.nil? ? {course_id: homework.course_id, role: 4} : {course_id: homework.course_id, role: 4, course_group_id: group_ids}

    shixun_id = homework.homework_commons_shixun.try(:shixun_id)

    student_works = homework.student_works.joins("join course_members on student_works.user_id = course_members.user_id").
        where(course_members: where_con, work_status: 0).joins("join myshixuns on myshixuns.user_id = student_works.user_id").
        where(myshixuns: {shixun_id: shixun_id})

    student_works.each do |work|
      myshixun = Myshixun.find_by(shixun_id: shixun_id, user_id: work.user_id)

      work.work_status = 1
      work.commit_time = myshixun.updated_at
      work.update_time = myshixun.updated_at
      work.myshixun_id = myshixun.id

      work.save!

      HomeworksService.new.set_shixun_final_score work
    end
  end
end
