import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  ValidationArguments,
  registerDecorator,
  ValidationOptions,
} from 'class-validator';

@ValidatorConstraint({ name: 'isChinesePhone', async: false })
export class IsChinesePhoneConstraint implements ValidatorConstraintInterface {
  validate(phone: string, args: ValidationArguments): boolean {
    return /^1[3-9]\d{9}$/.test(phone);
  }

  defaultMessage(args: ValidationArguments): string {
    return '手机号格式错误';
  }
}

export function IsChinesePhone(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsChinesePhoneConstraint,
    });
  };
}

@ValidatorConstraint({ name: 'isChineseIdCard', async: false })
export class IsChineseIdCardConstraint implements ValidatorConstraintInterface {
  validate(idCard: string, args: ValidationArguments): boolean {
    return /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/.test(
      idCard,
    );
  }

  defaultMessage(args: ValidationArguments): string {
    return '身份证号格式错误';
  }
}

export function IsChineseIdCard(validationOptions?: ValidationOptions) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsChineseIdCardConstraint,
    });
  };
}
