<template>
    <ElDialog
        class="!w-10/12 max-w-lg"
        title="修改密码"
        :model-value="modelValue"
        @update:model-value="setVisible"
        @open="onOpen"
    >
        <ElForm :model="model" :rules="rules" ref="formEl" label-position="top">
            <ElFormItem label="新密码" prop="password">
                <ElInput v-model="model.password" show-password></ElInput>
            </ElFormItem>
            <ElFormItem label="确认密码" prop="repeat">
                <ElInput v-model="model.repeat" show-password></ElInput>
            </ElFormItem>
        </ElForm>
        <template #footer>
            <ElButton @click="setVisible(false)">取消</ElButton>
            <ElButton type="primary" @click="submit" :loading="loading">确定</ElButton>
        </template>
    </ElDialog>
</template>
<script setup>
import { ref } from 'vue'
import { http } from '@/plugins/http'
import { ElMessage } from 'element-plus'
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['update:modelValue'])
const model = ref({
    password: '',
    repeat: ''
})
const formEl = ref(null)
const rules = {
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    repeat: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== model.value.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}
function setVisible(val) {
    emit('update:modelValue', val)
}
const loading = ref(false)
function submit() {
    formEl.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                await http.post('/users/updatePassword', { password: model.value.password })
                setVisible(false)
                ElMessage.success('修改成功')
            } catch (e) {
                ElMessage.error(e.message)
            } finally {
                loading.value = false
            }
        }
    })
}
function onOpen() {
    if (formEl.value) {
        formEl.value.clearValidate()
    }
}
</script>
