class StudentJoinAttendanceRecordJob < ApplicationJob
  queue_as :default

  def perform(member_id)
    member = CourseMember.find_by(id: member_id)
    course = member&.course
    return if member.blank? || member.role != "STUDENT" || course.blank?

    current_date = Date.current
    current_end_time = Time.current.strftime("%H:%M:%S")
    group_ids = member.course_group_id == 0 ? [0] : [member.course_group_id, 0]

    # 删掉已创建的签到数据中不是目前所在分班的数据
    all_attendance_ids = course.course_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: group_ids}).pluck(:id)
    member.course_member_attendances.where.not(course_attendance_id: all_attendance_ids).delete_all


    # 正在签到的数据需要补上
    current_attendance_ids = course.course_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: group_ids}).
      where("(attendance_date = '#{current_date}' and end_time > '#{current_end_time}') or (attendance_date > '#{current_date}')").pluck(:id)

    attrs = %i[course_attendance_id user_id course_member_id course_id course_group_id created_at updated_at]

    same_attrs = {course_member_id: member_id, course_id: course.id, user_id: member.user_id, course_group_id: member.course_group_id}

    CourseMemberAttendance.bulk_insert(*attrs) do |worker|

      current_attendance_ids.each do |attendance_id|
        unless course.course_member_attendances.where(course_member_id: member_id, course_attendance_id: attendance_id).exists?
          worker.add same_attrs.merge(course_attendance_id: attendance_id)
        end
      end
    end
  end
end
