<template>
  <div class="collect-form">
    <div class="tip">
      密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型，长度不少于
      6-20位数字
    </div>
    <ElForm :rules="rules" :model="formModel" ref="formRef">
      <CustomizeFormItem prop="pwd1">
        <syDialogInput
          type="password"
          style="width: 100%"
          :maxLength="20"
          v-model:value="formModel.pwd1"
          placeholder="请输入密码"
        ></syDialogInput>
      </CustomizeFormItem>
      <CustomizeFormItem prop="pwd2">
        <syDialogInput
          type="password"
          style="width: 100%"
          :maxLength="20"
          v-model:value="formModel.pwd2"
          placeholder="再次输入密码"
        ></syDialogInput>
      </CustomizeFormItem>
    </ElForm>
  </div>
</template>

<script setup lang="ts">
import { syDialogInput } from "cqk-sy-ui";
import { reactive, ref, watch } from "vue";
import { ElForm } from "element-plus";
import CustomizeFormItem from "../CustomizeFormItem.vue";

const formRef = ref<InstanceType<typeof ElForm>>();

const formModel = reactive({
  pwd1: "",
  pwd2: "",
});

const emit = defineEmits(["collect"]);

function testPwd(str: string) {
  /**密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型*/
  const pattern =
    /^[0-9a-z\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\{\}\[\]\;\'\"\:\,\.\/\<\>\?\=\|]*$/gi;

  const p1 = /[0-9]+/gi;
  const p2 = /[a-z]+/gi;
  const p3 =
    /[\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\{\}\[\]\;\'\"\:\,\.\/\<\>\?\=\|]+/gi;

  return (
    pattern.test(str) &&
    [p1.test(str), p2.test(str), p3.test(str)].filter((i) => i).length >= 2 &&
    str.length >= 6 &&
    str.length <= 20
  );
}
watch(
  () => [formModel.pwd1, formModel.pwd2],
  () => {
    emit("collect", {
      value: formModel.pwd2,
      isValid: formModel.pwd1 === formModel.pwd2 && testPwd(formModel.pwd1),
    });
  }
);

const rules = {
  pwd1: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
    {
      min: 6,
      max: 20,
      message: "密码长度不少于6-20位数字",
      trigger: "change",
    },
    {
      validator: (rule: any, value: any, cb: any) => {
        console.log(value, rule);
        if (!testPwd(value)) {
          cb(
            "密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型"
          );
        } else if (formModel.pwd2 !== "") {
          formRef.value?.validateField("pwd2");
        }
        cb();
      },
      trigger: "blur",
    },
  ],
  pwd2: [
    {
      required: true,
      message: "请输入密码",
      trigger: "change",
    },
    {
      min: 6,
      max: 20,
      message: "密码长度不少于6-20位数字",
      trigger: "change",
    },
    {
      validator: (rule: any, value: any, cb: any) => {
        if (!testPwd(value))
          cb(
            "密码仅可由数字、英文字母或英文符号组成，且需包含其中至少两种类型"
          );
        else if (value !== formModel.pwd1) cb("请输入相同的密码");
        else cb();
      },
      trigger: "blur",
    },
  ],
};
</script>

<style></style>
