<template>
	<scForm :form-items="formItems" :initial-values="initialValues" :loading="loading" @finish="handleFinish" @reset="handleReset" />
</template>

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

const props = defineProps({
	userInfo: {
		type: Object,
		default: () => ({}),
	},
})

const emit = defineEmits(['update'])

const userStore = useUserStore()
const loading = ref(false)

// 表单初始值
const initialValues = computed(() => ({
	username: props.userInfo.username || '',
	real_name: props.userInfo.real_name || '',
	phone: props.userInfo.phone || '',
	email: props.userInfo.email || '',
}))

// 表单项配置
const formItems = [
	{
		field: 'username',
		label: '用户名',
		type: 'input',
		rules: [
			{ required: true, message: '请输入用户名', trigger: 'blur' },
			{
				min: 3,
				max: 20,
				message: '用户名长度在 3 到 20 个字符',
				trigger: 'blur',
			},
		],
	},
	{
		field: 'real_name',
		label: '真实姓名',
		type: 'input',
		required: true,
		rules: [
			{ required: true, message: '请输入真实姓名', trigger: 'blur' },
			{
				min: 2,
				max: 20,
				message: '姓名长度在 2 到 20 个字符',
				trigger: 'blur',
			},
		],
	},
	{
		field: 'phone',
		label: '手机号',
		type: 'input',
		rules: [
			{
				pattern: /^1[3-9]\d{9}$/,
				message: '请输入正确的手机号',
				trigger: 'blur',
			},
		],
	},
	{
		field: 'email',
		label: '邮箱',
		type: 'input',
		rules: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
	},
]

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

		// 获取当前用户ID
		const userId = userStore.userInfo?.id

		if (!userId) {
			throw new Error('用户信息不存在，请重新登录')
		}

		// 调用更新用户信息接口
		const res = await api.user.edit.put(userId, {
			username: values.username,
			real_name: values.real_name,
			phone: values.phone,
			email: values.email,
		})

		if (!res || res.code !== 200) {
			throw new Error(res.message || '保存失败，请重试')
		}

		// 重新获取用户信息
		const response = await api.me.get()
		if (response && response.data) {
			userStore.setUserInfo(response.data)
			emit('update', response.data)
		}

		message.success('保存成功')
	} catch (error) {
		message.error(error.message || '保存失败，请重试')
	} finally {
		loading.value = false
	}
}

// 重置表单
const handleReset = () => {
	message.info('已重置')
}
</script>

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