/*
 * @Author: codingfly
 * @Description:
 * @Date: 2021-10-12 13:19:43
 * @LastEditTime: 2021-11-25 11:56:50
 * @FilePath: \ui_model\src\form-rules\index.tsx
 */
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import IDCard from 'china-id-card';
import PasswordValidator from 'password-validator';

var baseSchema = function baseSchema(item) {
  return item
    .is()
    .min(8)
    .is()
    .max(20)
    .has()
    .not()
    .spaces();
};

var passwordSchemas = [
  baseSchema(new PasswordValidator())
    .has()
    .digits()
    .has()
    .symbols(),
  baseSchema(new PasswordValidator())
    .has()
    .symbols()
    .has()
    .letters(),
  baseSchema(new PasswordValidator())
    .has()
    .digits()
    .has()
    .letters(),
  baseSchema(new PasswordValidator())
    .has()
    .digits()
    .has()
    .letters()
    .has()
    .symbols(),
];
export default {
  idCard: function idCard(rule, value) {
    return value
      ? (value === null || value === void 0 ? void 0 : value.length) === 18 &&
        IDCard(value.toUpperCase()).isVerified
        ? Promise.resolve()
        : Promise.reject(new Error(rule.message || '请输入正确的身份证号码'))
      : rule.required
      ? Promise.reject(new Error('请输入身份证号码'))
      : Promise.resolve();
  },
  phone: function phone(rule, value) {
    return value
      ? /^1[3-9][0-9]{9}$/.test(value)
        ? Promise.resolve()
        : Promise.reject(new Error(rule.message || '请输入正确的手机号'))
      : rule.required
      ? Promise.reject(new Error('请输入手机号码'))
      : Promise.resolve();
  },
  password: function password(rule, value) {
    return value
      ? passwordSchemas.some(function(schema) {
          return schema.validate(value);
        })
        ? Promise.resolve()
        : Promise.reject(
            new Error(
              rule.message ||
                '请设置8-20位密码，至少包含数字、字母、特殊符号中2种，不能有空格',
            ),
          )
      : rule.required
      ? Promise.reject(new Error('请输入密码'))
      : Promise.resolve();
  },
  luhnCheck: function luhnCheck(rule, value) {
    return value
      ? (value === null || value === void 0 ? void 0 : value.length) === 20 &&
        function(value) {
          var arr = (value + '')
            .split('')
            .reverse()
            .map(function(x) {
              return parseInt(x);
            });
          var lastDigit = arr.splice(0, 1)[0];
          var sum = arr.reduce(function(acc, val, i) {
            return i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9;
          }, 0);
          sum += lastDigit;
          return sum % 10 === 0;
        }
        ? Promise.resolve()
        : Promise.reject(new Error('请输入银行卡号'))
      : rule.required
      ? Promise.reject(new Error('请输入银行卡号'))
      : Promise.resolve();
  },
};
