import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { checkLoginNameApi } from "@/api/user";

const checkLoginName = async (value: string) => {
  try {
    const res = await checkLoginNameApi(value);
    if (res.code === 0) {
      return res.data;
    }
  } catch (error) {
    console.log("验证账号失败", error);
  }
};

/** 密码正则（密码格式应为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 checkLoginNameV = (rule, value, callback) => {
  if (!value) {
    callback(new Error("账号不能为空"));
  } else {
    checkLoginName(value).then(val => {
      console.log(val);
      if (!val) {
        callback(new Error("无此用户"));
      } else {
        callback();
      }
    });
  }
};

/** 登录校验 */
const loginRules = reactive<FormRules>({
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (!REGEXP_PWD.test(value)) {
          callback(
            new Error("密码格式应为8-18位数字、字母、符号的任意两种组合")
          );
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  verification: [{ required: true, message: "验证码不能为空" }]
});

const smsRules = reactive<FormRules>({
  verifySmsCode: [{ required: true, message: "验证码不能为空" }]
});

export { loginRules, smsRules };
