#encoding: utf-8
class GraduationTask < ActiveRecord::Base
  include Redmine::SafeAttributes
  belongs_to :user
  belongs_to :course
  # attr_accessible :allow_late, :base_on_project, :comment_num, :comment_status, :comment_time, :cross_comment, :description, :end_time, :late_penalty, :max_num, :min_num, :name, :open_score, :open_work, :publish_time, :status, :task_type
  safe_attributes :name, :description, :task_type
  acts_as_attachable
  # task_type 1: 普通作业  2:分组作业
  # status 0:未发布  1:已发布  2:已截止  3:评阅中  4:评阅已截止
  # comment_status 1:随机分配  2:指导老师手动分配  3:答辩组内老师互评  4:答辩组间老师互评

  has_many :journals_for_messages, :as => :jour, dependent: :destroy
  has_many :praise_tread, as: :praise_tread_object, dependent: :destroy
  has_one :praise_tread_cache, as: :object, dependent: :destroy
  has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy
  has_many :tidings, as: :container, dependent: :destroy

  has_many :graduation_task_group_assignations, dependent: :destroy

  has_many :graduation_works, dependent: :destroy, :conditions => "graduation_works.is_delete = 0"
  has_many :graduation_work_scores, dependent: :destroy
  has_many :graduation_work_comment_assignations, dependent: :destroy
  # after_create :act_as_course_activity

  def task_type_name
    task_type == 1 ? "普通作业" : "分组作业"
  end

  def create_task_tidings
    tid_str = ""
    self.course.members.find_each do |member|
      tid_str += "," if tid_str != ""
      tid_str += "(#{member.user_id}, #{self.user_id}, #{self.id}, 'GraduationTask', #{self.id}, 'TaskPublish', #{self.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

  #课程动态公共表记录
  def act_as_course_activity
    if self.course
      if self.course_acts.size == 0
        self.course_acts << CourseActivity.new(:user_id => self.user_id,:course_id => self.course_id)
      end
    end
  end
end