<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <span>新密码：<el-input v-model="form.password" placeholder="请输入新密码" /></span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref } from 'vue';
  import { editPassword } from '@/api/user';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/stores/modules/user';
  const { userInfo } = useUserStore();
  const userStore = useUserStore();
  import { LOGIN_URL } from '@/config';
  const router = useRouter();

  const form = ref({
    password: '',
  });
  const dialogVisible = ref(false);
  const openDialog = () => {
    dialogVisible.value = true;
  };
  const submitForm = async () => {
    editPassword({
      id: userInfo.id,
      password: form.value.password,
    }).then(async (res) => {
      if (res.success) {
        ElMessage({
          type: 'success',
          message: '修改密码成功！',
          plain: true,
        });
        dialogVisible.value = false;
        await userStore.logout();

        // 重定向到登陆页
        router.replace(LOGIN_URL);
      }
    });
  };

  defineExpose({ openDialog });
</script>
