import { validateLowerCase, validateEmail, validateNumberAndLowerCase } from '@/utils/validate'

function usernameValidator(value: string | undefined, callback: (errMsg?: string) => void) {
  if (value === '' || !value) {
    callback('用户名不能为空')
  } else if (value.length < 3 || value.length > 20) {
    callback('用户名长度为3-20个字符')
  } else if (!validateLowerCase(value.substring(0, 1))) {
    callback('用户名只能由小写字母开头')
  } else if (!validateNumberAndLowerCase(value)) {
    callback('用户名只能由小写字母和数字组成')
  } else {
    callback()
  }
}

function phoneValidator(value: string | undefined, callback: (errMsg?: string) => void) {
  if (value === '' || !value) {
    callback('手机号不能为空')
  } else if (value.length !== 11) {
    callback('手机号长度为11个字符')
  } else if (!/^1[0-9]{10}$/.test(value)) {
    callback('手机号格式错误')
  } else {
    callback()
  }
}

export const passwordRule = [
  { required: true, message: '密码不能为空' },
  { minLength: 8, message: '密码长度不小于8个字符' }
]

export const usernameRule = [
  { required: true, message: '用户名不能为空' },
  { validator: usernameValidator }
]

export const phoneRule = [
  { required: true, message: '手机号不能为空' },
  { validator: phoneValidator }
]

function emailValidator(value: string | undefined, callback: (errMsg?: string) => void) {
  if (value === '' || !value) {
    callback('邮箱不能为空')
  } else if (!validateEmail(value)) {
    callback('邮箱格式错误')
  } else {
    callback()
  }
}
export const emailRule = [
  { required: true, message: '邮箱不能为空' },
  { validator: emailValidator }
]
