class AddScoreToWork < ActiveRecord::Migration
  require 'bigdecimal'

  def up
    count = StudentWork.all.count / 10 + 1
    transaction do
      for i in 1 ... count do i
        StudentWork.page(i).per(10).each do |work|
          teacher_score = work.student_works_scores.where(:reviewer_role => 1).order("created_at desc")
          unless teacher_score.empty?
            work.teacher_score = teacher_score.first.score
          end

          teaching_asistant_score = work.student_works_scores.where(:reviewer_role => 2)
          unless teaching_asistant_score.empty?
            work.teaching_asistant_score = teaching_asistant_score.average(:score).try(:round, 2).to_f
          end

          student_socre = work.student_works_scores.where(:reviewer_role => 3)
          unless student_socre.empty?
            work.student_score = student_socre.average(:score).try(:round, 2).to_f
          end

          if work.teacher_score.nil?
            if work.teaching_asistant_score.nil? #教辅评分为空，最终评分为学生匿评
              work.final_score = work.student_score
            elsif work.student_score.nil? #学生匿评评分为空，最终评分为教辅评分
              work.final_score = work.teaching_asistant_score
            else #都不为空，按比例来
              final_ta_score = BigDecimal.new("#{work.teaching_asistant_score}") * BigDecimal.new("0.6")
              final_s_score = BigDecimal.new("#{work.student_score}") * BigDecimal.new('0.4')
              final_score = final_ta_score + final_s_score
              work.final_score = format("%.2f",final_score.to_f)
            end
          else #教师评分不为空，最终评分为教师评分
            work.final_score = work.teacher_score
          end
          work.save
        end
      end
    end


  end

  def down
    count = StudentWork.all.count / 10 + 1
    transaction do
      for i in 1 ... count do i
        StudentWork.page(i).per(10).each do |work|
          work.teacher_score = nil
          work.teaching_asistant_score = nil
          work.student_score = nil
          work.final_score = nil
          work.save
        end
      end
    end
  end
end
