<template>
	年龄：{{myData.children}}
	<view v-for="(item,index) in myData.children" :key="item.timer">
		<view><text v-if="index == 0">孩子年龄</text></view>
		<uni-easyinput v-model="item.age" placeholder="请输入孩子年龄" @change="onChange" />
		<button @click="handleAdd" v-if="myData.children.length == 1">+</button>
		<button @click="handleAdd"
			v-else-if="myData.children.length-1 == index && myData.children.length != 1 && myData.children.length<3">+</button>
		<button @click="handleDelete(item.timer)" v-else>-</button>
	</view>
</template>

<script setup>
	import {
		computed,
		reactive,
		watch,
		watchEffect
	} from "vue"
	import {
		useHetong
	} from "../useHetong.js"
	const {
		injectHetong
	} = useHetong();

	const data = injectHetong()

	const emits = defineEmits(['change'])

	const myData = reactive({
		children: []
	})

	watchEffect(() => {
		const list = data.hetong.qzHzNianliang && data.hetong.qzHzNianliang.split(',').map((item,index) => ({
			age: item,
			timer: new Date().getTime()+index
		}));
		myData.children = list.length ? list : [{
			age: '',
			timer: new Date().getTime()
		}]
	})

	function onChange() {
		data.hetong.qzHzNianliang = myData.children.map(item => item.age).join(',')
	}

	function handleAdd() {
		myData.children.push({
			age: '',
			timer: new Date().getTime()
		});
		data.hetong.qzHzNianliang = myData.children.map(item => item.age).join(',')
		emits('change')
	}

	function handleDelete(timer) {
		console.log('timer', timer)
		myData.children = myData.children.filter(item => item.timer != timer)
		data.hetong.qzHzNianliang = myData.children.map(item => item.age).join(',')
		emits('change')
	}
</script>

<style>
</style>