<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'

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

const emit = defineEmits(['update'])

const loading = ref(false)

// 表单初始值
const initialValues = computed(() => ({
	username: props.userInfo.username || '',
	nickname: props.userInfo.nickname || '',
	phone: props.userInfo.phone || '',
	email: props.userInfo.email || '',
	gender: props.userInfo.gender || 0,
	birthday: props.userInfo.birthday || null,
	bio: props.userInfo.bio || '',
}))

// 表单项配置
const formItems = [
	{
		field: 'username',
		label: '用户名',
		type: 'input',
		disabled: true,
	},
	{
		field: 'nickname',
		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' }],
	},
	{
		field: 'gender',
		label: '性别',
		type: 'radio',
		options: [
			{ label: '男', value: 1 },
			{ label: '女', value: 2 },
			{ label: '保密', value: 0 },
		],
	},
	{
		field: 'birthday',
		label: '生日',
		type: 'date',
	},
	{
		field: 'bio',
		label: '个人简介',
		type: 'textarea',
		rows: 4,
		maxLength: 200,
		showCount: true,
	},
]

// 表单提交
const handleFinish = (values) => {
	loading.value = true
	// 模拟接口请求
	setTimeout(() => {
		emit('update', values)
		message.success('保存成功')
		loading.value = false
	}, 1000)
}

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

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