#coding=utf-8
#需要在0点以后执行
namespace :exercise_deadline_warn do
  desc "exercise deadline warn"
  task :deadline_warn => :environment do
    puts "--------------------------------exercise_nearly_end start"
    # 统一设置发布时间的测验
    exercises = Exercise.where("exercise_status = 2 and unified_setting = 1 and end_time <=? and end_time > ?", Time.now + 86400, Time.now + 84600)
    exercises.each do |exercise|
      if exercise.tidings.where(parent_container_type: "NearlyEnd").count == 0
        course = exercise.course
        tid_str = ""
        exercise.exercise_users.where(commit_status: 0).find_each do |student|
          tid_str += "," if tid_str != ""
          tid_str += "(#{student.user_id}, #{exercise.user_id}, #{exercise.id}, 'Exercise', #{exercise.id}, 'NearlyEnd',
                      #{course.id}, 'Course', 0, 'Exercise', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
        end
        if tid_str != ""
          tid_sql = "insert into tidings (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) values" + tid_str
          ActiveRecord::Base.connection.execute tid_sql
        end
      end
    end

    # 分组设置发布时间的测验
    exercise_group_settings = ExerciseGroupSetting.where("end_time <=? and end_time > ?", Time.now + 86400, Time.now + 84600)
    exercise_group_settings.each do |exercise_group|
      exercise = exercise_group.exercise
      if exercise.present?
        course = exercise.course
        members = course.students.where(course_group_id: exercise_group.course_group_id)
        if exercise.tidings.where(parent_container_type: "NearlyEnd", user_id: members.pluck(:user_id)).count == 0
          tid_str = ""
          exercise.exercise_users.where(commit_status: 0, user_id: members.pluck(:user_id)).find_each do |member|
            tid_str += "," if tid_str != ""
            tid_str += "(#{member.user_id},#{exercise.user_id}, #{exercise.id}, 'Exercise', #{exercise.id}, 'NearlyEnd',
                        #{course.id}, 'Course', 0, 'Exercise', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
          end
          if tid_str != ""
            tid_sql = "insert into tidings (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) values" + tid_str
            ActiveRecord::Base.connection.execute tid_sql
          end
        end
      end
    end
    puts "--------------------------------exercise_nearly_end end"
  end
end