<template>
    <a-form-model layout="vertical" style="width: 500px" :model="form" :rules="rules" ref="form">
        <a-form-model-item label="原始密码" prop="oldPassword">
            <a-input-password v-model="form.oldPassword" />
        </a-form-model-item>
        <a-form-model-item label="新密码" prop="newPassword">
            <a-input-password v-model="form.newPassword" />
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="confirmPassword">
            <a-input-password v-model="form.confirmPassword" />
        </a-form-model-item>
        <a-form-model-item>
            <a-button type="primary" @click="modifyPassword" :loading="loading">修改密码</a-button>
        </a-form-model-item>
    </a-form-model>
</template>

<script>
import { modifyPasswordApi } from '@/api';
import { EMPTY_FUN } from '@/utils';
import md5 from 'crypto-js/md5';

export default {
    data: vm => ({
        form: {
            newPassword: '',
            oldPassword: '',
            confirmPassword: '',
        },
        rules: {
            newPassword: [{ required: true }],
            oldPassword: [{ required: true }],
            confirmPassword: [
                { required: true },
                {
                    validator(rule, value, callback) {
                        if (value !== vm.form.newPassword) callback('两次密码不一致');
                        callback();
                    },
                },
            ],
        },
        loading: false,
    }),
    methods: {
        modifyPassword() {
            this.$refs.form
                .validate()
                .then(async () => {
                    try {
                        this.loading = true;
                        await modifyPasswordApi({
                            newPassword: md5(this.form.newPassword).toString(),
                            oldPassword: md5(this.form.oldPassword).toString(),
                        });
                        this.$message.success('修改成功');
                    } catch (error) {
                        // todo
                        this.$message.error('服务器异常');
                    }
                    this.loading = false;
                })
                .catch(EMPTY_FUN);
        },
    },
};
</script>
