Walmart Inc. agreed to pay $3.1 billion to resolve thousands of lawsuits by cities, counties, Native American tribes and states alleging its pharmacists failed to regulate opioid prescriptions, leading to a public health crisis in their communities.