import { reactive } from "vue";
import type { FormRules } from "element-plus";

/** 密码正则（密码格式应为8-18位数字、字母、符号的任意两种组合） */
export const REGEXP_PWD =
  /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[()])+$)(?!^.*[\u4E00-\u9FA5].*$)([^(0-9a-zA-Z)]|[()]|[a-z]|[A-Z]|[0-9]){8,18}$/;

/** 登录校验 */
const loginRules = reactive<FormRules>({
  password: [getLoginPasswordRule()]
});

function getLoginPasswordRule() {
  return {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
        return;
      }
      if (!REGEXP_PWD.test(value)) {
        callback(new Error("密码格式应为8-18位数字、字母、符号的任意两种组合"));
        return;
      }
      callback();
    },
    trigger: "blur"
  };
}

function getRegisterPasswordRule() {
  return {
    validator: (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
        return;
      }
      callback();
    },
    trigger: "blur"
  };
}

function buildRegisterRules(getPassword: () => string) {
  return reactive<FormRules>({
    username: [
      { required: true, message: "请输入账号", trigger: "blur" },
      { max: 64, message: "账号长度不能超过64个字符", trigger: "blur" }
    ],
    nickname: [
      { max: 32, message: "昵称长度不能超过32个字符", trigger: "blur" }
    ],
    email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
    phoneNumber: [
      { max: 18, message: "手机号长度不能超过18个字符", trigger: "blur" }
    ],
    password: [getRegisterPasswordRule()],
    confirmPassword: [
      {
        validator: (rule, value, callback) => {
          if (value === "") {
            callback(new Error("请再次输入密码"));
            return;
          }
          if (value !== getPassword()) {
            callback(new Error("两次输入的密码不一致"));
            return;
          }
          callback();
        },
        trigger: "blur"
      }
    ]
  });
}

export { buildRegisterRules, loginRules };
