class CompetitionAutoScoreNewJob < ApplicationJob
  queue_as :default

  def perform(competition_user_id, api_url, filePath, stage = 1)
    competition_user = CompetitionUser.find competition_user_id
    stage_score = competition_user.competition_user_scores.new(stage: stage.to_i)
    stage_score.api_status = 1
    stage_score.save
    # 开始打分
    domain = EduSetting.get("auto_score_api_url") || "http://114.116.228.69:8888"
    url = api_url || "/script/eye"
    params = { "filePath" => "#{filePath}", "userId" => competition_user.user_id }
    api_uri = URI.parse("#{domain}#{url}")
    http = Net::HTTP.new api_uri.host, api_uri.port
    http.open_timeout = 60
    http.read_timeout = 180
    if api_uri.scheme == 'https'
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    begin
      request = Net::HTTP::Post.new(api_uri.request_uri)
      request.set_form_data(params)
      request['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
      response = http.start { |http| http.request(request) }
      # puts "api response.body==#{response.body}"
      # Rails.logger.info "api response.body==#{response.body}"
      data = JSON.parse response.body
      status = data["status"].to_s == "0" ? 2 : 3
      if data["status"].to_s == "0"
        if url == "/script/qyCode"
          score = format("%.4f", data["pass@1"].to_f).to_f
        elsif url == "/script/qyMilitary"
          score = format("%.4f", data["accuracy"].to_f).to_f
        elsif url == "/script/cxds2025"
          score = format("%.4f", data["Weighted Score"].to_f).to_f
        else
          score = format("%.4f", (data["score"] || data["f1"]).to_f).to_f
          if data["data"].present?
            score = format("%.4f", data["data"]["f1"].to_f).to_f
          end
        end
        # 取最高分
        competition_user.score = score if score.to_f > competition_user.score.to_f
        # data["repeatTripleSet"] if data["repeatTripleSet"].present?
        stage_score.score = score
        stage_score.created_at = Time.now
        stage_score.last_score = 0.to_f
        stage_score.api_status = status
        stage_score.api_result = data.to_json
        stage_score.save
      else
        stage_score.created_at = Time.now
        stage_score.last_score = 0.to_f
        stage_score.api_status = status
        stage_score.api_result = data.to_json
        stage_score.save
      end
      competition_user.api_status = status
      competition_user.api_result = data.to_json
      competition_user.save
    end
  end
end
