class Competitions::PrizesController < Competitions::BaseController
  before_action :require_prize_user!

  helper_method :current_prize_user

  def show
    self_prizes = current_competition.competition_prize_users.where(user_id: current_prize_user.id).includes(:competition_team).order(:competition_prize_id)

    @leader = self_prizes.any?{ |prize_user| prize_user.leader? && prize_user.competition_prize.category == 'bonus' } # 是否为队长并且有奖金奖励
    if @leader || current_user.admin_or_business?
      @bank_account = self_prizes.find(&:leader?)&.extra
      @bank_account_editable = self_prizes.select(&:leader?).all?(&:pending?)
    end

    @self_prizes = self_prizes.select(&:certificate_exist?) # 个人证书quit
    @team_prizes = self_prizes.map(&:competition_team).uniq.select(&:certificate_exists?) # 团队证书

    prize_users = current_competition.competition_prize_users.where(competition_team_id: self_prizes.map(&:competition_team_id))
                    .includes(:competition_team, user: [:user_extension, :process_real_name_apply, :process_professional_apply])

    @prize_user_map = prize_users.group_by(&:competition_team)
  end

  private

  def require_prize_user!
    return if current_competition.competition_prize_users.exists?(user: current_prize_user)
    return if current_user.admin_or_business? || current_user.id == current_prize_user.id

    render_forbidden
  end

  def current_prize_user
    @_current_prize_user ||= User.find(params[:user_id])
  end
end