class Admins::ImportCompetitionScoreService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :file, :competition, :result

  def initialize(file, competition)
    @file   = file
    @competition = competition
    @result = { success: 0, fail: [] }
  end

  def call
    raise Error, '文件不存在' if file.blank?

    # 创建所有战队的得分记录
    create_all_records

    excel = Admins::ImportCompetitionScoreExcel.new(file)
    excel.read_each(&method(:update_competition_score)) # 更新单个战队成绩

    result
  rescue ApplicationImport::Error => ex
    raise Error, ex.message
  end

  private

  def update_competition_score(data)
    team = competition.competition_scores.find_by(competition_team_id: data.competition_team_id)
    raise "id为#{data.id}的战队不存在" if team.blank?
    team.update!(score: data.score)

    result[:success] += 1
  rescue Exception => ex
    fail_data = data.as_json
    fail_data[:data] = fail_data.values.join(',')
    fail_data[:message] = ex.message

    result[:fail] << fail_data
  end

  def create_all_records
    competition.competition_scores.destroy_all

    stage = competition.competition_stages.first

    attrs = %i[
      competition_id competition_stage_id score cost_time user_id competition_team_id created_at updated_at
    ]

    CompetitionScore.bulk_insert(*attrs) do |worker|
      base_attr = { competition_id: competition.id, competition_stage_id: stage&.id.to_i,
                    score: 0, cost_time: 0 }
      competition.competition_teams.each do |team|
        worker.add(base_attr.merge(user_id: team.user_id).merge(competition_team_id: team.id))
      end
    end
  end
end