class Admins::FeedbacksController < Admins::BaseController
  before_action :require_business
  before_action :get_feedback, only: [:new_history, :create_history, :destroy]

  def index 
    sort_by = Feedback.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_at'
    sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
    feedbacks = Feedback.order("#{sort_by} #{sort_direction}")
    @feedbacks = paginate(feedbacks)
  end

  def destroy 
    if @feedback.destroy 
      redirect_to admins_feedbacks_path 
      flash[:success] = "反馈意见删除成功"
    else 
      redirect_to admins_feedbacks_path 
      flash[:danger] = "反馈意见删除失败"
    end
  end

  def new_history 
    @feedback_message_history = FeedbackMessageHistory.new
  end

  def create_history 
    @feedback_message_history = @feedback.feedback_message_histories.new(feedback_message_history_params)
    @feedback_message_history.user = current_user
    if @feedback_message_history.save
      redirect_to admins_feedbacks_path 
      flash[:success] = "发送通知成功"
    else 
      redirect_to admins_feedbacks_path 
      flash[:danger] = @feedback_message_history.errors.full_messages.join(", ")
    end
  end

  private  
  def feedback_params 
    params.require(:feedback).permit!
  end

  def feedback_message_history_params 
    params.require(:feedback_message_history).permit(:title, :content)
  end

  def get_feedback 
    @feedback = Feedback.find_by_id(params[:id])
  end
end