<template>
  <el-dialog v-model="visible" title="修改密码" width="600px" @close="fnClose">
    <app-form-builder v-model="form" :options="options" label-width="80px" ref="formRef" :span="24" />
    <template #footer>
      <el-button type="primary" @click="fnSubmit">确认修改</el-button>
      <el-button @click="fnClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {debounce} from "throttle-debounce";
import useForm from "../../../hooks/useForm/index.js";
import { ref } from "vue";
import { postRequest } from "../../../axios/index.js";
import AppFormBuilder from "../../../components/form_builder/index.vue";
import { STRONG_PASSWORD } from "../../../regular/index.js";
import { ElDialog, ElButton } from 'element-plus'
import "element-plus/es/components/dialog/style/css";
import "element-plus/es/components/button/style/css";

const props = defineProps({
  changePasswordUrl: { type: String, required: true },
})
const emits = defineEmits(["submit"]);
const visible = defineModel("visible", { type: Boolean, required: true });
const form = ref({
  password: "",
  newPassword: "",
  newPasswordConfirm: "",
});
const { formRef, validate, reset } = useForm();
const options = [
  { key: "password", label: "旧密码", attrs: { type: "password" } },
  {
    key: "newPassword",
    label: "新密码",
    attrs: { type: "password" },
    rules: { pattern: STRONG_PASSWORD, message: "至少8个字符，包含大小写字母、数字和特殊字符", trigger: "blur" }
  },
  {
    key: "newPasswordConfirm",
    label: "确认密码",
    attrs: { type: "password" },
    rules: {
      required: true,
      validator: (_rule, value, callback) => {
        if (value === "") callback(new Error("请再次输入新密码"));
        else if (value !== form.value.newPassword) callback(new Error("两次输入密码不一致!"));
        else callback();
      },
      trigger: "blur"
    }
  },
]
const fnClose = () => {
  reset();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await validate();
    await postRequest(props.changePasswordUrl, {...form.value});
    fnClose();
    emits("submit");
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss"></style>
