class Admins::Topic::FriendlyLinksController < Admins::Topic::BaseController
  before_action :require_business
  before_action :find_friendly_link, only: [:edit, :update, :destroy]

  def index
    @friendly_links = paginate(::Topic::FriendlyLink)

    @friendly_links = paginate(::Topic::FriendlyLink.where("title like ?", "%#{params[:search]}%")) if params[:search].present?
  end

  def new 
    @friendly_link = ::Topic::FriendlyLink.new
  end

  def create 
    Rails.logger.info friendly_link_params
    @friendly_link = ::Topic::FriendlyLink.new(friendly_link_params)
    if @friendly_link.save 
      save_image_file(params[:image], @friendly_link)
      redirect_to admins_topic_friendly_links_path
      flash[:success] = "新增friendly_link成功"
    else
      redirect_to admins_topic_friendly_links_path
      flash[:danger] = "新增friendly_link失败"
    end
  end

  def edit 
  end

  def update 
    @friendly_link.attributes = friendly_link_params
    if @friendly_link.save 
      save_image_file(params[:image], @friendly_link)
      redirect_to admins_topic_friendly_links_path
      flash[:success] = "更新friendly_link成功"
    else  
      redirect_to admins_topic_friendly_links_path
      flash[:danger] = "更新friendly_link失败"
    end
  end

  def destroy 
    if @friendly_link.destroy 
      redirect_to admins_topic_friendly_links_path
      flash[:success] = "删除friendly_link成功"
    else  
      redirect_to admins_topic_friendly_links_path
      flash[:danger] = "删除friendly_link失败"
    end
  end

  private 
  def find_friendly_link
    @friendly_link = ::Topic::FriendlyLink.find_by_id(params[:id])
  end

  def friendly_link_params 
    params.require(:topic_friendly_link).permit(:title, :order_index, :url)
  end
end