<script lang="ts" setup>
import { FormInst, FormItemRule, FormRules } from "naive-ui";
import { changePwdApi } from "@/api/changePwd";
const modelFormRef = $ref<FormInst | null>(null);

type FormModel = {
  password: string;
  newPassword: string;
  renewPassword: string;
};
let formModel: FormModel = $ref({
  password: "",
  newPassword: "",
  renewPassword: "",
});
const password = {
  required: true,
  pattern: /^[a-zA-Z0-9]{6,18}$/,
  message: "密码只能由数字、字母组成，长度6-18个字符",
  trigger: "input",
};
const equalToOldPswd = (rule: FormItemRule, value: string): Error | boolean => {
  if (value && formModel.password && value === formModel.password) {
    return new Error("新旧密码不可以相同");
  }
  return true;
};
const equalToPswd = (rule: FormItemRule, value: string): Error | boolean => {
  if (value && formModel.newPassword && value !== formModel.newPassword) {
    return new Error("两次输入的密码不一致");
  }
  return true;
};
const formRules: FormRules = {
  password: [password],
  newPassword: [
    password,
    {
      validator: equalToOldPswd,
      trigger: "input",
    },
  ],
  renewPassword: [password, { validator: equalToPswd, trigger: "input" }],
};
async function inputChange() {
  await modelFormRef?.validate();
}

async function toSubmit() {
  const unvalid = await modelFormRef?.validate().catch(() => true);
  if (unvalid) return;

  await changePwdApi(formModel.password, formModel.newPassword);
  $message.success("修改成功！");
}
</script>

<template>
  <div class="part-box pwd-box">
    <div class="pwd-box-content">
      <n-form
        ref="modelFormRef"
        :model="formModel"
        :rules="formRules"
        :showLabel="false"
        size="medium"
      >
        <n-form-item label="旧秘密" path="password">
          <n-input
            v-model:value="formModel.password"
            type="password"
            placeholder="请输入旧秘密"
            clearable
            @change="inputChange"
          />
        </n-form-item>
        <n-form-item label="新密码" path="newPassword">
          <n-input
            v-model:value="formModel.newPassword"
            type="password"
            placeholder="请输入新密码（6到18位的数字或字母）"
            clearable
            @change="inputChange"
          />
        </n-form-item>
        <n-form-item label="新密码" path="renewPassword">
          <n-input
            v-model:value="formModel.renewPassword"
            type="password"
            placeholder="请再次输入新密码"
            clearable
            @change="inputChange"
          />
        </n-form-item>
        <n-form-item>
          <n-button type="success" @click="toSubmit"> 保存 </n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<style scoped>
.pwd-box-content {
  max-width: 500px;
  min-width: 200px;
}
</style>
