class Admins::RecruitmentsController < Admins::BaseController 
  before_action :require_business
  before_action :get_recruitment, only: [:history, :edit,:update, :destroy]

  def index 
    sort_by = Recruitment.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
    sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
    q = Recruitment.ransack(title_cont: params[:search])
    recruitments = q.result(distinct: true).reorder("#{sort_by} #{sort_direction},created_at desc")
    @recruitments = paginate(recruitments)
  end

  def new 
    @recruitment = Recruitment.new
  end

  def edit 
  end

  def create 
    @recruitment = Recruitment.new(recruitment_params)
    if @recruitment.save
      redirect_to admins_recruitments_path
      flash[:success] = '招聘信息创建成功'
    else
      redirect_to admins_recruitments_path
      flash[:danger] = @recruitment.errors.full_messages.join(",")
    end
  end

  def update 
    respond_to do |format|
      if @recruitment.update_attributes(recruitment_params)
        format.html do 
          redirect_to admins_recruitments_path
          flash[:success] = '招聘信息更新成功'
        end
        format.js {render_ok}
      else 
        format.html do 
          redirect_to admins_recruitments_path
          flash[:danger] = @recruitment.errors.full_messages.join(",")
        end
        format.js {render_js_error}
      end
    end
  end

  def destroy 
    if @recruitment.destroy 
      redirect_to admins_recruitments_path 
      flash[:success] = "招聘信息删除成功"
    else 
      redirect_to admins_recruitments_path 
      flash[:danger] = "招聘信息删除失败"
    end
  end

  private 
  def recruitment_params 
    params.require(:recruitment).permit!
  end

  def get_recruitment
    @recruitment = Recruitment.find_by(id: params[:id])
    unless @recruitment.present?
      redirect_to admins_recruitments_path 
      flash[:danger] = "招聘信息不存在"
    end
  end
end