class MigrateCourseMembers < ActiveRecord::Migration[5.2]
  def change
    # add_column :course_groups, :position, :integer, default: 0

    Course.find_each do |course|
      position = 1
      course.course_groups.reorder("CONVERT(course_groups.name USING gbk) COLLATE gbk_chinese_ci ASC").each do |group|
        group.update_attribute(:position, position)
        position += 1
      end
    end


    add_column :course_groups, :course_members_count, :integer, default: 0

    CourseGroup.find_each do |g|
      CourseGroup.reset_counters g.id, :course_members
    end

    ActiveRecord::Base.transaction do
      begin
        Member.where("course_id != -1").includes(:member_roles).find_each(batch_size: 500) do |member|
          puts(member.id)
          member.member_roles.each do |role|
            course_member_role = role.role_id == 3 ? 1 : (role.role_id == 9 ? 2 : (role.role_id == 7 ? 3 : 4))
            member_group_id = role.role_id == 10 ? member.course_group_id : 0
            CourseMember.create!(course_id: member.course_id, user_id: member.user_id, course_group_id: member_group_id,
                                 graduation_group_id: member.graduation_group_id, role: course_member_role, is_active: role.is_current)
          end
        end
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("migrate_course_members 迁移失败！")
        raise ActiveRecord::Rollback
      end
    end
  end
end
