/**
 * 验证邮箱格式
 */
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * 验证密码强度
 * @returns 返回 0-4 表示强度等级
 */
export function getPasswordStrength(password: string): number {
  let strength = 0;
  if (password.length >= 6) strength++;
  if (password.length >= 8) strength++;
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
  if (/\d/.test(password)) strength++;
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;
  return Math.min(strength, 4);
}

/**
 * 验证手机号
 */
export function isValidPhone(phone: string): boolean {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
}

/**
 * 验证密码格式 (6-20位)
 */
export function isValidPassword(password: string): boolean {
  return password.length >= 6 && password.length <= 20;
}

/**
 * 验证用户名 (2-20位字母数字下划线)
 */
export function isValidUsername(username: string): boolean {
  const usernameRegex = /^[a-zA-Z0-9_]{2,20}$/;
  return usernameRegex.test(username);
}

/**
 * 验证数字范围
 */
export function isInRange(value: number, min: number, max: number): boolean {
  return value >= min && value <= max;
}

/**
 * 验证非空
 */
export function isNotEmpty(value: string | null | undefined): boolean {
  return value !== null && value !== undefined && value.trim() !== '';
}

/**
 * 表单验证规则
 */
export const validationRules = {
  required: (message = '此字段为必填项') => ({
    validate: (value: string) => isNotEmpty(value),
    message,
  }),

  email: (message = '请输入有效的邮箱地址') => ({
    validate: isValidEmail,
    message,
  }),

  password: (message = '密码长度应为6-20位') => ({
    validate: isValidPassword,
    message,
  }),

  phone: (message = '请输入有效的手机号') => ({
    validate: isValidPhone,
    message,
  }),

  minLength: (min: number, message?: string) => ({
    validate: (value: string) => value.length >= min,
    message: message || `最少输入${min}个字符`,
  }),

  maxLength: (max: number, message?: string) => ({
    validate: (value: string) => value.length <= max,
    message: message || `最多输入${max}个字符`,
  }),

  range: (min: number, max: number, message?: string) => ({
    validate: (value: number) => isInRange(value, min, max),
    message: message || `请输入${min}-${max}之间的数字`,
  }),
};

/**
 * 验证单个字段
 */
export function validateField(
  value: unknown,
  rules: Array<{ validate: (v: unknown) => boolean; message: string }>
): string | null {
  for (const rule of rules) {
    if (!rule.validate(value)) {
      return rule.message;
    }
  }
  return null;
}
