class Migrate3176ExerciseScore < ActiveRecord::Migration[5.2]

  def calculate_student_score(exercise,user)
    score5 = 0.0  #实训题
    exercise_end_time = exercise.end_time
    exercise_questions = exercise.exercise_questions.includes(:exercise_standard_answers,:exercise_shixun_challenges)
    exercise_questions.each do |q|
      if q.question_type == 5
        q.exercise_shixun_challenges.each do |exercise_cha|
          game = Game.user_games(user.id,exercise_cha.challenge_id)&.first  #当前用户的关卡
          if game.present?
            exercise_cha_score = 0.0
            answer_status = 0
            # if game.status == 2 && game.final_score >= 0
            if game.final_score > 0 && (game.end_time.nil? || game.end_time < exercise_end_time)
              exercise_cha_score = game.real_score(exercise_cha.question_score)
              # exercise_cha_score = exercise_cha.question_score #每一关卡的得分
              answer_status = 1
            end
            ex_shixun_answer_content = exercise_cha.exercise_shixun_answers.find_by(user_id:user.id,exercise_question_id:q.id)
            if ex_shixun_answer_content.present? && !(ex_shixun_answer_content.score >0)  #把关卡的答案存入试卷的实训里
              ex_shixun_answer_content.update_attributes!(score:exercise_cha_score.round(1),status:answer_status)
            end
            score5 += exercise_cha_score
          else
            score5 += 0.0
          end
        end
      end
    end
    score5
  end

  def change
    exercise = Exercise.find_by(id: 3176)
    if exercise
      exercise_users = exercise.exercise_users.where("start_at is not null")
      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.present?
          exercise_user.update_attributes!(score:total_score,objective_score:calculate_score)
        end
        puts exercise_user.id
      end
    end
  end
end
