class StudentWorksScore < ApplicationRecord
  #appeal_status: 0：正常；1：申诉中，2：撤销申诉；3：申诉成功；4：申诉被拒绝；5：申诉失效
belongs_to :student_work
  belongs_to :user
  has_many :journals_for_messages, -> { order('created_on desc') }, as: :jour, dependent: :destroy
  has_one :student_works_scores_appeal, dependent: :destroy
  has_many :tidings, as: :container, dependent: :destroy
  has_many :attachments, as: :container, dependent: :destroy

  validates :comment, length: { maximum: 2000 }

  def show_name identity, user
    identity < Course::STUDENT || self.user == user || self.reviewer_role != 3
  end

  def allow_delete current_user, identity
    self.is_invalid && (current_user == self.user || identity < Course::STUDENT) ||
        (self.score.nil? && current_user == self.user)
  end

  # 匿评分
  def stu_score work_id
    StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM student_works_scores WHERE
                            student_work_id = #{work_id} AND reviewer_role = 3 AND score IS NOT NULL
                            AND appeal_status != 3 AND is_invalid = 0").first.score.try(:round, 2).to_f
  end

  # 助教平均分
  def ta_score work_id
      StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM student_works_scores WHERE
                                     student_work_id = #{work_id} AND reviewer_role = 2 AND score IS NOT NULL
                                     AND is_invalid = 0").first.score.try(:round, 2).to_f
  end
end
