class CompetitionPrizeUser < ApplicationRecord
  include AASM

  belongs_to :competition
  belongs_to :competition_team
  belongs_to :competition_prize
  belongs_to :user
  belongs_to :approver, class_name: 'User', optional: true # 审批人

  serialize :extra, JSON

  aasm(:status) do
    state :pending, initial: true
    state :approved

    event :approve do
      transitions from: [:pending], to: :approved, guard: :user_certified?
    end

    event :unapprove do
      transitions from: [:approved], to: :pending
    end
  end

  delegate :bank, :second_bank, :card_no, to: :extra, allow_nil: true

  def user_certified?
    user.authentication? && user.professional_certification?
  end

  def certificate_exist?
    Util::FileManage.exists?(self)
  end

  def certificate_url
    Util::FileManage.source_disk_file_url(self)
  end

  def certificate_path
    Util::FileManage.source_disk_filename(self)
  end

  def role_text
    return '队长' if leader?

    user.is_teacher? ? '教师' : '队员'
  end
end