class MigrateStudentWorkCompeleteStatus < ActiveRecord::Migration[5.2]
  def change
    student_works = StudentWork.where("myshixun_id is not null and myshixun_id != 0")
    student_works.includes(homework_common: :homework_challenge_settings, myshixun: :games).find_each do |work|
      if work.myshixun && work.homework_common
        myshixun = work.myshixun
        homework= work.homework_common
        setting_time = homework.homework_group_setting(myshixun.user_id)
        homework_end_or_late_time = homework.allow_late ? homework.late_time : setting_time.end_time
        challenge_ids = homework.homework_challenge_settings.pluck(:challenge_id)
        games = myshixun.games.select{ |game| challenge_ids.include?(game.challenge_id) }
        myshixun_endtime = games.select{|game| game.status == 2}.size == games.size ? games.map(&:end_time).max : nil
        if work.work_status != 0 && homework_end_or_late_time.present?
          if myshixun_endtime.present? && myshixun_endtime <= homework_end_or_late_time
            # 2是按时通关， 3是迟交通关
            compelete_status = setting_time.end_time.present? && myshixun_endtime < setting_time.end_time ? 2 : 3
          else
            compelete_status = 1 # 未通关
          end
          work.update_column("compelete_status", compelete_status)
        end
      end
    end
  end
end
