<template>
  <div class="personalCenter">
    <el-card style="height: 100%">
      <h3>修改密码</h3>
      <div style="width: 50%; padding-top: 2em">
        <el-form :model="form" label-width="120px">
          <el-form-item label="旧密码">
            <el-input type="password" v-model="form.oldPwd" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input type="password" v-model="form.newPwd" />
          </el-form-item>
          <el-form-item label="确认新密码">
            <el-input type="password" v-model="form.isNewPwd" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">确定修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import { changePwdApi } from '@/api/index';
import sha256 from 'sha256';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();
document.title = '修改密码';
const form = reactive({
  oldPwd: '',
  newPwd: '',
  isNewPwd: '',
});

const onSubmit = () => {
  if (!form.oldPwd) return ElMessage.error('请输入旧密码');
  if (!form.isNewPwd || !form.newPwd) return ElMessage.error('请输入新密码');
  if (form.isNewPwd !== form.newPwd) return ElMessage.error('两次新密码不一致');
  changePwdApi({
    oldPwd: sha256(form.oldPwd),
    pwd: sha256(form.newPwd),
  }).then(() => {
    form.oldPwd = '';
    form.newPwd = '';
    form.isNewPwd = '';
    ElMessage({
      message: '修改成功',
      type: 'success',
      onClose(){
        router.go(-1);
      }
    });
  });
};
</script>

<style scoped>
.personalCenter {
  padding: 1em;
  height: 100%;
}
</style>
