class CompetitionAutoScoreNewJob < ApplicationJob
  queue_as :default

  def perform(competition_user_id, api_url, filePath)
    competition_user = CompetitionUser.find competition_user_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"].to_f).to_f
        competition_user.score = score
        # data["repeatTripleSet"] if data["repeatTripleSet"].present?
      end
      competition_user.api_status = status
      competition_user.api_result = data.to_json
      competition_user.save
    end
  end
end
