<template>
    <a-form-model layout="vertical" style="width: 500px" :model="form" :rules="rules" ref="form">
        <a-form-model-item :label="$t('user.initialPassword')" prop="oldPassword">
            <a-input-password v-model="form.oldPassword" />
        </a-form-model-item>
        <a-form-model-item :label="$t('user.password')" prop="newPassword">
            <a-input-password v-model="form.newPassword" />
        </a-form-model-item>
        <a-form-model-item :label="$t('user.confirmPassword')" 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">
                {{ $t('user.modifyPassword') }}
            </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(this.$t('user.twoInconsistent'));
                        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(this.$t('user.modifiedSuccessfully'));
                    } catch (error) {
                        // todo
                        this.$message.error(this.$t('user.serverException'));
                    }
                    this.loading = false;
                })
                .catch(EMPTY_FUN);
        },
    },
};
</script>
