<template>
  <a-typography-title :heading="6">修改密码</a-typography-title>
  <c-form
    v-model="form"
    :option="{
      columns: [
        {
          name: '旧密码',
          span: 24,
          type: 'password',
          prop: 'password',
          rules: passwordRule
        },
        {
          name: '新密码',
          span: 24,
          type: 'password',
          prop: 'newPassword',
          rules: newPasswordRule
        }
      ]
    }"
    @submit="handleSubmit"
  ></c-form>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { passwordRule, passwordValidator } from '@/rules/user-rules'
import { updatePassword } from '@/api/upms/user'

const form = ref({
  password: '',
  newPassword: ''
})

const newPasswordRule = [
  { required: true, message: '密码不能为空' },
  {
    validator: (value: string | undefined, callback: (errMsg?: string) => void) => {
      if (value === form.value.password) {
        callback('新密码不能与旧密码相同')
      } else {
        callback()
      }
    }
  },
  {
    validator: passwordValidator
  }
]
const handleSubmit = (val: any, done: Function) => {
  updatePassword(val.password, val.newPassword)
    .then(() => {
      form.value = {
        password: '',
        newPassword: ''
      }
      Message.success('修改成功')
    })
    .finally(() => done())
}
</script>
