<template>
	<el-form ref="formRef" :model="form" :rules="rules" label-width="auto" style="max-width: 600px">
		<el-form-item label="Activity name" prop="name">
			<el-input v-model="form.name" />
		</el-form-item>
		<el-form-item label="Activity zone" prop="region">
			<el-select v-model="form.region" placeholder="please select your zone">
				<el-option label="1" value="shanghai" />
				<el-option label="2" value="beijing" />
			</el-select>
		</el-form-item>
		<el-form-item label="Instant delivery">
			<el-switch v-model="form.delivery" />
		</el-form-item>
		<el-form-item label="Activity type">
			<el-checkbox-group v-model="form.type">
				<el-checkbox label="1" name="type"> Online activities </el-checkbox>
				<el-checkbox label="2" name="type"> Promotion activities </el-checkbox>
				<el-checkbox label="3" name="type"> Offline activities </el-checkbox>
				<el-checkbox label="4" name="type"> Simple brand exposure </el-checkbox>
			</el-checkbox-group>
		</el-form-item>
		<el-form-item label="Resources">
			<el-radio-group v-model="form.resource">
				<el-radio label="Sponsor">Sponsor</el-radio>
				<el-radio label="Venue">Venue</el-radio>
			</el-radio-group>
		</el-form-item>
		<el-form-item label="Activity form">
			<el-input v-model="form.desc" type="textarea" />
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { ref, defineExpose, inject, watch } from 'vue'

const formRef = ref(null)
const myEmit = defineEmits(['form-valid'])
/*获取父组件传递过来的数据，调整完毕，传给父组件实现双向绑定 start */
const dyVueForm = inject('dyVueForm')
const form = ref(dyVueForm.value.dy || {})

watch(
	() => dyVueForm.value.dy,
	vl => (form.value = vl)
)
watch(
	() => form.value,
	v => (dyVueForm.value.dy = v)
)
/*获取父组件传递过来的数据，调整完毕，传给父组件实现双向绑定 start*/

const rules = ref({
	name: [
		{
			required: true,
			message: '请填写',
			trigger: ['submit']
		}
	],
	region: [
		{
			required: true,
			message: '请选择',
			trigger: ['submit']
		}
	]
})

/**
 * 当前表单如果没有必填校验，则可以去掉校验规则
 * 直接通过myEmit('form-valid', form.value)将值传给父组件
 */
const validateForm = () => {
	const formValidate = formRef.value
	formValidate.validate((valid: any) => {
		if (!valid) {
			return false
		}
		myEmit('form-valid')
	})
}

const getComponentData = () => {
	return form.value
}

defineExpose({
	// 把数据暴露给父节点使用
	validateForm,
	getComponentData
})
</script>
