package org.sky.scientific.utils;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.sky.core.log.exception.ServiceException;
import org.sky.core.tool.utils.StringUtil;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

public class ValidationUtils {

	private static final Validator validator;
	static {
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		validator = factory.getValidator();
	}

	/**
	 * 验证实体对象
	 */
	public static <T> List<String> validate(T object) {
		Set<ConstraintViolation<T>> violations = validator.validate(object);
		List<String> errorMessages = new ArrayList<>();
		for (ConstraintViolation<T> violation : violations) {
			errorMessages.add(violation.getMessage());
		}
		return errorMessages;
	}

	/**
	 * 安全的日期转换
	 */
	public static Date safeParseDate(String dateStr, String pattern) {
		if (StringUtil.isBlank(dateStr)) {
			return null;
		}
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			sdf.setLenient(false);
			return sdf.parse(dateStr.trim());
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 安全的数字转换
	 */
	public static Integer safeParseInteger(String numberStr) {
		if (StringUtil.isBlank(numberStr)) {
			return null;
		}
		try {
			return Integer.parseInt(numberStr.trim());
		} catch (NumberFormatException e) {
			return null;
		}
	}


	public static Double safeParseDouble(String numberStr) {
		if (StringUtil.isBlank(numberStr)) {
			return null;
		}
		try {
			return Double.parseDouble(numberStr.trim());
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static Double safeParseDoubleWithPercentage(String numberStr ,String key) {
		if (StringUtil.isBlank(numberStr)) {
			return null;
		}
		try {
			String numberPart = numberStr.trim().split("%")[0];
			return Double.parseDouble(numberPart) / 100;
		}catch (Exception e) {
			throw new ServiceException(key + "不是一个有效的百分比");
		}
	}

	public static BigDecimal safeParseBigDecimal(String numberStr) {
		if (StringUtil.isBlank(numberStr)) {
			return null;
		}
		try {
			return new BigDecimal(numberStr.trim());
		} catch (NumberFormatException e) {
			return null;
		}
	}

	/**
	 * 验证日期格式
	 */
	public static boolean isValidDateFormat(String dateStr, String pattern) {
		if (StringUtil.isBlank(dateStr)) {
			return false;
		}
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			sdf.setLenient(false);
			sdf.parse(dateStr.trim());
			return true;
		} catch (ParseException e) {
			return false;
		}
	}
}
