<template>
	<scForm :form-items="formItems" :initial-values="initialValues" :loading="loading" submit-text="修改密码" @finish="handleFinish" @reset="handleReset" />
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import scForm from '@/components/scForm/index.vue'
import api from '@/api/auth'

const emit = defineEmits(['success'])
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)

// 表单初始值
const initialValues = ref({
	old_password: '',
	password: '',
	password_confirmation: '',
})

// 表单项配置
const formItems = [
	{
		field: 'old_password',
		label: '原密码',
		type: 'password',
		required: true,
		rules: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
	},
	{
		field: 'password',
		label: '新密码',
		type: 'password',
		required: true,
		rules: [
			{ required: true, message: '请输入新密码', trigger: 'blur' },
			{
				min: 6,
				max: 20,
				message: '密码长度在 6 到 20 个字符',
				trigger: 'blur',
			},
		],
	},
	{
		field: 'password_confirmation',
		label: '确认密码',
		type: 'password',
		required: true,
		dependencies: ['password'],
		rules: [
			{ required: true, message: '请再次输入新密码', trigger: 'blur' },
			{
				validator: (_, value) => {
					if (!value || !initialValues.value.password) {
						return Promise.resolve()
					}
					if (value !== initialValues.value.password) {
						return Promise.reject('两次输入的密码不一致')
					}
					return Promise.resolve()
				},
				trigger: 'blur',
			},
		],
	},
]

// 表单提交
const handleFinish = async (values) => {
	try {
		loading.value = true

		// 调用修改密码接口
		const res = await api.changePassword.post({
			old_password: values.old_password,
			password: values.password,
			password_confirmation: values.password_confirmation,
		})

		if (!res || res.code !== 200) {
			throw new Error(res.message || '密码修改失败，请重试')
		}

		message.success('密码修改成功，请重新登录')

		// 清除用户信息和token
		userStore.logout()

		// 延迟跳转到登录页
		setTimeout(() => {
			router.push('/login')
		}, 1500)

		emit('success')
		handleReset()
	} catch (error) {
		message.error(error.message || '密码修改失败，请重试')
	} finally {
		loading.value = false
	}
}

// 重置表单
const handleReset = () => {
	initialValues.value = {
		old_password: '',
		password: '',
		password_confirmation: '',
	}
}
</script>

<style scoped lang="scss"></style>
