<template>
  <el-card>
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
    >
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="username" disabled/>
      </el-form-item>
      <el-form-item label="原密码：" prop="userPassword">
        <el-input v-model="form.userPassword" type="password" show-password/>
      </el-form-item>
      <el-form-item label="新密码：" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" show-password/>
      </el-form-item>
      <el-form-item label="确认新密码：" prop="checkNewPassword">
        <el-input v-model="form.checkNewPassword" type="password" show-password/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确认修改
        </el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script setup>
import {ref} from 'vue'
import axios from "@/util/axios";
import {ElMessage} from "element-plus";


import { useStore } from 'vuex'
const store=useStore();
const   username=ref()
const password=ref()

const form = ref({
  userPassword: "",
  newPassword: "",
  checkNewPassword: ""
})
const rules = ref({
  newPassword: [
    {
      required: true,
      message: '请输入新密码'
    }
  ],
  newPassword2: [
    {
      required: true,
      message: '请输入确认新密码'
    }
  ],
})
const formRef = ref(null);
const initFormData = () => {
  let userInfoJson = window.sessionStorage.getItem("USER_LOGIN_STATE");
  //console.log(JSON.parse(userInfoJson).username)
   username.value = JSON.parse(userInfoJson).username;
  let pwd = window.sessionStorage.getItem("token");
  password.value=JSON.parse(pwd).userPassword;
  //console.log(JSON.parse(pwd).userPassword)
 // form.value.userPassword = JSON.parse(pwd).userPassword;
 // console.log(form.value.userPassword)
}
initFormData();
const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      //console.log("success")
      if (form.value.userPassword !== password.value) {
        ElMessage.error("原密码错误！");
      } else if (form.value.newPassword !== form.value.checkNewPassword) {

        ElMessage.error("确认新密码错误！");
      } else {
        try {
          let result = await axios.post("user/password/update", form.value)
          let data = result.data;
          console.log(result.request)
          if (data.code == 0) {
            ElMessage.success("密码修改成功，重新登录后生效！");
            formRef.value.resetFields();
          } else {
            ElMessage.error(data.description);
          }
        } catch (err) {
          console.log(err)
          ElMessage.error("系统运行出错，请联系管理员！");
        }
      }
    } else {
      console.log("fail")
      return false
    }
     store.dispatch('logout')
    let res= await axios.post("/user/logout")
    console.log(res)
  })

}
</script>
<style lang="scss" scoped>
.el-input {
  width: 300px;
}
</style>