import {validEmail, validMasterCardNo, validVisaCardNo} from "~/utils/validate";

export default {
  country: (rule: any, value: any, callback: any) => {
    if(!value) return callback(new Error("must not be empty"));
    if (value === '**') return callback();
    if(value.length !== 2) return callback(new Error("Country code length must be 2 and All uppercase"))
    if(!/^[A-Z][A-Z]$/.test(value)) return callback(new Error("Country code length must be 2 and All uppercase"))
    else callback()
  },

  state: (rule: any, value: any, callback: any) => {
    if(!value) return callback(new Error("must not be empty"));
    if (value === '**') return callback();
    if(value.length !== 2) return callback(new Error("State length must be 2 and All uppercase"))
    if(!/^[A-Z][A-Z]$/.test(value)) return callback(new Error("State length must be 2 and All uppercase"))
    else callback()
  },

  zip: (rule: any, value: any, callback: any) => {
    if (!value) return callback(new Error("must not be empty"));
    if (value.length < 5 || value.length > 10)
      return callback(new Error("Zip length must between 5 and 10"))
    if (!/^[\d-]+$/.test(value))
      return callback(new Error("Invalid zip"))
    callback()
  },

  address: (rule: any, value: any, callback: any) => {
    if (!value) return callback(new Error("must not be empty"));
    if (value.length > 45)
      return callback(new Error("Address length must not greater than 45 characters"))
    return callback()
  },

  mobile: (rule: any, value: any, callback: any) => {
    if (!value) return callback();
    if (!/^[\d]{10,12}/.test(value))
      return callback(new Error("Invalid mobile"))
    return callback()
  },

  email: (rule: any, value: any, callback: any) => {
    if (!value) return callback();
    if (!validEmail(value))
      return callback(new Error("Invalid email"))
    return callback()
  },

  // 信用卡校验，仅校验Visa和MasterCard
  // https://www.w3resource.com/javascript/form/credit-card-validation.php
  creditCardNo: (rule: any, value: any, callback: any) => {
    if (!value) return callback();
    if (!validVisaCardNo(value) && !validMasterCardNo(value))
      return callback(new Error("Invalid Visa/Master Credit Card No."))
    return callback()
  },

  // 信用卡有效日期校验，格式为YYYYMM
  creditCardValidDate: (rule: any, value: any, callback: any) => {
    if (!value) return callback();
    if (!/^20[2-4][0-9](0[1-9]|1[012])$/.test(value))
      return callback(new Error("Invalid Card Valid Date"))
    return callback()
  },

  // 行用卡cvv校验，格式为3为数字
  creditCardCVV: (rule: any, value: any, callback: any) => {
    if (!value) return callback();
    if (!/^\d{3}$/.test(value))
      return callback(new Error("Invalid CVV"))
    return callback()
  },

}
