import type { Rule } from 'ant-design-vue/es/form'
import { isPhone, isPassword, isEmail } from './reg'
import type { Ref } from 'vue'
export const validatePassword = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('密码未输入')
  } else {
    if (!isPassword(value)) {
      return Promise.reject('密码格式不正确（6-20位字母、数字、符号组合）')
    }
    return Promise.resolve()
  }
}
export const genValidateRePassword = (prePwd: Ref<string>) => {
  return async (_rule: Rule, value: string) => {
    if (value === '') {
      return Promise.reject('密码未输入')
    }
    if (!isPassword(value)) {
      return Promise.reject('密码格式不正确（6-20位字母、数字、符号组合）')
    }
    if (prePwd.value !== value) {
      return Promise.reject('两次密码不一致')
    }
    return Promise.resolve()
  }
}

export const validatePhone = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('手机号未输入')
  } else {
    if (!isPhone(value)) {
      return Promise.reject('手机号格式不正确')
    }
    return Promise.resolve()
  }
}
export const validatePhoneOrEmail = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('手机号/邮箱未输入')
  } else {
    if (value.includes('@')) {
      if (!isEmail(value)) {
        return Promise.reject('邮箱格式不正确')
      }
    } else {
      if (!isPhone(value)) {
        return Promise.reject('手机号格式不正确')
      }
    }
    return Promise.resolve()
  }
}
export const validateEmail = async (_rule: Rule, value: string) => {
  if (value === '') {
    return Promise.reject('Email number is required')
  } else {
    if (!isEmail(value)) {
      return Promise.reject('Email format is incorrect')
    }
    return Promise.resolve()
  }
}
export const maskedPhoneOrEmail = (value: string) => {
  if (!value) return ''
  const _val = JSON.parse(JSON.stringify(value))
  if (_val.includes('@')) {
    if (isEmail(_val)) {
      return _val.slice(0, 1) + '****@' + _val.split('@')[1]
    }
  } else {
    if (isPhone(_val)) {
      return _val.slice(0, 3) + '****' + _val.slice(7)
    }
  }
}

export const genValidateTrue = (msg: string) => {
  return async (_rule: Rule, value: boolean) => {
    if (value !== true) {
      return Promise.reject(msg)
    }
    return Promise.resolve()
  }
}
