|
|
@@ -0,0 +1,70 @@
|
|
|
+import {editUserPassword} from '@apis';
|
|
|
+import {LOGIN_PATH} from '@routes';
|
|
|
+import {storeToRefs, useUserStore} from '@stores';
|
|
|
+import {useMutation} from '@tanstack/vue-query';
|
|
|
+import {formatValidateError} from '@utils';
|
|
|
+import {toTypedSchema} from '@vee-validate/zod';
|
|
|
+import {useMessage} from 'naive-ui';
|
|
|
+import {useForm} from 'vee-validate';
|
|
|
+import {Ref, watchEffect} from 'vue';
|
|
|
+import {useI18n} from 'vue-i18n';
|
|
|
+import {useRouter} from 'vue-router';
|
|
|
+import {object, string} from 'zod';
|
|
|
+
|
|
|
+type FromState = {
|
|
|
+ oldPassword: string;
|
|
|
+ newPassword: string;
|
|
|
+ repeatPassword: string;
|
|
|
+};
|
|
|
+
|
|
|
+export function useFormState(visible: Ref<boolean>) {
|
|
|
+ const {handleSubmit, handleReset, setFieldError} = useForm<FromState>({
|
|
|
+ initialValues: {
|
|
|
+ oldPassword: '',
|
|
|
+ newPassword: '',
|
|
|
+ repeatPassword: '',
|
|
|
+ },
|
|
|
+ validationSchema: toTypedSchema(object({
|
|
|
+ oldPassword: string(formatValidateError('home.editpasswordError.oldPassword'))
|
|
|
+ .min(1, 'home.editpasswordError.oldPassword'),
|
|
|
+ newPassword: string(formatValidateError('home.editpasswordError.newPassword'))
|
|
|
+ .min(1, 'home.editpasswordError.newPassword'),
|
|
|
+ repeatPassword: string(formatValidateError('home.editpasswordError.repeatPassword'))
|
|
|
+ .min(1, 'home.editpasswordError.repeatPassword'),
|
|
|
+ })),
|
|
|
+ });
|
|
|
+
|
|
|
+ const userStore = useUserStore();
|
|
|
+ const {user} = storeToRefs(userStore);
|
|
|
+ const message = useMessage();
|
|
|
+ const {t} = useI18n();
|
|
|
+ const {push} = useRouter();
|
|
|
+
|
|
|
+ const {mutate, isLoading} = useMutation({
|
|
|
+ mutationFn: editUserPassword,
|
|
|
+ onSuccess({msg}) {
|
|
|
+ if (msg === '200') {
|
|
|
+ message.success(t('home.editPassword.success'));
|
|
|
+ userStore.logout();
|
|
|
+ push(LOGIN_PATH);
|
|
|
+ }
|
|
|
+ },
|
|
|
+ });
|
|
|
+
|
|
|
+ const onSubmit = handleSubmit(function({
|
|
|
+ oldPassword,
|
|
|
+ newPassword,
|
|
|
+ repeatPassword,
|
|
|
+ }) {
|
|
|
+ if (newPassword !== repeatPassword)
|
|
|
+ return setFieldError('repeatPassword', 'home.editpasswordError.validatePassword');
|
|
|
+
|
|
|
+ mutate({id: user.value.id, password: oldPassword, newPassword});
|
|
|
+ });
|
|
|
+
|
|
|
+ watchEffect(function() {
|
|
|
+ visible.value && handleReset();
|
|
|
+ });
|
|
|
+
|
|
|
+ return [isLoading, onSubmit] as const;
|
|
|
+}
|