class Admins::Topic::OrganizationsController < Admins::Topic::BaseController
  before_action :find_organization, only: [:edit, :update, :destroy]

  def index 
    q = ::Topic::Organization.ransack(title_cont: params[:search])
    organizations = q.result(distinct: true)
    @organizations = paginate(organizations)
  end

  def new 
    @organization = ::Topic::Organization.new
  end

  def create 
    @organization = ::Topic::Organization.new(organization_params)
    if @organization.save 
      save_image_file(params[:image], @organization)
      redirect_to admins_topic_organizations_path
      flash[:success] = "新增合作机构logo成功"
    else
      redirect_to admins_topic_organizations_path
      flash[:danger] = "新增合作机构logo失败"
    end
  end

  def edit 
  end

  def update 
    @organization.attributes = organization_params
    if @organization.save 
      save_image_file(params[:image], @organization)
      redirect_to admins_topic_organizations_path
      flash[:success] = "更新合作机构logo成功"
    else  
      redirect_to admins_topic_organizations_path
      flash[:danger] = "更新合作机构logo失败"
    end
  end

  def destroy 
    if @organization.destroy 
      redirect_to admins_topic_organizations_path
      flash[:success] = "删除合作机构logo成功"
    else  
      redirect_to admins_topic_organizations_path
      flash[:danger] = "删除合作机构logo失败"
    end
  end

  private 
  def find_organization
    @organization = ::Topic::Organization.find_by_id(params[:id])
  end

  def organization_params 
    params.require(:topic_organization).permit(:title, :url, :order_index)
  end
end