# 执行示例  bundle exec rake migrate_exam_item:item args=2933
# 参数是试卷id，不传参则是迁移所有的
desc "迁移试卷库中的试题"

namespace :migrate_exam_item do
  if ENV['args']
    exam_id = ENV['args'].split(",")[0] # 对应试卷的id
  end

  task item: :environment do
    if exam_id.present?
      exams = ExaminationBank.where(id: exam_id)
    else
      exams = ExaminationBank.all
    end

    exams.each do |exam|
      exam.examination_items.includes(:container, :examination_item_choices, :examination_item_analysis, item_bank: [:container, :item_choices, :item_analysis]).each do |item|
        item_bank = item.item_bank
        if item_bank.present?
          item.update(name: item_bank.name)

          if item.item_type == "PROGRAM"
            if item.container.present? && item_bank.container.present?
              item.container&.update(name: item_bank.container.name, description: item_bank.container.description)
            end
          else
            item.examination_item_choices.each_with_index do |choice, index|
              bank_choice = item_bank.item_choices[index]
              choice.update(choice_text: bank_choice.choice_text) if bank_choice.present?
            end
          end

          item.examination_item_analysis&.update(analysis: item_bank.analysis) if item_bank.analysis.present?
        end

        puts item.id
      end
    end
  end
end