# status 0：待选中 1：待确认 2：已确认
class GraduationTopic < ApplicationRecord
  belongs_to :course, counter_cache: true
  belongs_to :user
  has_many :student_graduation_topics, :dependent => :destroy
  # 附件
  #acts_as_attachable
  has_many :attachments, as: :container, dependent: :destroy
  # 回复
  has_many :journals_for_messages, :as => :jour, :dependent => :destroy

  # 题库
  belongs_to :gtopic_bank, optional: true

  scope :search_by_name, ->(name) { where("graduation_topics.name LIKE ?", "%#{name}%")}
  scope :search_by_status, ->(status) {where(status: status)}


  #after_create :act_as_course_activity

  # 课题名称和描述字段长度限制
  validates :name, length: { maximum: 60,
                            too_long: "60 characters is the maximum allowed" }
  validates :description, length: { maximum: 5000,
                                    too_long: "5000 characters is the maximum allowed" }

  def status_name
    case self.status
    when 0
      "待选中"
    when 1
      "待确认"
    when 2
      "已确认"
    else
      "状态错误！"
    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

  # 跟选题后，查询所有选题的状态
  def student_graduation_topic_status
    sgt = self.student_graduation_topics
    status =
        if sgt.where(status: [0, 1]).count.zero?
          0
        elsif sgt.is_accepting.count.zero?
          2
        else
          1
        end
    return status
  end

  def teacher
    User.find(self.tea_id)
  end

  # 用户选题的状态
  def user_status(user_id)
    self.student_graduation_topics.where(user_id: user_id).last.try(:status)
  end

end
