import { useI18n } from '@/hooks/web/useI18n'
import { FormItemRule } from 'element-plus'

const { t } = useI18n()

interface LengthRange {
  min: number
  max: number
  message?: string
}

export const useValidator = () => {
  /** 必选 */
  const required = (message?: string): FormItemRule => {
    return {
      required: true,
      message: message || t('common.required')
    }
  }

  /** 长度 */
  const lengthRange = (options: LengthRange): FormItemRule => {
    const { min, max, message } = options

    return {
      min,
      max,
      message: message || t('common.lengthRange', { min, max })
    }
  }

  /** 不能包含空格 */
  const notSpace = (message?: string): FormItemRule => {
    return {
      validator: (_, val, callback) => {
        if (val?.indexOf(' ') !== -1) {
          callback(new Error(message || t('common.notSpace')))
        } else {
          callback()
        }
      }
    }
  }

  /** 不能包含特殊字符 */
  const notSpecialCharacters = (message?: string): FormItemRule => {
    return {
      validator: (_, val, callback) => {
        if (/[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/gi.test(val)) {
          callback(new Error(message || t('common.notSpecialCharacters')))
        } else {
          callback()
        }
      }
    }
  }

  /** 手机号码正则 */
  const MOBILE_PATTERN =
    /^1((3\d)|(4[578])|(5[0-3,5-9])|(6[67])|(7[1-3,5-8])|(8\d)|(9[013,5-9])|(44))\d{8}$/
  /** 手机号验证 */
  const phone = (message?: string): FormItemRule => {
    return {
      pattern: MOBILE_PATTERN,
      message: message || t('common.phoneValidator')
    }
  }

  /** 邮箱 */
  const email = (message?: string): FormItemRule => {
    return {
      type: 'email',
      message: message || t('common.emailValidator')
    }
  }

  return {
    required,
    lengthRange,
    notSpace,
    notSpecialCharacters,
    phone,
    email
  }
}
