class MigrateCourseSecondCategory < ActiveRecord::Migration[5.2]
  def change
    add_column :homework_commons, :course_second_category_id, :integer, default: 0
    add_index :homework_commons, :course_second_category_id
    add_column :course_second_categories, :course_module_id, :integer
    add_index :course_second_categories, :course_module_id

    Course.find_each do |course|
      homework_position = 1
      course_module = course.course_modules.where(module_type: "shixun_homework").first
      course.course_homework_categories.reorder("CONVERT(name USING gbk) COLLATE gbk_chinese_ci ASC").find_each do |category|
        new_category = CourseSecondCategory.create!(course_id: course.id, name: category.name, category_type: "shixun_homework",
                                                    position: homework_position, course_module_id: course_module.id)
        course.homework_commons.where(course_homework_category_id: category.id).update_all(course_second_category_id: new_category.id)
        homework_position += 1
      end
    end
  end
end
