<template>
    <div>
        <a-modal v-model:visible="visible" title="修改密码" @ok="handleOk" :footer="null">
            <a-form :model="formState" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" autocomplete="off" @finish="onFinish" @finishFailed="onFinishFailed">
                <a-form-item label="旧密码" name="password" :rules="[{ required: true, message: '请输入你的原密码' }]">
                    <a-input-password v-model:value="formState.password" />
                </a-form-item>

                <a-form-item label="新密码" name="newPassword" :rules="[{ required: true, message: '请输入新密码' }]">
                    <a-input-password v-model:value="formState.newPassword" />
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" html-type="submit" @click="confirmPassword">确定</a-button>
                    <a-button type="primary" style="margin-left:10px;" html-type="submit" @click="handleOk">取消</a-button>
                </a-form-item>
            </a-form>
        </a-modal>

    </div>
</template>

<script setup>
import { editPassword } from '@/api/user';
import { useStore } from '@/store/index.js'
import { message } from 'ant-design-vue';
import router from '../../../router';
const userStore = useStore();
const visible = ref(false);
const showModal = () => {
    visible.value = true;
};
const handleOk = e => {
    console.log(e);
    visible.value = false;
};
const formState = reactive({
    password: '',
    newPassword: ''
});
const onFinish = values => {
    // console.log('Success:', values);
};
const onFinishFailed = errorInfo => {
    // console.log('Failed:', errorInfo);
};

//提交密码
const confirmPassword = () => {
    const params = {
        userId: userStore.userInfo.id,
        oldPassword: btoa(encodeURI(formState.password)),
        newPassword: btoa(encodeURI(formState.newPassword))
    };
    editPassword(params).then(res => {
        if (res.code == '9000') {
            message.success('密码修改成功，请重新登录！');
            localStorage.removeItem('user')
            userStore.token = null;
            router.push('/login');
        }
    }).catch(error => {
        message.error(error.message);
    })
}

defineExpose({
    showModal
})
</script>