import {AbstractControl, ValidatorFn, Validators} from '@angular/forms';
import {NzSafeAny} from 'ng-zorro-antd';

export type validatorsErrorsOptions = { 'zh-cn': string; en: string } & Record<string, NzSafeAny>;
export type validatorsErrors = Record<string, validatorsErrorsOptions>;

export class ValidatorsService extends Validators {

  /**
   * 验证字符最小长度
   * @param minLength
   */
  static pwdLength(min: number, max: number): ValidatorFn {
    return (control: AbstractControl): validatorsErrors | null => {
      if (Validators.minLength(min)(control) === null && Validators.maxLength(max)(control) === null) {
        return null;
      }
      return { minlength: { 'zh-cn': `请输入${min}-${max}位密码`, en: ''} };
    };
  }

  /**
   * 验证字符最小长度
   * @param minLength
   */
  static minLength(minLength: number): ValidatorFn {
    return (control: AbstractControl): validatorsErrors | null => {
      if (Validators.minLength(minLength)(control) === null) {
        return null;
      }
      return { minlength: { 'zh-cn': `字符最小长度为 ${minLength}`, en: `MinLength is ${minLength}` } };
    };
  }

  /**
   * 验证字符最大长度
   * @param maxLength
   */
  static maxLength(maxLength: number): ValidatorFn {
    return (control: AbstractControl): validatorsErrors | null => {
      if (Validators.maxLength(maxLength)(control) === null) {
        return null;
      }
      return { maxlength: { 'zh-cn': `字符最大长度为 ${maxLength}`, en: `MaxLength is ${maxLength}` } };
    };
  }

  /**
   * 验证手机号
   * @param control
   */
  static mobile(control: AbstractControl): validatorsErrors | null {
    const value = control.value;

    if (isEmptyInputValue(value)) {
      return null;
    }

    return isMobile(value) ? null : { mobile: { 'zh-cn': `手机号码格式不正确`, en: `Mobile phone number is not valid` } };
  }

  static isMobile(value: string): boolean {
    return typeof value === 'string' && /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/.test(value);
  }

}


function isEmptyInputValue(value: NzSafeAny): boolean {
  return value == null || value.length === 0;
}

function isMobile(value: string): boolean {
  return typeof value === 'string' && /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/.test(value);
}
