namespace :graduation_task do
  desc "start/end/comment graduation tasks"

  task :publish => :environment do
    tasks = GraduationTask.where("publish_time is not null and publish_time <= '#{Time.now}' and status = 0")
    tasks.each do |task|
      task.update_attributes(status: 1)
      GraduationTaskPublishNotifyJob.perform_later(task.id)

      task.course_acts << CourseActivity.new(user_id: task.user_id, course_id: task.course_id) if !task.course_acts.exists?
    end
  end

  task :nearly_end => :environment do
    tasks = GraduationTask.where("end_time <=? and end_time > ?", Time.now + 86400, Time.now + 84600)
    tasks.each do |task|
      if task.tidings.where(parent_container_type: "NearlyEnd").count == 0
        course = task.course
        tid_str = ""
        task.graduation_works.where(work_status: 0).find_each do |student|
          tid_str += "," if tid_str != ""
          tid_str += "(#{student.user_id}, #{task.user_id}, #{task.id}, 'GraduationTask', #{task.id}, 'NearlyEnd',
                      #{course.id}, 'Course', 0, 'GraduationTask', '#{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

  task :end => :environment do
    tasks = GraduationTask.where("end_time <= '#{Time.now}' and status = 1")
    tasks.each do |task|
      task.update_attributes(status: 2)
    end
  end

  task :cross_comment_start => :environment do
    tasks = GraduationTask.where("cross_comment = 1 and comment_time is not null and comment_time <= '#{Time.now}' and status = 2")
    tasks.each do |task|
      if task.comment_status == 4
        GraduationTaskCrossCommentJob.perform_later(task.id)
      end
      task.update_attributes(status: 3)

      # 给老师发消息
      tid_str = ""
      task.course.teachers.find_each do |member|
        tid_str += "," if tid_str != ""
        tid_str += "(#{member.user_id}, #{task.user_id}, #{task.id}, 'GraduationTask', #{task.id}, 'CrossComment',
                    #{task.course.id}, 'Course', 0, 'GraduationTask', '#{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