McLaren's Oscar Piastri won the Azerbaijan Grand Prix in a race that ended behind a virtual safety car after a collision between Ferrari's Carlos Sainz and Red Bull's Sergio Perez as they fought for third place.