#coding=utf-8
namespace :course do
  desc "course end"
  task :nearly_course_end => :environment do
    courses = Course.where("end_date <= '#{Date.today + 1.day}' and is_end = 0")
    courses.each do |course|
      if Tiding.where(:parent_container_type => "NearlyLateEnd", :belong_container_id => course.id, :belong_container_type => "Course").count == 0
        tid_str = ""
        course.graduation_tasks.where("status > 1 and allow_late = 1").each do |task|
          task.graduation_works.where(:work_status => 0).find_each do |work|
            tid_str += "," if tid_str != ""
            tid_str += "(#{work.user_id}, #{task.user_id}, #{task.id}, 'GraduationTask', #{task.id}, 'NearlyLateEnd', #{course.id}, 'Course', 0, 'GraduationTask', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
          end
        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
    courses = Course.where("end_date <= '#{Date.today}' and is_end = 0")
    courses.each do |course|
      course.update_attribute(:is_end, 1)
      tid_str = ""
      course.members.includes(:roles).where("roles.id" => [3,7,9]).each do |mem|
        tid_str += "," if tid_str != ""
        tid_str += "(#{mem.user_id}, #{course.tea_id}, #{course.id}, 'ArchiveCourse', #{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, 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