<template>
  <a-dialog v-model="dialogVisible" title="修改密码" @submit="formSubmit" @closed="formClosed">
    <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24"> </a-form>
  </a-dialog>
</template>

<script setup lang="ts">
import { FormConfigType } from '@/components/AForm/type'
import { editPwdApi } from '@/api/system/auth'
import { StrAnyObj } from '@/typings'

const dialogVisible = ref(false)
const formRef = ref()
const formData = ref<StrAnyObj>({})

const formConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'oldPwd',
    label: '原密码',
    itemType: 'password',
    showPassword: true,
    rule: [
      { required: true, message: '原密码不能为空', trigger: 'blur' },
      { min: 6, max: 30, message: '密码长度必须在6到30个字符之间', trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    prop: 'newPwd',
    label: '新密码',
    itemType: 'password',
    showPassword: true,
    rule: [
      { required: true, message: '新密码不能为空', trigger: 'blur' },
      { min: 6, max: 30, message: '密码长度必须在6到30个字符之间', trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    prop: 'checkPwd',
    label: '确认密码',
    itemType: 'password',
    showPassword: true,
    rule: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      { validator: validatePwd, trigger: 'blur' }
    ]
  }
]

defineExpose({ openDialog })

function openDialog() {
  dialogVisible.value = true
}

function validatePwd(rule: any, value: any, callback: any) {
  if (formData.value.newPwd === formData.value.checkPwd) {
    callback()
  } else {
    callback(new Error('新密码与确认密码必须相同'))
  }
}

function formSubmit() {
  formRef.value.validate(() => {
    editPwdApi(formData.value).then(() => {
      ElMessage.success('修改密码成功')
      dialogVisible.value = false
    })
  })
}

function formClosed() {
  formRef.value.resetFields()
}
</script>
