class ExercisePublishTask
  include ExercisesHelper
  include GitHelper

  def publish
    Rails.logger.info("log--------------------------------exercise_publish start")
    puts "--------------------------------exercise_publish start"
    exercises = Exercise.includes(:exercise_users).where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
    exercises&.each do |exercise|
      begin
        ActiveRecord::Base.transaction do
          exercise.update_column('exercise_status', 2)

          if exercise.unified_setting
            ExercisePublishNotifyJob.perform_later(exercise.id, nil)
          else
            course = exercise.course
            teachers = course.teachers.where.not(id: course.teacher_course_groups.select(:course_member_id))
            tid_str = ""
            teachers.find_each do |member|
              tid_str += "," if tid_str != ""
              tid_str += "(#{member.user_id}, #{exercise.user_id}, #{exercise.id}, 'Exercise', #{exercise.id}, 'ExercisePublish', #{course.id}, 'Course', 0, 'Exercise', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
            end
            if tid_str != ""
              tid_sql = "insert into tidings (user_id, trigger_user_id, container_id, container_type, parent_container_id, parent_container_type, belong_container_id, belong_container_type, viewed, tiding_type, created_at, updated_at) values" + tid_str
              ActiveRecord::Base.connection.execute tid_sql
            end
          end

          exercise.course_acts << CourseActivity.new(user_id: exercise.user_id, course_id: exercise.course_id) if !exercise.course_acts.exists?

          # 如果是随机组卷的话，则需要增加一步: 根据随机规则为学生分配试题
          if exercise.is_random?
            exercise.create_exercise_questions_by_random_settings
          end
        end
      rescue Educoder::TipException => e
        Rails.logger.info("#{e.message}, #{$@},#{exercise.id}")
        puts("#{e.message}, #{$@},#{exercise.id}")
        exercise.update_columns(exercise_status: 1, publish_time: nil)
      end
    end
    
    # 分组设置发布时间的测验
    exercise_group_settings = ExerciseGroupSetting.where("publish_time < ? and publish_time > ?", Time.now + 900, Time.now - 900)
    exercise_group_settings&.each do |exercise_group|

      exercise = exercise_group.exercise
      if exercise.present?
        exercise.update_attributes(:exercise_status => 2) if exercise.exercise_status == 1
        ExercisePublishNotifyJob.perform_later(exercise.id, [exercise_group.course_group_id])
      end
    end

    exercise_group_settings.map(&:exercise).each do |exercise|
      begin
        ActiveRecord::Base.transaction do
          # 如果是随机组卷的话，则需要增加一步: 根据随机规则为学生分配试题
          if exercise.is_random? && exercise.exercise_status != Exercise::PUBLISHED
            exercise.create_exercise_questions_by_random_settings
          end
        end
      rescue Educoder::TipException => e
        Rails.logger.info("该随机试卷题库数量不足,无法发布!exercise_id: #{exercise.id}")
        puts "该随机试卷题库数量不足,无法发布!exercise_id: #{exercise.id}"
        exercise.update_attributes(exercise_status: 1, publish_time: nil)
      end
    end
    Rails.logger.info("log--------------------------------exercise_publish end")
    puts "--------------------------------exercise_publish end"
  end


  def end
    Rails.logger.info("log--------------------------------exercise_end start")
    puts "--------------------------------exercise_end start"
    # 1。统一设置的试卷
    exercises = Exercise.includes(:exercise_questions).where("exercise_status = 2 AND end_time <= ?",Time.now + 900)
    exercises.each do |exercise|
      Rails.logger.info("end_exercise_id: #{exercise.id}")
      exercise.update_attributes!(exercise_status: 3)
      if exercise.unified_setting
        ex_type = exercise.exercise_questions.pluck(:question_type).uniq
        # 更新该试卷下所有未提交的用户试卷
        # 只要用户是未提交状态都会自动交卷(以前是要求必须开始答题)
        exercise.exercise_users.where("commit_status = 0").each do |exercise_user|
          begin
            Rails.logger.info("true: user_id:#{exercise_user.user_id}--commit_status:#{exercise_user.commit_status}")
            calculate_result = calculate_student_score(exercise, exercise_user, exercise.end_time)
            s_score = calculate_result[:total_score]
            reviewed = calculate_result[:reviewed]
            subjective_reviewed = calculate_result[:subjective_reviewed]

            if ex_type.include?(4)   #是否包含主观题
              subjective_score = exercise_user.subjective_score
            else
              subjective_score = -1.0
            end
            total_score_subjective_score = subjective_score < 0.0 ? 0.0 : subjective_score
            total_score = s_score + total_score_subjective_score
            Rails.logger.info("true: user_id:#{exercise_user.user_id}--subjective_score:#{subjective_score}")
            Rails.logger.info("true: user_id:#{exercise_user.user_id}--s_score:#{s_score}")
            Rails.logger.info("true: user_id:#{exercise_user.user_id}--commit_method:#{exercise_user.commit_method}")
            # 需要判断用户是否进行了答题，如果没有答题，将状态置为已交卷未答题
            if exercise.exercise_answers.where(user_id: exercise_user.user_id).blank? && exercise.exercise_shixun_answers.where(user_id: exercise_user.user_id).blank?
              commit_status = "commit_with_no_answer"
            else
              commit_status = "commited"
            end
            commit_option = {
              :status => 1,
              :commit_status => commit_status,
              :end_at => exercise.end_time,
              :objective_score => s_score,
              :score => total_score,
              :subjective_score => subjective_score,
              :commit_method => exercise_user&.commit_method.to_i > 0 ? exercise_user&.commit_method.to_i : 3,
              :reviewed => reviewed,
              :subjective_reviewed => subjective_reviewed
            }
            exercise_user.update_attributes(commit_option)
          rescue Exception => e
            Rails.logger.info("rescue errors ___________________________#{e}")
            next
          end
        end
      end
    end

    ExerciseGroupSetting.where("end_time < ? and end_time > ?", Time.now + 900, Time.now - 900).each do |exercise_setting|
      exercise = exercise_setting.exercise
      Rails.logger.info("exercise_group_setting: exercise_id:#{exercise.id}--group_settings_id:#{exercise_setting.id}")

      users = exercise.course.course_members.where(:course_group_id => exercise_setting.course_group_id)
      exercise_users = exercise.exercise_users.where(user_id: users.pluck(:user_id)).where("commit_status = 0 and start_at is not null")
      ex_types = exercise.exercise_questions.pluck(:question_type).uniq
      exercise_users.each do |exercise_user|
        Rails.logger.info("false: user_id:#{exercise_user.user_id}--commit_status:#{exercise_user.commit_status}")
        begin
          if ex_types.include?(4)   #是否包含主观题
            subjective_score = exercise_user.subjective_score
          else
            subjective_score = -1.0
          end

          calculate_result = calculate_student_score(exercise, exercise_user, exercise_setting.end_time)
          s_score = calculate_result[:total_score]
          reviewed = calculate_result[:reviewed]
          subjective_reviewed = calculate_result[:subjective_reviewed]

          total_score_subjective_score = subjective_score < 0.0 ? 0.0 : subjective_score
          total_score = s_score + total_score_subjective_score
          Rails.logger.info("false: user_id:#{exercise_user.user_id}--s_score:#{s_score}")
          Rails.logger.info("false: user_id:#{exercise_user.user_id}--subjective_score:#{subjective_score}")
          Rails.logger.info("false: user_id:#{exercise_user.user_id}--commit_method:#{exercise_user.commit_method}")
          # 需要判断用户是否进行了答题，如果没有答题，将状态置为已交卷未答题
          if exercise.exercise_answers.where(user_id: exercise_user.user_id).blank? && exercise.exercise_shixun_answers.where(user_id: exercise_user.user_id).blank?
            commit_status = "commit_with_no_answer"
          else
            commit_status = "commited"
          end
          commit_option = {
            :status => 1,
            :commit_status => commit_status,
            :end_at => exercise_setting.end_time,
            :objective_score => s_score,
            :score => total_score,
            :subjective_score => subjective_score,
            :commit_method => exercise_user&.commit_method.to_i > 0 ? exercise_user&.commit_method.to_i : 3,
            :reviewed => reviewed,
            :subjective_reviewed => subjective_reviewed
          }
          exercise_user.update_attributes(commit_option)
        rescue Exception => e
          Rails.logger.info("unified_setting_false_rescue errors ___________________________#{e}")
          next
        end
      end
    end
    Rails.logger.info("log--------------------------------exercise_end end")
    puts "--------------------------------exercise_end end"
  end
end