<template>
  <el-dialog :model-value="showModifyDialog" title="修改密码" width="400px" @close="close()">
    <el-form :model="modifyForm" :rules="modifyRules" ref="modifyFormRef">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="modifyForm.oldPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="modifyForm.newPassword" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="modifyForm.confirmPassword" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="handleModifyPassword">确认修改</el-button>
    </template>
  </el-dialog>
</template>
  
  <script setup>
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { updatePassword } from "@/api/account";
const props = defineProps({
  showModifyDialog: { type: Boolean, default: false },
  username: { type: String, default: "" },
});
const emits = defineEmits(["close"]);
const modifyFormRef = ref();
const modifyForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});
watch(
  () => props.showModifyDialog,
  (val) => {
    if (val) {
      modifyForm.oldPassword = "";
      modifyForm.newPassword = "";
      modifyForm.confirmPassword = "";
    }
  }
);
const validateConfirmPassword = (rule, value, callback) => {
  if (value !== modifyForm.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};
const modifyRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

const handleModifyPassword = async () => {
  await modifyFormRef.value.validate();
  if (!props.username) return ElMessage.warning("账号不能为空");
  const { oldPassword, newPassword, confirmPassword } = modifyForm;
  if (oldPassword === newPassword) return ElMessage.warning("新密码不能与原密码相同");
  if (newPassword !== confirmPassword) return ElMessage.warning("两次输入密码不一致");
  const { success, message } = await updatePassword({ oldPassword, newPassword, username: props.username, corpId: import.meta.env.VITE_CORP_ID });
  if (!success) return ElMessage.error(message);
  close();
  ElMessage.success("密码修改成功");
};

function close() {
  emits("close");
}
</script>
  
  <style scoped>
</style>