class CompetitionAutoScoreJob < ApplicationJob
  queue_as :default

  def perform(team_id, api_url, filePath)
    competition_team = CompetitionTeam.find team_id
    domain = EduSetting.get("auto_score_api_url") || "http://114.116.228.69:8888"
    url = api_url || "/script/eye"
    params = {"filePath" => "#{filePath}"}
    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"
        score = format("%.4f", (data["score"] || data["f1"]).to_f).to_f
        competition_score = competition_team.competition_scores.present? ? competition_team.competition_scores.first : competition_team.competition_scores.new
        competition_score.score = score
        competition_score.region = data["repeatTripleSet"] if data["repeatTripleSet"].present?
        competition_score.competition_id = competition_team.competition_id
        competition_score.user_id = competition_team.user_id
        competition_score.save
      end
      competition_team.update_attributes!(api_status: status, api_result: data.to_json)
    end
  end
end
