class Migrate2796ExerciseScore < ActiveRecord::Migration[5.2]
  def calculate_student_score(exercise,user)
    score1 = 0.0  #实训题
    exercise_questions = exercise.exercise_questions.includes(:exercise_standard_answers)
    exercise_questions.each do |q|
      answers_content = q.exercise_answers.where(user_id: user.id)  #学生的答案
      if q.question_type <= 2  #为选择题或判断题时
        if answers_content.present?   #学生有回答时
          answer_choice_array = []
          answers_content.each do |a|
            answer_choice_array.push(a.exercise_choice.choice_position)  #学生答案的位置
          end
          user_answer_content = answer_choice_array.sort
          standard_answer = q.exercise_standard_answers.pluck(:exercise_choice_id).sort  #该问题的标准答案，可能有多个

          #TODO: 旧版多选题的标准答案是放在一个里面的，新版又做成了一个题有多个标准答案（exercise_choice_id存放的是标准答案的位置..）
          if q.question_type == 1 && standard_answer.size == 1
            standard_answer = standard_answer.first.to_s.split("").map(&:to_i).sort
          end

          if user_answer_content == standard_answer  #答案一致,多选或单选才给分，答案不对不给分
            if standard_answer.size > 0
              q_score_1 = q.question_score
              # q_score_1 = (q.question_score.to_f / standard_answer.count)   #当多选答案正确时，每个answer的分数均摊。
            else
              q_score_1 = 0.0
            end
            answers_content.update_all(:score => q_score_1)
            score1 = score1 + q.question_score
          else
            answers_content.update_all(:score => -1.0)
            score1 += 0.0
          end
        else
          score1 += 0.0
        end
      end
    end
    score1
  end

  def change
    exercise = Exercise.find_by(id: 2796)
    if exercise
      exercise_users = exercise.exercise_users.where("start_at is not null and commit_status = 0")
      exercise_users.each do |exercise_user|
        calculate_score = calculate_student_score(exercise, exercise_user.user)
        subjective_score = exercise_user.subjective_score
        total_score_subjective_score = subjective_score < 0.0 ? 0.0 : subjective_score
        total_score = calculate_score + total_score_subjective_score
        if exercise_user.end_at.nil?
          exercise_user.update_attributes!(score:total_score,objective_score:calculate_score,end_at:exercise.end_time,commit_status:1,status:1,commit_method:3)
        else
          exercise_user.update_attributes!(score:total_score,objective_score:calculate_score)
        end
        puts exercise_user.id
      end
    end
  end
end
