# 执行示例  RAILS_ENV=production bundle exec rake migrate_course_resource:import_attachments args=3835,2526
#

desc "同步课堂学生数据"
namespace :migrate_course_resource do
  if ENV['args']
    source_id = ENV['args'].split(",")[0] # 源课堂id
    target_id = ENV['args'].split(",")[1] # 目标课堂id
  end

  task import_attachments: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?

    source_course.attachments.each do |atta|
      if atta.course_second_category.present?
        target_category = CourseSecondCategory.find_by(name: atta.course_second_category.name, course_id: target_course.id, category_type: "attachment")
         unless target_category.present?
           course_module = target_course.course_modules.find_by(module_type: "attachment")
           target_category = CourseSecondCategory.create(name: atta.course_second_category.name, course_id: target_course.id,
                                                         category_type: "attachment", course_module_id: course_module&.id,
                                                         position: course_module&.course_second_categories&.count.to_i + 1)
         end
      end
      target_course.attachments << target_course.attachments.build(atta.attributes.except("id").merge(
        quotes: 0,
        downloads: 0,
        author_id: target_course.tea_id,
        created_on: Time.now,
        course_second_category_id: target_category&.id.to_i
      ))
    end
  end

  task import_videos: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?

    source_course.course_videos.each do |video|
      target_course.course_videos << CourseVideo.new(video_id: video.video_id)
    end
  end

  task import_homeworks: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?

    source_course.homework_commons.each do |homework|
      ActiveRecord::Base.transaction do
        if homework.course_second_category.present?
          target_category = CourseSecondCategory.find_by(name: homework.course_second_category.name, course_id: target_course.id, category_type: "shixun_homework")
          unless target_category.present?
            course_module = target_course.course_modules.find_by(module_type: "shixun_homework")
            target_category = CourseSecondCategory.create(name: homework.course_second_category.name, course_id: target_course.id,
                                                          category_type: "shixun_homework", course_module_id: course_module&.id,
                                                          position: course_module&.course_second_categories&.count.to_i + 1)
          end
        end

        # 复制作业的基本信息
        new_homework = HomeworkCommon.new(name: homework.name, user_id: target_course.tea_id, description: homework.description,
                                          homework_type: homework.homework_type, course_id: target_course.id,
                                          reference_answer: homework.reference_answer, course_second_category_id: target_category&.id.to_i)

        # 作业的基本设置复制
        new_homework.homework_detail_manual = HomeworkDetailManual.new
        new_homework_detail_manual = new_homework.homework_detail_manual
        new_homework_detail_manual.te_proportion = 0.7
        new_homework_detail_manual.ta_proportion = 0.3

        if new_homework.homework_type == "group"
          # 分组作业表的复制
          old_homework_group = homework.homework_detail_group
          new_homework.homework_detail_group = HomeworkDetailGroup.new
          new_homework.homework_detail_group.min_num = old_homework_group&.min_num
          new_homework.homework_detail_group.max_num = old_homework_group&.max_num
          new_homework.homework_detail_group.base_on_project = old_homework_group&.base_on_project
        end

        if new_homework.homework_type == "practice"
          # 分组作业表的复制
          new_homework.homework_commons_shixun = HomeworkCommonsShixun.new
          new_homework.homework_commons_shixun.shixun_id = homework.homework_commons_shixun&.shixun_id

          homework.position = HomeworkCommon.where(course_id:target_course.id, homework_type: "practice").pluck(:position).max.to_i + 1

          homework.homework_challenge_settings.each do |setting|
            new_homework.homework_challenge_settings << HomeworkChallengeSetting.new(challenge_id: setting.challenge_id,
                                                                                     shixun_id: setting.shixun_id, score: setting.score)
          end
        end

        # 附件
        if new_homework.save
          homework.attachments.try(:each) do |attachment|
            att = attachment.copy
            att.container_id = nil
            att.container_type = nil
            att.author_id = homework.user_id
            att.attachtype = attachment.attachtype || 1
            # att.attachtype = 1
            att.copy_from = attachment.id
            att.save!
            new_homework.attachments << att
          end
          new_homework_detail_manual.save if new_homework_detail_manual
          new_homework.homework_detail_group.save if new_homework.homework_detail_group
          new_homework.homework_commons_shixun.save if new_homework.homework_commons_shixun
          CreateStudentWorkJob.perform_later(new_homework.id)
        end
      end
    end
  end

  task import_exercises: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?

    source_course.exercises.each do |exercise|
      ActiveRecord::Base.transaction do
        new_exercise = Exercise.new(:exercise_name => exercise.exercise_name, :exercise_description => exercise.exercise_description,
                                    :user_id => target_course.tea_id, :course_id => target_course.id)
        # 复制试卷基本信息
        exercise.exercise_questions.each do |q|
          option = {
            :question_title => q.question_title,
            :question_type => q.question_type || 1,
            :question_number => q.question_number,
            :question_score => q.question_score,
            :shixun_name => q.shixun_name,
            :shixun_id => q.shixun_id,
            :is_ordered => q.is_ordered
          }
          exercise_question = new_exercise.exercise_questions.new option
          # question_type:5实训题;其他是非实训题
          if q.question_type != 5
            # 复制选择题题目选项
            q.exercise_choices.try(:each_with_index) do |choice, index|
              exercise_question.exercise_choices.new({choice_position: index+1, choice_text: choice.choice_text})
            end

            # 复制标准答案(填空题和问答题)  多空填空题的话,应该是原标准答案的exercise_choice_id,即为题空的位置。
            q.exercise_standard_answers.try(:each) do |answer|
              exercise_question.exercise_standard_answers.new({exercise_choice_id: answer.exercise_choice_id, answer_text: answer.answer_text})
            end
          else
            # 复制实训题
            q.exercise_shixun_challenges.try(:each_with_index) do |sc, index|
              exercise_question.exercise_shixun_challenges.new({position: index+1, challenge_id: sc.challenge_id,
                                                                shixun_id: sc.shixun_id, question_score: sc.question_score})
            end
          end
        end
        new_exercise.save!
      end
    end
  end

  task import_polls: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?

    source_course.polls.each do |poll|
      new_poll = Poll.new(:polls_name => poll.polls_name, :polls_description => poll.polls_description, :user_id => target_course.tea_id,
                          :polls_type => 'Course', :course_id => target_course.id)

      poll.poll_questions.try(:each) do |q|
        option = {
          :question_title => q.question_title,
          :question_type => q.question_type || 1,
          :is_necessary => q.is_necessary,
          :question_number => q.question_number,
          :max_choices => q.max_choices,
          :min_choices => q.min_choices
        }
        poll_question = new_poll.poll_questions.new option
        q.poll_answers.try(:each_with_index) do |choice, index|
          poll_question.poll_answers.new({answer_position: index+1, answer_text: choice.answer_text})
        end
      end
      new_poll.save!
    end
  end


  task import_members: :environment do
    source_course = Course.find_by(id: source_id)
    target_course = Course.find_by(id: target_id)
    return if source_course.blank? || target_course.blank?


    # 先把target——course中的老师创建分班权限
    target_course.teachers.each do |member|
      if member.teacher_course_groups.blank?
        target_course.course_groups.each do |group|
          TeacherCourseGroup.create!(course_group_id: group.id, course_id: target_course.id, course_member_id: member&.id, user_id: member&.user_id)
        end
      end
    end

    source_course.course_members.where(role: %i[PROFESSOR ASSISTANT_PROFESSOR]).each do |teacher|
      new_member = target_course.teachers.find_by(user_id: teacher.user_id)
      unless new_member.present?
        new_member = CourseMember.create!(course_id: target_course.id, user_id: teacher.user_id, role: teacher.role)
      end
    end

    source_course.course_groups.each do |group|
      unless target_course.course_groups.where(name: group.name).exists?
        new_group = CourseGroup.create!(course_id: target_course.id, name: group.name, position: target_course.course_groups.pluck(:position).max.to_i + 1)
      else
        new_group = target_course.course_groups.find_by(name: group.name)
      end
      new_user_ids = []
      group.course_members.where(role: 4).each do |member|
        new_member = target_course.students.find_by(user_id: member.user_id)
        if new_member.present?
          new_member.update_attributes(course_group_id: new_group.id)
        else
          CourseMember.create!(course_id: target_course.id, course_group_id: new_group.id, user_id: member.user_id, role: member.role)
          new_user_ids << member.user_id
        end
      end

      CourseAddStudentCreateWorksJob.perform_later(target_course.id, new_user_ids) unless new_user_ids.blank?

      group.teacher_course_groups.each do |teacher_group|
        member = CourseMember.find_by(course_id: target_course.id, user_id: teacher_group.user_id, role: %i[CREATOR PROFESSOR ASSISTANT_PROFESSOR])
        if member.present? && !member.teacher_course_groups.where(course_group_id: new_group.id).exists?
          TeacherCourseGroup.create!(course_group_id: new_group.id, course_id: target_course.id, course_member_id: member&.id, user_id: member&.user_id)
        end
      end
    end

    user_ids = []
    source_course.students.where(course_group_id: 0).each do |member|
      new_member = target_course.students.find_by(user_id: member.user_id)
      if new_member.present?
        new_member.update_attributes(course_group_id: 0)
      else
        CourseMember.create!(course_id: target_course.id, course_group_id: 0, user_id: member.user_id, role: member.role)
        user_ids << member.user_id
      end
    end
    CourseAddStudentCreateWorksJob.perform_later(target_course.id, user_ids) unless user_ids.blank?

  end

  end