class Admins::TopicsController < Admins::Topic::BaseController
  before_action :require_business
  before_action :find_topic, only: [:edit, :update, :destroy, :show]

  def index
    scope = ::Topic.with_mutil_type(params[:topic_type])
    scope = scope.where(location: params[:location]) if params[:location].present?
    scope = scope.where(type: params[:type]) if params[:type].present?
    scope = scope.ransack(title_cont: params[:search])
    topics = scope.result(distinct: true)
    @topics = paginate(topics)
  end

  def new
    @topic = ::Topic.new
  end

  def create
    @topic = topic_model.new(topic_params)
    params[:topic_type] = @topic.type_group_name
    if @topic.save
      save_image_file(params[:image], @topic) if params[:image].present?
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:success] = "新增成功"
    else
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:danger] = "新增失败"
    end
  end

  def show
  end

  def edit
  end

  def update
    @topic.attributes = topic_params
    if @topic.save!
      save_image_file(params[:image], @topic) if params[:image].present?
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:success] = "更新成功"
      return
    else
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:danger] = "更新失败"
      return
    end
  end

  def destroy
    if @topic.destroy
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:success] = "删除成功"
    else
      redirect_to admins_topics_path(topic_type: params[:topic_type])
      flash[:danger] = "删除失败"
    end
  end

  private

  def find_topic
    @topic = topic_model.find(params[:id])
    params[:topic_type] = @topic.type_group_name
  end

  def topic_model
    ::Topic
  end

  def topic_params
    params.require(:topic).permit(:type, :title, :uuid, :url, :order_index,
                                  :location, :identifier, :labels, :description, :date)
  end
end