Novak Djokovic came back from the brink to deny Andy Murray a hat-trick of Shanghai Masters titles in a bad-tempered final.