class Admins::Topic::CkJsForumsController < Admins::Topic::BaseController
  before_action :require_business
  before_action :find_ck_js_forum, only: [:edit, :update, :destroy]

  def index 
    @topics = ::Topic.where(type: ['Topic::JsForum', 'Topic::CkForum'])
    if params[:search].present?
      q = @topics.ransack(identifier_cont: params[:search]) if params[:search].present?
      @topics = q.result(distinct: true) 
    end
    @ck_js_forums = paginate(@topics)
  end

  def new 
    @ck_js_forum = ::Topic.new
  end

  def create 
    if params[:type] == 'Topic::JsForum'
      @ck_js_forum = ::Topic::JsForum.new(ck_js_forums_params)
    elsif params[:type] == 'Topic::CkForum'
      @ck_js_forum = ::Topic::CkForum.new(ck_js_forums_params)
    else
      redirect_to admins_topic_ck_js_forums_path
      flash[:danger] = "新增创客/竞赛失败"
    end
    if @ck_js_forum.save 
      redirect_to admins_topic_ck_js_forums_path
      flash[:success] = "新增创客/竞赛成功"
    else
      redirect_to admins_topic_ck_js_forums_path
      flash[:danger] = "新增创客/竞赛失败"
    end
  end

  def edit 
  end

  def update 
    @ck_js_forum.attributes = update_ck_js_forum_params
    if @ck_js_forum.save 
      redirect_to admins_topic_ck_js_forums_path
      flash[:success] = "更新创客/竞赛成功"
    else  update_ck_js_forum_params
      redirect_to admins_topic_ck_js_forums_path
      flash[:danger] = "更新创客/竞赛失败"
    end
  end

  def destroy 
    if @ck_js_forum.destroy 
      redirect_to admins_topic_ck_js_forums_path
      flash[:success] = "删除平台动态成功"
    else  
      redirect_to admins_topic_ck_js_forums_path
      flash[:danger] = "删除平台动态失败"
    end
  end

  private 
  def find_ck_js_forum
    @ck_js_forum = ::Topic.find_by_id(params[:id])
  end

  def ck_js_forums_params 
    params.require(:topic).permit(:title, :identifier, :description, :labels, :order_index)
  end

  def update_ck_js_forum_params 
    if @ck_js_forum.type == 'Topic::JsForum'
      params.require(:topic_js_forum).permit(:title, :description, :identifier, :labels, :order_index)
    else 
      params.require(:topic_ck_forum).permit(:title, :description, :identifier, :labels, :order_index)
    end
  end
end