class Ecs::EcCoursesController < Ecs::BaseController
  before_action :check_major_manager_permission!, only: [:create, :import, :destroy]

  def index
    ec_courses = current_year.ec_courses

    @count = ec_courses.count

    @ec_courses = paginate ec_courses.includes(:course_managers)

    course_ids = @ec_courses.map(&:id)
    # 课程目标数
    @target_count_map             = EcCourseTarget.where(ec_course_id: course_ids).group(:ec_course_id).count
    # 考核方式数
    @evaluation_count_map         = EcCourseEvaluation.where(ec_course_id: course_ids).group(:ec_course_id).count
    # 评价方法数
    @achievement_method_count_map = EcCourseAchievementMethod.where(ec_course_id: course_ids).group(:ec_course_id).count
    # 毕业目标数
    @graduation_subitem_count_map = EcGraduationSubitemCourseTarget.joins(:ec_course_target)
                                      .where(ec_course_targets: { ec_course_id: course_ids })
                                      .group('ec_course_targets.ec_course_id')
                                      .count('distinct ec_graduation_subitem_id')
    # 已达成毕业目标数
    @completed_subitem_count_map = EcCourseSupport.joins(:ec_graduation_requirement_calculation)
                                     .where(ec_course_id: course_ids)
                                     .where(ec_graduation_requirement_calculations: { status: 1 })
                                     .group('ec_course_supports.ec_course_id')
                                     .count('distinct ec_graduation_subitem_id')
  end

  def search
    ec_courses = current_year.ec_courses

    search = params[:search].to_s.strip
    if search
      ec_courses = ec_courses.where('name LIKE ?', "%#{search}%")
    end

    @count      = ec_courses.count
    @ec_courses = paginate ec_courses
  end

  def create
    create_params = params.permit(:name)
    @ec_course = Ecs::CreateCourseService.call(current_year, create_params)
  rescue Ecs::CreateCourseService::Error => ex
    render_error(ex.message)
  end

  def destroy
    current_course.destroy!
    render_ok
  end

  def import
    success_count = Ecs::ImportCourseService.call(current_year, params[:attachment_id])
    render_ok(success_count: success_count)
  rescue Ecs::ImportCourseService::Error => ex
    render_error(ex.message)
  end

  def link_course
    link_params = params.permit(:course_id)
    Ecs::LinkCourseService.call(current_course, link_params)
    render_ok
  rescue Ecs::LinkCourseService::Error => ex
    render_error(ex.message)
  end

  private

  def current_course
    @_current_course ||= current_year.ec_courses.find(params[:id])
  end
end
