class MigrateExerciseAnswerScore < ActiveRecord::Migration[5.2]
  def challenge_path(path)
    cha_path = path.present? ? path.split("；") : []
    cha_path.reject(&:blank?)[0].try(:strip)
  end

  # 版本库文件内容，带转码
  def git_fle_content(repo_path, path)
    begin
      Rails.logger.info("git file content: repo_path is #{repo_path}, path is #{path}")

      content = GitService.file_content(repo_path: repo_path, path: path)

      Rails.logger.info("git file content: content is #{content}")
      decode_content = nil
      if content.present?
        content = content["content"]   #6.24 -hs 这个为新增，因为当实训题里含有选择题时，这里会报错,undefined method `[]' for nil:NilClass

        content = Base64.decode64(content)
        cd = CharDet.detect(content)
        Rails.logger.info "encoding: #{cd['encoding']} confidence: #{cd['confidence']}"
        # 字符编码问题，GB18030编码识别率不行
        decode_content =
          if cd["encoding"] == 'GB18030' && cd['confidence'] > 0.8
            content.encode('UTF-8', 'GBK', {:invalid => :replace, :undef => :replace, :replace => ' '})
          else
            content.force_encoding('UTF-8')
          end
      end

      decode_content

    rescue Exception => e
      Rails.logger.error(e.message)
      raise Educoder::TipException.new("文档内容获取异常")
    end
  end

  def calculate_student_score(exercise,user)
    score5 = 0.0  #实训题
    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 < 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.where(user_id:user.id,exercise_question_id:q.id)
            code = nil
            if exercise_cha.challenge&.path.present?
              cha_path = challenge_path(exercise_cha.challenge&.path)
              game_challenge = game.game_codes.search_challenge_path(cha_path)&.first
              if game_challenge.present?
                game_code = game_challenge
                code = game_code.try(:new_code)
              else
                begin
                  code = git_fle_content(game.myshixun.repo_path,cha_path)
                rescue
                  code = ""
                end
              end
            end
            if ex_shixun_answer_content.blank?  #把关卡的答案存入试卷的实训里
              ### Todo 实训题的_shixun_details里的代码是不是直接从这里取出就可以了？涉及到code的多个版本库的修改
              sx_option = {
                :exercise_question_id => q.id,
                :exercise_shixun_challenge_id => exercise_cha.id,
                :user_id => user.id,
                :score => exercise_cha_score.round(1),
                :answer_text => code,
                :status => answer_status
              }
              ExerciseShixunAnswer.create!(sx_option)
            else
              ex_shixun_answer_content.first.update_attributes!(score:exercise_cha_score.round(1),answer_text:code,status:answer_status)
            end
            score5 += exercise_cha_score
          else
            score5 += 0.0
          end
        end
      end
    end
    score5
  end

  def change
    user_ids = [111887, 111892, 111883, 111880]
    exercise = Exercise.find_by(id: 2734)
    if exercise
      exercise_users = exercise.exercise_users.where(user_id: user_ids)
      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
        exercise_user.update_attributes!(score:total_score,objective_score:calculate_score)
        puts exercise_user.id
      end
    end
  end
end
