class Subjects::UserUsedInfoService < ApplicationService
  require 'parallel'
  attr_reader :subject, :shixun_ids


  def initialize(subject)
    @subject = subject
    @shixun_ids = subject.shixuns.pluck(:id)

  end

  def call
    users_info = []
    users = User.includes(myshixuns: :games).where(myshixuns: {shixun_id: shixun_ids}, games: {status: 2}, users: {is_test: false})
    users.find_in_batches(batch_size: 500) do |u|
      u.each do |user|
        myshixuns = user.myshixuns.select{|m| shixun_ids.include?(m.shixun_id)}
        name =  "#{user.lastname}#{user.firstname}"
        passed_myshixun_count = myshixuns.select{|m| m.status == 1}.size
        passed_games_count = myshixuns.map{|m| m.games.select{|g| g.status == 2}.size }.size
        code_line_count = 0
        evaluate_count = myshixuns.map{|m| m.output_times }.sum
        cost_time = myshixuns.map{|m|m.total_cost_time }.sum
        users_info << {user_id: user.id, name: name, passed_myshixun_count: passed_myshixun_count,
                       passed_games_count: passed_games_count, code_line_count: code_line_count,
                       evaluate_count: evaluate_count, cost_time: cost_time}
      end
    end

    users_info
  end

end
