class Admins::ShixunAuthorizationsController < Admins::BaseController
  def index
    params[:status] ||= 'pending'

    applies = ApplyAction.where(container_type: 'ApplyShixun')

    status =
      case params[:status]
      when 'pending'   then 0
      when 'processed' then [1, 2]
      when 'agreed'    then 1
      when 'refused'   then 2
      else 0
      end
    applies = applies.where(status: status) if status.present?

    # 关键字模糊查询
    keyword = params[:keyword].to_s.strip
    if keyword.present?
      applies = applies.joins('JOIN shixuns ON shixuns.id = apply_actions.container_id')
                  .where('shixuns.name LIKE :keyword', keyword: "%#{keyword}%")
    end

    applies = applies.order(updated_at: :desc)

    @applies = paginate applies.includes(user: :user_extension)

    shixun_ids = @applies.map(&:container_id)
    @shixun_map = Shixun.where(id: shixun_ids).each_with_object({}) { |s, h| h[s.id] = s }
  end

  def agree
    Admins::ShixunAuths::AgreeApplyService.call(current_apply, current_user)
    render_success_js
  end

  def refuse
    Admins::ShixunAuths::RefuseApplyService.call(current_apply, current_user, params)

    render_success_js
  end

  private

  def current_apply
    @_current_apply ||= ApplyAction.where(container_type: 'ApplyShixun').find(params[:id])
  end
end