class Admins::CompetitionPrizeUsersController < Admins::BaseController
  def index
    @competition = current_competition

    prize_users = Admins::CompetitionPrizeUserQuery.call(params.merge(competition_id: current_competition.id))
    include_class = [:competition_team, :competition_prize, :approver,
                     user: [:process_real_name_apply, :process_professional_apply, user_extension: :school]]
    @prize_users = paginate(prize_users.preload(include_class))

    respond_to do |format|
      format.js
      format.html
      format.xlsx do
        @all_prize_users = prize_users
        filename = "#{@competition.name}竞赛获奖人信息列表_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
        render xlsx: 'index', filename: filename
      end
    end
  end

  def create
    Admins::CreateCompetitionPrizeUsersService.call(current_competition)
    render_ok
  rescue ApplicationService::Error => ex
    render_error(ex.message)
  end

  def approve
    Admins::ApproveCompetitionPrizeUserService.call(current_prize_user, current_user)
    @prize_user = current_prize_user
  rescue ApplicationService::Error => ex
    render_js_error(ex.message, type: :notify)
  end

  def unapprove
    Admins::UnapproveCompetitionPrizeUserService.call(current_prize_user, current_user)
    @prize_user = current_prize_user
  rescue ApplicationService::Error => ex
    render_js_error(ex.message, type: :notify)
  end

  private

  def current_prize_user
    @_current_prize_user ||= current_competition.competition_prize_users.find(params[:id])
  end

  def current_competition
    @_current_competition ||= Competition.find(params[:competition_id])
  end
end