#encoding=UTF-8
class StudentWorksScore < ActiveRecord::Base
  #reviewer_role: 1:教师评分;2:教辅评分;3:学生匿评
  attr_accessible :student_work_id, :user_id, :score, :comment, :reviewer_role

  belongs_to :user
  belongs_to :student_work
  has_many :journals_for_messages, :as => :jour, :dependent => :destroy
  has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy

  acts_as_attachable

  after_save :act_as_course_message

  # 评阅作品消息提示
  def act_as_course_message
    if self.student_work && self.student_work.user && self.student_work.homework_common.course
      receiver = self.student_work.user
      # 判断是第一次评阅还是更新 status:0 新建；1 更新
      if self.created_at == self.updated_at
        if self.comment.nil?
          self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id,
                                                       :viewed => false, :content => "作业评分：#{self.score}", :status=> false)
        else
          self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id,
                                                    :viewed => false, :content => "作业评分：#{self.score}&nbsp;&nbsp;&nbsp; 评语：#{self.comment}", :status=> false)
        end
      else # 更新
        if self.comment.nil?
          self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id,
                                                       :viewed => false, :content => "作业评分：#{self.score}", :status=> true)
        else
          self.course_messages << CourseMessage.new(:user_id => receiver.id, :course_id => self.student_work.homework_common.course.id,
                                                       :viewed => false, :content => "作业评分：#{self.score}&nbsp;&nbsp;&nbsp; 评语：#{self.comment}", :status=> true)
        end
      end
    end
  end

end
