/*
 * @Author: Maple
 * @Date: 2021-03-22 11:42:26
 * @LastEditors: Do not edit
 * @LastEditTime: 2021-03-29 14:47:54
 * @Description: 全局验证服务
 */
import { Injectable, Injector } from '@angular/core';
import { BaseService } from '../core/base.service';

@Injectable({
  providedIn: 'root',
})
export class EAValidateService extends BaseService {
  constructor(public injector: Injector) {
    super(injector);
  }

  /**
   * 通过正则表达式验证字符串
   * @param value 待验证的字符串
   * @param partern 正则表达式
   * @returns 验证结果
   */
  validate(value: string, partern: RegExp): boolean {
    const reg = new RegExp(partern);
    return reg.test(value);
  }

  /**
   * 验证手机号码
   * @param value 待验证的值
   * @returns 验证结果
   */
  validateChineseCharacters(value: string, star: number): boolean {
    const express = /^[\u4e00-\u9fa5]{2, 4}$/;
    return this.validate(value, express);
  }

  /**
   * 验证手机号码
   * @param value 待验证的值
   * @returns 验证结果
   */
  validateMobile(value: string): boolean {
    const express = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    return this.validate(value, express);
  }

  /**
   * 验证固定电话
   * @param value 待验证的值
   * @returns 验证结果
   */
  validateTel(value: string): boolean {
    const express = /^(0\d{2,3})-?(\d{7,8})$/;
    return this.validate(value, express);
  }

  /**
   * 验证身份证号码
   * @param value 待验证的值
   * @param mode 匹配模式：indistinct - 模糊匹配 | accurate - 精准匹配（默认值：indistinct）
   * @param length 号码长度 (默认值：18)
   * @returns 验证结果
   */
  validateIDCard(value: string, mode: 'indistinct' | 'accurate' = 'indistinct', length: 15 | 18 = 18): boolean {
    // 模糊校验
    let express = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    // 精准校验18位身份证号码
    const express1 = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    // 精准校验15位身份证号码
    const express2 = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/;

    if (mode === 'accurate') {
      if (length === 18) {
        express = express1;
      } else if (length === 15) {
        express = express2;
      }
    }
    return this.validate(value, express);
  }

  /**
   * 验证邮政编码
   * @param value 待验证的值
   * @returns 验证结果
   */
  validatePostalCode(value: string): boolean {
    const express = /^[1-9]\d{5}$/;
    return this.validate(value, express);
  }

  /**
   * 验证邮箱地址
   * @param value 待验证的值
   * @returns 验证结果
   */
  validateEmail(value: string): boolean {
    const express = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return this.validate(value, express);
  }
}
