This phrase is used to offer comfort (or advice) in the face of a bad or difficult situation: even tragedies or problems can bring benefits or positive results in the long or short term.
Its origin is unknown as it was mainly passed down orally, but it can already be found in writings dating back to the 1600s.