<template>
  <el-dialog v-model="visible" append-to-body title="修改密码" width="500px" draggable>
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="formData" @submit.enter.prevent="handleSubmit">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" type="password" placeholder="请填写原密码" show-password clearable />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="formData.password" type="password" placeholder="请填写新密码" show-password clearable />
      </el-form-item>
      <el-form-item label="确认新密码" prop="newPwdConfirm">
        <el-input v-model="formData.newPwdConfirm" type="password" placeholder="请填写确认新密码" show-password clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PasswordDialog">
import UserApi from '@/api/module/system/user'
import { LOGIN_URL } from '@/constants'
import { ResultEnum } from '@/enums/HttpEnum'
import router from '@/router'
import { useUserStore } from '@/stores'
const validateOldNewPassword = (rule: any, value: any, callback: (error?: string | Error) => void) => {
  if (value === formData.value.oldPassword) {
    callback(new Error('旧密码和新密码不能相同'))
    return
  }
  callback()
}

const validateConfirmPassword = (rule: any, value: any, callback: (error?: string | Error) => void) => {
  if (value !== formData.value.password) {
    callback(new Error('新密码和确认密码不一致'))
    return
  }
  callback()
}

const rules = reactive({
  oldPassword: [{ required: true, message: '请填写原密码' }],
  password: [
    { required: true, message: '请填写新密码' },
    { validator: validateOldNewPassword, trigger: 'blur' }
  ],
  newPwdConfirm: [
    { required: true, message: '请填写确认新密码' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

const formData = ref({
  oldPassword: '',
  password: '',
  newPwdConfirm: ''
})

const ruleFormRef = ref()
const handleSubmit = () => {
  ruleFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      const { code } = await UserApi.modifyPassword({ oldPassword: formData.value.oldPassword, password: formData.value.password })
      if (code === ResultEnum.SUCCESS) {
        ElMessage.success({ message: `修改密码成功，请重新登录！` })
        visible.value = false
        useUserStore().clear()
        router.replace(LOGIN_URL)
      }
    } catch (error) {
      console.log(error)
    }
  })
}

const visible = ref(false)
const openDialog = () => {
  visible.value = true
  formData.value = {
    oldPassword: '',
    password: '',
    newPwdConfirm: ''
  }
}

defineExpose({ openDialog })
</script>
