<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable @close="onReset(ruleFormRef)">
    <el-form ref="ruleFormRef" :model="ruleForm" size="large" label-width="120px">
      <!-- <el-form-item
        label="昵称"
        :rules="[
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }
        ]"
        prop="nickname"
      >
        <el-input clearable v-model="ruleForm.nickname" placeholder="请输入昵称" maxlength="10" show-word-limit />
      </el-form-item> -->

      <el-form-item
        label="原密码"
        prop="oldPassword"
        :rules="[
          {
            required: true,
            message: '请输入原密码',
            trigger: 'blur'
          }
        ]"
      >
        <el-input clearable show-password v-model="ruleForm.oldPassword" placeholder="请输入新密码" />
      </el-form-item>

      <el-form-item
        prop="password"
        label="新密码"
        :rules="[
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur'
          }
        ]"
      >
        <el-input clearable show-password v-model="ruleForm.password" placeholder="密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage, type FormInstance } from "element-plus";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";

import request from "@/api";

const router = useRouter();
const userStore = useUserStore();

const dialogVisible = ref(false);
const openDialog = () => {
  dialogVisible.value = true;
};

const ruleForm = ref({
  password: "",
  oldPassword: ""
});
const ruleFormRef = ref();

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (!valid) return;
    request.post("/archivesService/agency/update/password", ruleForm.value).then(_ => {
      ElMessage({
        type: "success",
        message: "修改成功"
      });

      // 2.清除 Token
      userStore.setToken("");

      // 3.重定向到登陆页
      router.replace(LOGIN_URL);
    });
  });
};
const onReset = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
};

defineExpose({ openDialog });
</script>
