class Admins::CoursesController < Admins::BaseController
  before_action :find_course, except: [:index, :export_teacher_info]

  def index
    default_sort('created_at', 'desc')

    courses = Admins::CourseQuery.call(params)
    @ended_courses = courses.where(is_end: 1).size
    @processed_courses = courses.where(is_end: 0).size
    @courses = paginate courses.includes(:school, :students, :teacher_course_members, :informs, :course_videos, :attachments, :homework_commons, teacher: :user_extension)

    respond_to do |format|
      format.js
      format.html
      format.xlsx do
        @courses = courses.not_deleted.includes(:school, :students, :teacher_course_members, :informs, :course_videos,
                                                :live_links, :attachments, :homework_commons,
                                                teacher: [user_extension: :department])

        filename = "课堂列表_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
        render xlsx: 'index', filename: filename
      end
    end
  end

  def export_teacher_info
    courses = Course.where(school_id: params[:school_id], is_delete: 0)
    teachers = User.joins(:user_extension).where(user_extensions: {identity: 0},
                                                 id: CourseMember.where(role: %i[CREATOR PROFESSOR ASSISTANT_PROFESSOR], course_id: courses.not_deleted).pluck(:user_id))
    respond_to do |format|
      format.xlsx do
        @teachers = teachers.preload(:manage_courses, user_extension: :department)
        @begin_time = params[:begin_time]
        @end_time = params[:end_time]
        filename = "课堂教师信息_#{Time.current.strftime('%Y%m%d%H%M%S')}.xlsx"
        render xlsx: 'export_teacher_info', filename: filename
      end
    end
  end

  def destroy
    if @course.is_delete == 0
      @course.delete!
      Tiding.create!(user_id: current_user.id, trigger_user_id: current_user.id, container_id: @course.id,
                     container_type: 'DeleteCourse', tiding_type: 'System', belong_container: @course, extra: @course.name)
    end
  end

  def update
    unless @course.update_attributes!(setting_params)
      redirect_to admins_courses_path
      flash[:danger] = "更新失败"
    end
  end

  private

  def find_course
    @course = Course.find_by!(id: params[:id])
  end

  def setting_params
    params.permit(:homepage_show, :email_notify)
  end
end