A wounded Novak Djokovic was beaten in three sets by Grigor Dimitrov in the second round of the Madrid Open.