class Ecs::CourseEvaluationsController < Ecs::CourseBaseController
  def index
    @course_evaluations = current_course.ec_course_evaluations.includes(:ec_course_evaluation_subitems)
  end

  def create
    course_evaluation = current_course.ec_course_evaluations.new
    @course_evaluation = Ecs::SaveCourseEvaluationService.call(course_evaluation, create_params)
    render 'show'
  end

  def update
    @course_evaluation = Ecs::SaveCourseEvaluationService.call(current_course_evaluation, update_params)
    render 'show'
  end

  def destroy
    current_course_evaluation.destroy!
    render_ok
  end

  def slimmer
    course_evaluations = current_course.ec_course_evaluations

    if params[:course_evaluation_id].present?
      course_evaluations = course_evaluations.where(id: params[:course_evaluation_id])
    end

    @course_evaluations = course_evaluations.includes(:ec_course_evaluation_subitems)
  end

  def average_score_import_template
    @course_evaluation = current_course_evaluation
    filename = "#{@course_evaluation.name}平均成绩导入模板_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
    render xlsx: 'average_score_import_template', filename: filename
  end

  def detail_score_import_template
    @course_evaluation = current_course_evaluation
    filename = "#{@course_evaluation.name}明细成绩导入模板_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
    render xlsx: 'detail_score_import_template', filename: filename
  end

  def import_student_achievement
    Ecs::ImportCourseStudentAchievementService.call(current_course_evaluation, params[:attachment_id])
    render_ok
  rescue Ecs::ImportCourseStudentAchievementService => ex
    render_error(ex.message)
  end

  private

  def create_params
    params.permit(:name, :evaluation_count, :status, course_evaluation_subitems: [:name])
  end

  def update_params
    params.permit(:name, :evaluation_count, :status, course_evaluation_subitems: [:id, :name])
  end

  def current_course_evaluation
    @_current_course_evaluation ||= current_course.ec_course_evaluations.find(params[:id])
  end
end